// ==UserScript==
// @name 学习通刷课助手
// @namespace http://tampermonkey.net/
// @version 1.6.2
// @description 学习通视频自动播放+自动答题一站式助手
// @author 叶屿
// @license GPL3
// @antifeature payment 题库答题功能需要验证码(免费)或激活码(付费),视频播放等基础功能完全免费
// @match *://*.chaoxing.com/*
// @match *://chaoxing.com/*
// @match *://*.xuexitong.com/*
// @match *://xuexitong.com/*
// @exclude *://*.chaoxing.com/ananas/modules/pdf/*
// @exclude *://*.chaoxing.com/ananas/modules/ppt/*
// @exclude *://*.chaoxing.com/ananas/modules/doc/*
// @exclude *://*.chaoxing.com/ananas/modules/book/*
// @exclude *://*.chaoxing.com/ananas/modules/audio/*
// @exclude *://*.xuexitong.com/ananas/modules/pdf/*
// @exclude *://*.xuexitong.com/ananas/modules/ppt/*
// @exclude *://*.xuexitong.com/ananas/modules/doc/*
// @exclude *://*.xuexitong.com/ananas/modules/book/*
// @exclude *://*.xuexitong.com/ananas/modules/audio/*
// @run-at document-end
// @icon https://www.chaoxing.com/favicon.ico
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_getResourceText
// @grant unsafeWindow
// @connect *.chaoxing.com
// @connect *.xuexitong.com
// @connect 103.236.88.53
// @connect open.bigmodel.cn
// @connect ark.cn-beijing.volces.com
// @connect api.deepseek.com
// @connect *
// @connect chizhu-dl.github.io
// @require https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js
// @require https://unpkg.com/tesseract.js@v2.1.0/dist/tesseract.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js
// @require https://cdn.jsdelivr.net/combine/gh/photopea/Typr.js@15aa12ffa6cf39e8788562ea4af65b42317375fb/src/Typr.min.js,gh/photopea/Typr.js@f4fcdeb8014edc75ab7296bd85ac9cde8cb30489/src/Typr.U.min.js
// @resource fontTable http://103.236.88.53:23123/index.php?s=/api/font/resource&name=chaoxing-table&v=a7f0d85f12bc21094a976381e3e10c06c06af4c97bb26ca70dfefb8c0e10891f
// @grant GM_setClipboard
// @grant GM_info
// @grant GM_registerMenuCommand
// @grant GM_openInTab
// ==/UserScript==
// 请求统一收尾:取消和超时都结算等待方,迟到回包不再触发业务回调。
const CXRequests = (() => {
const active = new Set();
const generations = new Map();
let readTaskGroup = () => 'ui';
function request(options, group = 'ui') {
let settled = false, handle = null, timer = null;
const timeout = Number.isFinite(Number(options.timeout)) && Number(options.timeout) > 0
? Math.min(Number(options.timeout), 120000) : 25000;
const entry = { group, abort: () => stop('onabort', { aborted: true, error: '请求已取消' }) };
function finish(kind, response) {
if (settled) return;
settled = true;
clearTimeout(timer);
active.delete(entry);
const callback = options[kind] || (kind === 'onabort' || kind === 'ontimeout' ? options.onerror : null);
try { if (callback) callback(response); }
catch (_) {
// 回调自身异常也必须结算其 Promise;不回显响应或凭据。
if (kind !== 'onerror') {
try { options.onerror?.({ error: '接口响应处理失败', callbackError: true }); } catch (_) {}
}
}
}
function stop(kind, response) {
if (settled) return;
try { finish(kind, response); }
finally { try { handle?.abort(); } catch (_) {} }
}
active.add(entry);
timer = setTimeout(() => stop('ontimeout', { timedOut: true, error: '请求超时,处理结果需确认' }), timeout);
try {
handle = GM_xmlhttpRequest({
...options, timeout,
onload: response => finish('onload', response),
onerror: response => finish('onerror', response),
ontimeout: response => stop('ontimeout', response),
onabort: response => finish('onabort', response),
onprogress: response => { if (!settled) options.onprogress?.(response); }
});
if (settled) { try { handle?.abort(); } catch (_) {} }
} catch (_) { finish('onerror', { error: '请求无法发出' }); }
return { abort: entry.abort };
}
function cancelGroup(group) {
generations.set(group, (generations.get(group) || 0) + 1);
for (const entry of [...active]) if (entry.group === group) {
try { entry.abort(); } catch (_) {}
}
}
function cancelAll() {
for (const group of new Set(['ui', 'answer', 'video', ...generations.keys(), ...[...active].map(entry => entry.group)])) {
generations.set(group, (generations.get(group) || 0) + 1);
}
for (const entry of [...active]) { try { entry.abort(); } catch (_) {} }
}
return {
request, cancelGroup, cancelAll,
taskRequest: options => request(options, readTaskGroup()),
capture(group = readTaskGroup()) {
const generation = generations.get(group) || 0;
if (!generations.has(group)) generations.set(group, generation);
return () => (generations.get(group) || 0) === generation;
},
taskGroup: () => readTaskGroup(),
setTaskGroupReader(reader) { readTaskGroup = reader; },
readJSON(response) {
const status = Number(response?.status);
let value;
try { value = JSON.parse(response?.responseText || ''); } catch (_) {}
const message = status === 429 ? '请求过于频繁,请稍后再试' :
typeof value?.msg === 'string' ? value.msg.slice(0, 300) : '接口响应无效,请稍后核对结果';
if (!Number.isInteger(status) || status < 200 || status >= 300 ||
!value || typeof value !== 'object' || Array.isArray(value) || value.code !== 1 ||
!value.data || typeof value.data !== 'object' || Array.isArray(value.data)) {
throw Object.assign(new Error(message), { status, businessCode: value?.code });
}
return value.data;
}
};
})();
// Included only in generated candidates; the supplied original clients stay untouched.
const __scriptAnnouncementV2 = (() => {
'use strict';
const service = "http://103.236.88.53:23123";
const scriptSlug = "chaoxing";
const isVideo = false;
const imageAttribute = 'data-script-announcement-image';
const allowedImageTypes = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
const objectUrls = new Set();
const pendingImages = new WeakSet();
const activeRequests = new Set();
let leaving = false;
function safeHttp(raw) {
if (typeof raw !== 'string' || /[\u0000-\u0020\u007f\\]/.test(raw)) return '';
try {
const url = new URL(raw, service + '/');
return /^https?:$/.test(url.protocol) && !url.username && !url.password ? url.href : '';
} catch (_) { return ''; }
}
function safeInvitation(raw) {
const value = safeHttp(raw);
if (!value) return '';
const url = new URL(value);
return url.protocol === 'https:' && !url.port && ['qm.qq.com','jq.qq.com','qun.qq.com'].includes(url.hostname) ? url.href : '';
}
function groupInfo(data) {
const group = typeof data.qq_group === 'string' && /^[1-9][0-9]{4,11}$/.test(data.qq_group) ? data.qq_group : '';
const invitation = safeInvitation(data.qq_join_url);
const scheme = group ? 'mqqapi://card/show_pslcard?src_type=internal&version=1&uin=' + group + '&card_type=group&source=qrcode' : '';
return {group, invitation, scheme};
}
function prepareImage(image, raw) {
const url = safeHttp(raw);
if (url) image.setAttribute(imageAttribute, url);
}
function hydrateImages(container) {
if (leaving) return;
for (const image of container.querySelectorAll('img[' + imageAttribute + ']')) {
if (pendingImages.has(image)) continue;
pendingImages.add(image);
const url = safeHttp(image.getAttribute(imageAttribute));
if (!url) continue;
image.referrerPolicy = 'no-referrer';
if (new URL(url).protocol === 'https:' || location.protocol !== 'https:') { image.src = url; continue; }
if (new URL(url).origin !== new URL(service).origin) { image.alt = '外部HTTP图片请改用HTTPS地址'; continue; }
// Uploaded images on a temporary HTTP IP endpoint cannot be inserted into
// an HTTPS course page directly. The userscript's granted transport loads
// raster bytes, which are displayed through an inert object URL instead.
if (typeof GM_xmlhttpRequest !== 'function') { image.alt = '公告图片需更新脚本或使用HTTPS服务'; continue; }
let request, settled = false;
const finish = () => { settled = true; activeRequests.delete(request); };
try {
request = CXRequests.request({
method:'GET', url, responseType:'blob', timeout:15000, anonymous:true,
onload(response) {
finish();
if (leaving) return;
const blob = response.response;
const finalUrl = response.finalUrl ? safeHttp(response.finalUrl) : url;
if (!finalUrl || new URL(finalUrl).origin !== new URL(service).origin || response.status < 200 || response.status >= 300 || !blob || !allowedImageTypes.has(String(blob.type || '').split(';',1)[0].toLowerCase()) || blob.size > 5 * 1024 * 1024) {
image.alt = '公告图片加载失败'; return;
}
try {
const objectUrl = URL.createObjectURL(blob);
objectUrls.add(objectUrl);
const release = () => { URL.revokeObjectURL(objectUrl); objectUrls.delete(objectUrl); };
image.addEventListener('load', release, {once:true});
image.addEventListener('error', release, {once:true});
image.src = objectUrl;
} catch (_) { image.alt = '公告图片加载失败'; }
},
onerror() { finish(); image.alt = '公告图片加载失败'; },
ontimeout() { finish(); image.alt = '公告图片加载超时'; },
onabort() { finish(); }
});
if (!settled && request && typeof request.abort === 'function') activeRequests.add(request);
} catch (_) { image.alt = '公告图片加载失败'; }
}
}
function enhance(container, data, loadImages = true) {
if (!container || !data) return;
if (loadImages) hydrateImages(container);
container.querySelector('[data-script-announcement-group]')?.remove();
const {group, invitation, scheme} = groupInfo(data);
if (!group && !invitation) return;
const doc = container.ownerDocument;
const row = doc.createElement('div');
row.setAttribute('data-script-announcement-group','1');
row.style.cssText = 'display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-top:6px;font:inherit;line-height:1.5;';
const link = doc.createElement('a');
link.href = invitation || scheme;
link.textContent = group ? 'QQ群:' + group : '加入QQ群';
if (invitation) { link.target = '_blank'; link.rel = 'noopener noreferrer'; }
link.style.cssText = 'display:inline-block;padding:2px 7px;border:1px solid #94a3b8;border-radius:5px;color:#1d4ed8;background:#fff;text-decoration:underline;font:inherit;';
link.setAttribute('aria-label', group ? '打开QQ群 ' + group + (invitation ? ' 的官方邀请链接' : ' 的群资料,需要QQ客户端') : '打开QQ群官方邀请链接');
row.appendChild(link);
if (group) {
const copy = doc.createElement('button');
copy.type = 'button'; copy.textContent = '复制群号';
copy.style.cssText = 'padding:2px 7px;border:1px solid #94a3b8;border-radius:5px;background:#fff;color:#334155;cursor:pointer;font:inherit;';
const status = doc.createElement('span'); status.setAttribute('role','status');
copy.addEventListener('click', async () => {
try {
if (typeof GM_setClipboard === 'function') { GM_setClipboard(group, 'text'); }
else if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(group); }
else { throw new Error('clipboard'); }
status.textContent = '群号已复制';
} catch (_) { status.textContent = '请手动复制群号:' + group; }
});
row.append(copy, status);
}
if (!invitation) {
const hint = doc.createElement('small'); hint.textContent = '点击群号尝试打开QQ群资料,能否加群由QQ和群设置决定。';
hint.style.cssText = 'flex-basis:100%;color:inherit;font-size:11px;'; row.appendChild(hint);
}
container.appendChild(row);
}
function fetchVideoAnnouncement() {
if (!isVideo || typeof GM_xmlhttpRequest !== 'function' || window.top !== window.self) return;
try {
CXRequests.request({
method:'GET', url:service + '/index.php?s=/admin/unified_manage/scriptannouncementapi&script_id=' + encodeURIComponent(scriptSlug), timeout:8000,
onload(response) {
try {
if (response.status < 200 || response.status >= 300) return;
const result = JSON.parse(response.responseText);
const data = result.data;
if (Number(result.code) !== 1 || !data || ![true,1,'1'].includes(data.enabled)) return;
const existing = document.getElementById('script-video-announcement');
if (existing) return;
// A collapsed, closeable panel does not cover course controls or
// display an image unsolicited. The user opens the announcement.
const root = document.createElement('details'); root.id = 'script-video-announcement';
root.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:2147483000;width:min(320px,calc(100vw - 24px));box-sizing:border-box;border:1px solid #cbd5e1;border-radius:8px;background:#fff;color:#1e293b;font:13px/1.6 system-ui,sans-serif;box-shadow:0 4px 16px #0002;';
const summary = document.createElement('summary');
summary.textContent = '脚本公告:' + String(data.title || '公告').slice(0,180);
summary.style.cssText = 'cursor:pointer;padding:8px 10px;overflow-wrap:anywhere;';
const content = document.createElement('div');
content.style.cssText = 'padding:0 10px 10px;max-height:50vh;overflow:auto;overflow-wrap:anywhere;';
const text = document.createElement('p'); text.textContent = String(data.content || ''); text.style.whiteSpace = 'pre-wrap'; content.appendChild(text);
const images = Array.isArray(data.images) ? data.images : data.image_url ? [data.image_url] : [];
for (const raw of [...new Set(images)].slice(0,12)) {
const url = safeHttp(raw); if (!url) continue;
const link = document.createElement('a'); link.href=url; link.target='_blank'; link.rel='noopener noreferrer';
link.setAttribute('aria-label','查看公告原图');
const image = document.createElement('img'); image.alt='公告图片'; image.loading='lazy';
image.style.cssText='display:block;max-width:100%;max-height:220px;object-fit:contain;margin:8px auto;';
prepareImage(image,url); link.appendChild(image); content.appendChild(link);
}
const close = document.createElement('button'); close.type='button'; close.textContent='关闭公告';
close.style.cssText='margin-top:8px;padding:4px 8px;border:1px solid #94a3b8;border-radius:5px;background:#fff;color:#334155;font:inherit;cursor:pointer;';
close.addEventListener('click',()=>root.remove());
root.append(summary,content); enhance(content,data,false); content.appendChild(close);
root.addEventListener('toggle',()=>{if(root.open)hydrateImages(content);});
(document.body || document.documentElement).appendChild(root);
} catch (_) { /* Announcement failure must not affect the video tool. */ }
}
});
} catch (_) {}
}
if (isVideo) {
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded',fetchVideoAnnouncement,{once:true});
else fetchVideoAnnouncement();
}
window.addEventListener('pagehide', event => {
if (event.persisted) return;
leaving=true;
for (const request of activeRequests) { try { request.abort(); } catch (_) {} }
activeRequests.clear();
for (const url of objectUrls) URL.revokeObjectURL(url);
objectUrls.clear();
});
return {prepareImage, enhance};
})();
// Included in generated candidates only. Public policy stays in memory.
const __scriptVerificationV1 = (() => {
'use strict';
const service = "http://103.236.88.53:23123";
const profile = "chaoxing";
const scopes = ['free-answer', 'ai-unlock', 'video-trial'];
const listeners = new Set();
const documents = new Map();
const imageStates = new WeakMap();
const sessionCache = new Map();
const sessionRequests = new Map();
let state = null, fetchedAt = 0, maxAge = 60000, pending = null, stopped = false, scanTimer;
const now = () => Date.now();
const fresh = () => fetchedAt > 0 && now() >= fetchedAt && now() - fetchedAt < maxAge;
const snapshot = () => fresh() && state ? state : { scopes: Object.fromEntries(scopes.map(key => [key, true])), qrcode_url: '' };
function safeUrl(raw) {
if (typeof raw !== 'string' || !raw || raw.length > 2048 || /[\u0000-\u0020\u007f\\]/.test(raw)) return '';
try {
const url = new URL(raw, service + '/');
return /^https?:$/.test(url.protocol) && !url.username && !url.password ? url.href : '';
} catch (_) { return ''; }
}
function notify() {
scheduleScan();
for (const listener of listeners) { try { listener(); } catch (error) { console.warn('[验证码配置]', error); } }
}
function refresh(force = false) {
if (stopped) return Promise.resolve(snapshot());
if (pending) return pending;
if (!force && fresh()) return Promise.resolve(state);
// Establish the request before notifying subscribers; a subscriber may
// synchronously call required()/refresh() again.
let resolveRequest;
pending = new Promise(resolve => { resolveRequest = resolve; });
const request = pending;
request.then(() => { if (pending === request) pending = null; });
// Expired disabled policy must never authorize use while a request is pending.
state = null; fetchedAt = 0;
notify();
(() => {
let settled = false;
const finish = value => {
if (settled) return;
settled = true;
state = value;
fetchedAt = now();
if (!value) maxAge = 10000;
notify();
resolveRequest(snapshot());
};
if (typeof GM_xmlhttpRequest !== 'function') { finish(null); return; }
try {
CXRequests.request({
method: 'GET', url: service + '/index.php?s=/api/code/config', timeout: 8000, anonymous: true,
headers: { Accept: 'application/json' },
onload(response) {
try {
if (response.status !== 200) { finish(null); return; }
const result = JSON.parse(response.responseText);
const data = result && result.data;
if (Number(result.code) !== 1 || !data || !data.scopes || typeof data.scopes !== 'object' || Array.isArray(data.scopes)) { finish(null); return; }
const policy = Object.fromEntries(scopes.map(key => [key, data.scopes[key] !== false]));
maxAge = Math.min(60, Math.max(1, Number(data.refresh_after) || 60)) * 1000;
finish({ scopes: policy, qrcode_url: safeUrl(data.qrcode_url) });
} catch (_) { finish(null); }
},
onerror() { finish(null); }, ontimeout() { finish(null); }, onabort() { finish(null); }
});
} catch (_) { finish(null); }
})();
return request;
}
function required(scope) {
if (!fresh() && !pending && !stopped) refresh();
return !scopes.includes(scope) || snapshot().scopes[scope] !== false;
}
function qrcodeUrl() { return snapshot().qrcode_url; }
function sessionIdentity(scope, device, token, until) {
return [scope, String(device || ''), String(token || ''), Number(until) || 0].join('|');
}
function sessionValid(scope, device, token, until) {
if (!required(scope)) return true;
if (!token || !device || Number(until) <= now() / 1000) return false;
const entry = sessionCache.get(sessionIdentity(scope, device, token, until));
return !!entry && entry.valid && entry.expiresAt > now() && entry.until * 1000 > now();
}
function sessionRejected(scope, device, token, until) {
const entry = sessionCache.get(sessionIdentity(scope, device, token, until));
return !!entry?.rejected && entry.expiresAt > now();
}
async function checkSession(scope, device, token, until) {
await refresh();
if (!required(scope)) return true;
if (!scopes.includes(scope) || !token || !device || String(token).length > 4096 || Number(until) <= now() / 1000) return false;
const key = sessionIdentity(scope, device, token, until);
const cached = sessionCache.get(key);
if (cached && cached.expiresAt > now()) return sessionValid(scope, device, token, until);
if (sessionRequests.has(key)) return sessionRequests.get(key);
const request = new Promise(resolve => {
let settled = false;
const finish = (valid, rejected = false, serverUntil = until) => {
if (settled) return;
settled = true;
const deadline = Math.min(Number(until), Number(serverUntil) || 0);
const expiresAt = Math.min(now() + (valid ? 60000 : 10000), valid ? deadline * 1000 : Infinity);
sessionCache.set(key, {valid, rejected, until: deadline, expiresAt});
if (sessionCache.size > 24) sessionCache.delete(sessionCache.keys().next().value);
resolve(valid && expiresAt > now());
};
try {
CXRequests.request({
method: 'POST', url: service + '/index.php?s=/api/code/check_session', timeout: 10000,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'scope=' + encodeURIComponent(scope) + '&device_id=' + encodeURIComponent(device) + '&session_token=' + encodeURIComponent(token),
onload(response) {
if (response.status === 401 || response.status === 403) { finish(false, true); return; }
try {
const result = JSON.parse(response.responseText);
const data = result?.data;
// A verification-free response is policy only. Never turn it
// into a remembered token/deadline that could survive reenable.
if (response.status === 200 && Number(result.code) === 1 && data?.valid === true && data.verification_required !== false && data.scope === scope && Number(data.valid_until) > now() / 1000) finish(true, false, data.valid_until);
else finish(false, response.status === 200 && (Number(result.code) === 0 || data?.valid === false));
} catch (_) { finish(false); }
},
onerror() { finish(false); }, ontimeout() { finish(false); }, onabort() { finish(false); }
});
} catch (_) { finish(false); }
});
sessionRequests.set(key, request);
request.then(() => { if (sessionRequests.get(key) === request) sessionRequests.delete(key); });
return request;
}
function prepareQr(image) {
if (!image) return;
image.setAttribute('data-script-verification-qr', '');
scheduleScan();
}
function paintQr(image) {
const url = qrcodeUrl();
if (imageStates.get(image)?.url === url) return;
const previous = imageStates.get(image);
if (previous?.objectUrl) URL.revokeObjectURL(previous.objectUrl);
const current = { url, objectUrl: '' };
imageStates.set(image, current);
image.removeAttribute('src');
let hint = image.nextElementSibling;
if (!hint?.hasAttribute('data-script-verification-qr-hint')) {
hint = image.ownerDocument.createElement('span');
hint.setAttribute('data-script-verification-qr-hint', '');
hint.setAttribute('role', 'status');
hint.style.cssText = 'display:block;font:inherit;font-size:12px;line-height:1.6;white-space:normal;';
image.insertAdjacentElement('afterend', hint);
}
hint.textContent = url ? '' : '二维码尚未配置,请联系管理员获取验证码。';
image.hidden = !url;
if (!url) return;
image.referrerPolicy = 'no-referrer';
const loaded = () => { if (imageStates.get(image) === current) { image.hidden = false; image.style.removeProperty('display'); } };
image.addEventListener('load', loaded, { once: true });
image.addEventListener('error', () => { if (imageStates.get(image) === current) { image.hidden = true; hint.textContent = '二维码加载失败,请联系管理员。'; } }, { once: true });
if (new URL(url).protocol === 'https:' || location.protocol !== 'https:') { image.src = url; return; }
// Only this service's raster upload can be loaded over userscript transport.
if (new URL(url).origin !== new URL(service).origin || typeof GM_xmlhttpRequest !== 'function') {
image.hidden = true; hint.textContent = '二维码需使用 HTTPS 地址。'; return;
}
try {
CXRequests.request({
method: 'GET', url, responseType: 'blob', timeout: 15000, anonymous: true,
onload(response) {
if (imageStates.get(image) !== current || stopped) return;
const blob = response.response;
const finalUrl = response.finalUrl ? safeUrl(response.finalUrl) : url;
if (response.status !== 200 || !finalUrl || new URL(finalUrl).origin !== new URL(service).origin || !blob || !['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(String(blob.type).split(';')[0].toLowerCase()) || blob.size > 5 * 1024 * 1024) {
image.hidden = true; hint.textContent = '二维码加载失败,请联系管理员。'; return;
}
current.objectUrl = URL.createObjectURL(blob);
image.src = current.objectUrl;
},
onerror() { if (imageStates.get(image) === current) hint.textContent = '二维码加载失败,请联系管理员。'; },
ontimeout() { if (imageStates.get(image) === current) hint.textContent = '二维码加载超时,请稍后重试。'; }
});
} catch (_) { image.hidden = true; hint.textContent = '二维码加载失败,请联系管理员。'; }
}
function scan(doc, depth = 0) {
if (stopped || depth > 3 || !doc.documentElement) return;
if (!documents.has(doc)) {
const observer = new MutationObserver(scheduleScan);
observer.observe(doc.documentElement, { childList: true, subtree: true });
documents.set(doc, observer);
const style = doc.createElement('style');
style.textContent = '[data-script-verification-disabled]{display:none!important}';
(doc.head || doc.documentElement).appendChild(style);
}
for (const panel of doc.querySelectorAll('[data-script-verification-scope]')) {
panel.toggleAttribute('data-script-verification-disabled', !required(panel.getAttribute('data-script-verification-scope')));
}
for (const image of doc.querySelectorAll('img[data-script-verification-qr]')) paintQr(image);
for (const link of doc.querySelectorAll('a[data-script-verification-qr-link]')) {
const url = qrcodeUrl();
if (url) link.href = url; else link.removeAttribute('href');
}
for (const frame of doc.querySelectorAll('iframe')) { try { if (frame.contentDocument) scan(frame.contentDocument, depth + 1); } catch (_) {} }
for (const [observed, observer] of documents) {
try { if (observed !== document && !observed.defaultView?.frameElement?.isConnected) { observer.disconnect(); documents.delete(observed); } } catch (_) { observer.disconnect(); documents.delete(observed); }
}
}
function scheduleScan() {
if (!scanTimer && !stopped) scanTimer = setTimeout(() => { scanTimer = null; scan(document); }, 50);
}
function subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }
function stableDevice(key) {
let value = String(GM_getValue(key, '') || '');
if (!/^[A-Za-z0-9_-]{16,128}$/.test(value)) {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
value = 'dev_' + Array.from(bytes, item => item.toString(16).padStart(2, '0')).join('');
GM_setValue(key, value);
}
return value;
}
const timer = setInterval(() => { refresh(); scheduleScan(); }, 10000);
window.addEventListener('focus', () => { refresh(); scheduleScan(); });
window.addEventListener('pageshow', () => { refresh(); scheduleScan(); });
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', scheduleScan, { once: true }); else scheduleScan();
window.addEventListener('pagehide', event => {
if (event.persisted) return;
stopped = true; clearInterval(timer); clearTimeout(scanTimer);
for (const observer of documents.values()) observer.disconnect();
for (const doc of documents.keys()) for (const image of doc.querySelectorAll('img[data-script-verification-qr]')) {
const current = imageStates.get(image); if (current?.objectUrl) URL.revokeObjectURL(current.objectUrl);
}
documents.clear(); listeners.clear(); sessionCache.clear(); sessionRequests.clear();
}, { once: true });
return Object.freeze({ refresh, required, qrcodeUrl, prepareQr, subscribe, stableDevice, checkSession, sessionValid, sessionRejected, profile });
})();
// BEGIN generated font resources: public dictionaries, no question upload.
const __scriptFontV1 = (() => {
'use strict';
const base = "http://103.236.88.53:23123";
const resources = {"chaoxing-table":{"sha256":"a7f0d85f12bc21094a976381e3e10c06c06af4c97bb26ca70dfefb8c0e10891f","entries":20902}};
const pending = new Map();
const memory = new Map();
const maxAge = 24 * 60 * 60 * 1000;
const cacheKey = name => '__script_font_v1:' + base + ':' + name + ':' + resources[name].sha256;
const url = name => base + '/index.php?s=/api/font/resource&name=' + encodeURIComponent(name) + '&v=' + resources[name].sha256;
function validate(name, value) {
const definition = resources[name];
if (!definition || !value || typeof value !== 'object' || Array.isArray(value)) throw new Error('字形字典格式错误');
const pattern = name === 'chaoxing-table' ? /^[0-9a-f]{8}$/ : /^[0-9a-f]{40}$/;
let count = 0;
for (const [key, code] of Object.entries(value)) {
if (pattern.test(key)) {
if (!Number.isInteger(code) || code < 0 || code > 0x10ffff || code >= 0xd800 && code <= 0xdfff) throw new Error('字形字典码点无效');
count++;
} else if (name !== 'chaoxing-table' || !['author', 'license', 'namespace', 'version'].includes(key) || typeof code !== 'string') {
throw new Error('字形字典包含无效条目');
}
}
if (count !== definition.entries) throw new Error('字形字典条数不符');
return value;
}
function request(name) {
return new Promise((resolve, reject) => {
let settled = false;
const finish = (error, value) => { if (settled) return; settled = true; error ? reject(error) : resolve(value); };
try {
CXRequests.request({method:'GET', url:url(name), timeout:15000,
onload(response) {
try {
if (response.status !== 200) throw new Error('字形字典 HTTP ' + response.status);
finish(null, validate(name, JSON.parse(response.responseText)));
} catch (error) { finish(error); }
},
onerror:()=>finish(new Error('字形字典下载失败')),
ontimeout:()=>finish(new Error('字形字典下载超时')),
onabort:()=>finish(new Error('字形字典下载已取消'))});
} catch (error) { finish(error); }
});
}
async function loadTable(name, installedResource) {
if (!resources[name] || !/-table$/.test(name)) throw new Error('未知字形字典');
if (memory.has(name)) return memory.get(name);
if (pending.has(name)) return pending.get(name);
const task = (async () => {
let table;
try {
const cached = await GM_getValue(cacheKey(name), null);
if (cached && cached.schema === 1 && cached.sha256 === resources[name].sha256 &&
Number.isFinite(cached.savedAt) && Date.now() >= cached.savedAt && Date.now() - cached.savedAt < maxAge) {
table = validate(name, cached.table);
}
} catch (_) { /* Ignore incompatible or corrupt old cache, never memoize it. */ }
if (!table && installedResource && typeof GM_getResourceText === 'function') {
try { table = validate(name, JSON.parse(await GM_getResourceText(installedResource))); } catch (_) {}
}
if (!table) table = await request(name);
try { await GM_setValue(cacheKey(name), {schema:1, sha256:resources[name].sha256, savedAt:Date.now(), table}); } catch (_) {}
memory.set(name, table);
return table;
})();
pending.set(name, task);
try { return await task; }
finally { if (pending.get(name) === task) pending.delete(name); }
}
return Object.freeze({loadTable, url});
})();
// END generated font resources.
;(async () => {
await __scriptVerificationV1.refresh();
/*
* ==========================================
* 学习通刷课助手 v1.6.2
* ==========================================
*
* 【功能说明】
* 1. 视频自动播放(支持倍速、自动推进章节、自动跳过测验)
* 2. 作业自动答题(题库查询 + AI 答题)
* 3. 考试自动答题(支持停止/继续)
* 4. 双模式题库(免费验证码 / 付费激活码)
*
* 【赞赏积分】
* 点击“去赞赏,领积分”打开赞赏页;打赏阶梯读取后台实际套餐。
* 商品总积分已包含赠送,具体期限和领取规则以赞赏页为准。
*
* 【付费声明】
* 本脚本基础功能(视频播放)完全免费
* 题库答题功能需要验证码(免费24小时)或激活码(付费永久)
* 付费仅用于题库API调用成本,不强制购买
*
* 【免责声明】
* 本脚本仅供学习交流使用,请勿用于违反学校规定或作弊行为
* 使用本脚本造成的任何后果由使用者自行承担
*
* 【版权信息】
* 作者:叶屿 | 版本:v1.6.2 | 更新:2026-11-15
*
* 【v1.6.2 字体与更新】
* - 按字体实际 cmap 识别页面字符,保留正常备用字体文字,补齐扩展汉字和私用区
* - 真正未匹配的字形继续保留原字体并回退 OCR,仅处理当前题目
* - 接入面板新版提示、更新说明、稍后提醒和扩展菜单手动检查
*
* 【v1.6.0 稳定性更新】
* - 对接当前后台验证码策略、公告与字体资源,保留设备及个人配置
* - 修复字体连续替换、网络超时、任务停止与多页面运行状态隔离
*
* 【v1.5.10 优化】
* - 按 AI 来源获取模型列表,支持名称与 ID 搜索、完整名称展示及手动填写
* - 题干及选项图片传给 AI,实际检测图片能力后再作答,缺图或能力未知时跳过
* - AI 来源配置独立保存,隔离异步回包与未保存草稿,沿用现有面板样式
* - 兼容 v1.5.9 及此前验证码、AI 解锁凭据
*
* 【v1.5.9 修复】
* - 支持播放器中途弹题的文字题干与选项,避免普通判断题误走 OCR
* - OCR 增加超时、停止取消和 Worker 清理,防止识别一直等待
* - 弹题仅提交一次,确认题窗关闭后续播,修复答题与防暂停任务互相干扰
* - 保留 v1.5.8 验证码与 AI 解锁凭据兼容
*
* 【v1.5.8 修复】
* - 统一选择题已选状态识别,修复蓝色选项已选中却提示未完整填写的问题
* - 点击后等待并核实全部目标选项,避免异步更新误报或部分选中误提交
* - 保留 v1.5.7 验证码与 AI 解锁凭据兼容
*
* 【v1.5.7 修复】
* - 识别、查询、匹配或分页切题失败时保留答案,不再自动提交整份作业或试卷
* - 多空填空题必须全部填写完成才会判定作答完成
* - 免费题库临时网络异常保留本地验证码;AI 解锁改为后台复核,不阻塞题间冷却
* - 停止答题会立即取消冷却等待,并补齐视频章节测验和弹题的提交保护
*
* 【v1.5.6 修复】
* - 修复 AI 解锁状态与实际冷却状态不同步的问题
* - 更新 DeepSeek Flash / V4 Pro 接口参数,并保留自定义 OpenAI 兼容接口
*
* 【v1.5.0 修复】
* - 修复作业/章测答完后部分模板不会自动提交的问题
* - 增强视频中途弹题识别、自动作答与继续播放
* - 加强免费验证码与 AI 解锁码会话守护
* - 支持后台图片公告展示与复习用途确认弹窗
*
* 【v1.5.2 修复】
* - 修复填空题 AI 兜底返回“答案:”空壳时被误判为成功的问题
* - 增强括号填空题 prompt 与 AI 答案解析,空答案自动重试一次
* - 修复逐题答题时误触整页提交导致后续题目被跳过的问题
* - 限制确认按钮查找范围,避免页面内容被误当成提交确认
* - 保留 v1.5.1 激活凭据兼容校验,升级版本无需重复激活
*
* 【v1.5.3 修复】
* - 学习目标等静态无视频内容自动推进到下一节
* - PPT、PDF、课件支持翻页、缩略页和滚动浏览,完成后再推进
* - 跨域文档无法读取内部状态时采用有界等待,避免永久卡住
* - 严格区分课程“下一节”、文档“下一页”和测验“下一题”
* - 仅刷新视频 iframe,避免 PPT/PDF 被反复刷新回第一页
* - 加强 SPA 页面切换验证,避免章节树回退造成连续跳节
* - 保留已完成视频的来源标记,避免切换内容时重复播放旧视频
*
* 【v1.5.4 修复】
* - 顶层只运行一个完整控制器,跨域视频 iframe 使用无面板工作端
* - 播放前检查媒体源,空源等待加载,不再直接触发无支持源错误
* - 仅在浏览器阻止自动播放时静音重试,无效媒体源采用有界重载并继续任务
*
* 【v1.5.5 修复】
* - 隔离章节切换前的旧播放器消息,避免重复推进或重复播放
* - 播放命令、播放器重载和工作帧心跳增加校验与有界超时
* - 单个坏视频源优先跳到同课时下一个视频,不再卡在当前任务点
*
* ==========================================
*/
(() => {
'use strict';
const SCRIPT_VERSION = '1.6.2';
const LEGACY_PROOF_VERSIONS = ['1.6.1', '1.6.0', '1.5.14', '1.5.13', '1.5.12', '1.5.11', '1.5.10', '1.5.9', '1.5.8', '1.5.7', '1.5.6', '1.5.5', '1.5.4', '1.5.3', '1.5.2', '1.5.1'];
const CXUtils = {
safeJSONParse(value, fallback = null) {
try { return JSON.parse(value); } catch (_) { return fallback; }
},
hashString(value) {
const str = String(value || '');
if (typeof CryptoJS !== 'undefined' && CryptoJS.SHA256) {
return CryptoJS.SHA256(str).toString();
}
let h1 = 0x811c9dc5;
let h2 = 0x01000193;
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
h1 ^= c;
h1 = Math.imul(h1, 0x01000193);
h2 ^= c + i;
h2 = Math.imul(h2, 0x85ebca6b);
}
return ((h1 >>> 0).toString(36) + (h2 >>> 0).toString(36));
},
listAccessibleDocs(rootDoc = document, maxDepth = 4) {
const docs = [];
const seen = new Set();
const visit = (doc, depth) => {
if (!doc || seen.has(doc) || depth > maxDepth) return;
seen.add(doc);
docs.push(doc);
let frames = [];
try { frames = Array.from(doc.querySelectorAll('iframe,frame')); } catch (_) { return; }
for (const frame of frames) {
try {
const childDoc = frame.contentDocument || frame.contentWindow?.document;
if (childDoc) visit(childDoc, depth + 1);
} catch (_) {}
}
};
visit(rootDoc, 0);
return docs;
},
hostFamily() {
const host = String(location.hostname || '').toLowerCase();
if (/(^|\.)chaoxing\.com$/.test(host)) return 'chaoxing.com';
if (/(^|\.)xuexitong\.com$/.test(host)) return 'xuexitong.com';
return 'chaoxing';
}
};
CXRequests.setTaskGroupReader(() => {
try {
if (AnswerModule._answering) return 'answer';
if (VideoModule._playing) return 'video';
} catch (_) {}
return 'ui';
});
// 只让顶层页面运行完整控制器。子 frame 中仅视频任务继续加载为媒体 worker,
// 普通页面、PPT/PDF/文档预览会在业务模块和常驻定时器创建前退出。
let _isTopLevelPage = false;
try { _isTopLevelPage = window.top === window.self; } catch (_) {}
let _canTopAccessThisFrame = _isTopLevelPage;
if (!_isTopLevelPage) {
try {
// 能读取 top.document 说明同源,顶层控制器可直接操作此 frame,无需第二个 owner。
_canTopAccessThisFrame = !!window.top.document;
} catch (_) {
_canTopAccessThisFrame = false;
}
}
const _frameUrl = String(location.href || '');
let _frameHasDocumentMarker = false;
try {
_frameHasDocumentMarker = !!document.querySelector('.ans-doc, .ans-ppt, .pdf-viewer, .ppt-viewer, .document-reader, .pdfViewer, .document-viewer');
} catch (_) {}
const _isDocumentFrame = _frameHasDocumentMarker || /(?:\/ananas\/modules\/(?:pdf|ppt|doc|book)\/|\.(?:pdf|ppt|pptx|doc|docx)(?:[?#]|$)|(?:^|[\/_.?=&-])(?:pdf|pptx?|docx?|book|office|document)(?:[\/_.?=&-]|$))/i.test(_frameUrl);
let _frameHasVideo = false;
try { _frameHasVideo = !!document.querySelector('video'); } catch (_) {}
const _hasVideoUrlHint = /(?:\/ananas\/modules\/video\/|(?:^|[\/_.?=&-])(?:video|player|m3u8|mp4|flv|hls)(?:[\/_.?=&-]|$))/i.test(_frameUrl);
const _isMediaWorkerFrame = !_isTopLevelPage && !_canTopAccessThisFrame && !_isDocumentFrame && (_frameHasVideo || _hasVideoUrlHint);
if (!_isTopLevelPage && !_isMediaWorkerFrame) return;
// AI Provider 配置:保留智谱、豆包、DeepSeek,以及 OpenAI 兼容自定义接口。
const AI_PROVIDERS = {
zhipu: {
name: '智谱 GLM-4-Flash',
model: 'glm-4-flash',
url: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
free: true,
desc: '智谱 AI 免费模型,速度快,中文题目适配较好',
link: 'https://www.bigmodel.cn/',
linkText: '前往智谱 AI 开放平台注册/登录获取 API Key →',
keyHint: '进入控制台 → API Keys → 创建 API Key → 复制'
},
doubao: {
name: '豆包 Doubao-lite',
model: 'doubao-lite-32k',
url: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
free: true,
desc: '字节跳动豆包模型,速度快,需在火山引擎开通模型',
link: 'https://console.volcengine.com/ark/',
linkText: '前往火山引擎 Ark 平台获取 API Key →',
keyHint: '登录 → API Key 管理 → 创建 API Key → 复制'
},
deepseek: {
name: 'DeepSeek Flash(V4.1)',
model: 'deepseek-flash',
url: 'https://api.deepseek.com/chat/completions',
thinking: 'disabled',
answerMaxTokens: 2048,
timeout: 60000,
free: false,
desc: 'DeepSeek 官方 Flash 模型,当前为 V4.1。使用非思考模式直接生成答案,费用以官方定价为准。',
link: 'https://platform.deepseek.com/',
linkText: '前往 DeepSeek 开放平台注册/登录获取 API Key →',
keyHint: '登录后 → 左侧 API Keys → 创建 API Key → 复制'
},
deepseek_v4: {
name: 'DeepSeek V4 Pro',
model: 'deepseek-v4-pro',
url: 'https://api.deepseek.com/chat/completions',
thinking: 'disabled',
answerMaxTokens: 2048,
timeout: 60000,
free: false,
desc: 'DeepSeek 官方 Pro 模型。使用非思考模式直接生成答案,与 Flash 共用 API Key,费用以官方定价为准。',
link: 'https://platform.deepseek.com/',
linkText: '前往 DeepSeek 开放平台注册/登录获取 API Key →',
keyHint: '与 Flash 使用同一平台 API Key,可直接切换'
}
};
// ==========================================
// ConfigStore - 配置存储模块
// ==========================================
const ConfigStore = {
// AES 加密内置密钥(补齐到 16 字节)
_key: CryptoJS.enc.Utf8.parse('chaoxing_cfg_key'),
_iv: CryptoJS.enc.Utf8.parse('chaoxing_cfg_key'),
// 通用存取(GM_setValue / GM_getValue)
get(key) {
const raw = GM_getValue(key, undefined);
if (raw === undefined) return undefined;
try { return JSON.parse(raw); } catch (_) { return raw; }
},
set(key, value) {
GM_setValue(key, JSON.stringify(value));
},
remove(key) {
GM_deleteValue(key);
},
clearAll() {
this._studyPurposeInMemory = false;
this.remove('cx_video_config');
this.remove('cx_answer_config');
try { GM_deleteValue(this._deviceIdKey); } catch (_) {}
try { localStorage.removeItem('cx_device_id'); } catch (_) {}
this.clearAllRunStates();
try { localStorage.removeItem('cx_study_purpose_confirmed'); } catch (_) {}
},
// 密码加密 / 解密(AES/CBC/PKCS7)
encryptPassword(plaintext) {
return CryptoJS.AES.encrypt(plaintext, this._key, {
iv: this._iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString();
},
decryptPassword(ciphertext) {
const bytes = CryptoJS.AES.decrypt(ciphertext, this._key, {
iv: this._iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return bytes.toString(CryptoJS.enc.Utf8);
},
// 设备 ID 使用脚本级 GM 存储,跨 chaoxing/xuexitong 子域刷新仍保持一致。
_deviceIdKey: 'cx_device_id_global',
_isValidDeviceId(value) {
const id = String(value == null ? '' : value).trim();
return id.length > 0 && id.length <= 128 ? id : '';
},
_readGlobalDeviceId() {
try {
return this._isValidDeviceId(GM_getValue(this._deviceIdKey, ''));
} catch (_) {
return '';
}
},
_writeGlobalDeviceId(id) {
try { GM_setValue(this._deviceIdKey, id); } catch (_) {}
},
_readLocalDeviceId() {
try {
return this._isValidDeviceId(localStorage.getItem('cx_device_id'));
} catch (_) {
return '';
}
},
_writeLocalDeviceId(id) {
try { localStorage.setItem('cx_device_id', id); } catch (_) {}
},
_recoverDeviceIdFromProof() {
// 首次切换到新子域时,旧配置仍可能带有可验证的设备 ID,先迁移它。
let cfg = null;
try { cfg = this.get('cx_answer_config'); } catch (_) {}
const proofs = [cfg && cfg.verifyProof, cfg && cfg.aiUnlockProof];
for (const raw of proofs) {
const payload = this.readAccessProof(raw);
const id = this._isValidDeviceId(payload && payload.deviceId);
if (!id || !payload || !payload.scope || !payload.sig || !payload.nonce || !payload.issuedAt || !payload.codeHash) continue;
const until = this.normalizeValidUntil(payload.validUntil);
if (until <= Date.now() / 1000 || payload.family !== CXUtils.hostFamily()) continue;
if (payload.ua !== CXUtils.hashString(navigator.userAgent || '')) continue;
if (Date.now() - Number(payload.issuedAt) > 30 * 60 * 60 * 1000) continue;
const proofVersions = [SCRIPT_VERSION, ...LEGACY_PROOF_VERSIONS];
const validSignature = proofVersions.some(version => {
const source = [
payload.scope,
payload.family,
payload.deviceId,
payload.validUntil,
payload.issuedAt,
payload.nonce,
payload.ua,
version,
payload.codeHash
].join('|');
return payload.sig === CXUtils.hashString(source);
});
if (validSignature) return id;
}
return '';
},
_generateDeviceId() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
},
getDeviceId() {
let id = this._readGlobalDeviceId();
if (!id) id = this._recoverDeviceIdFromProof();
if (!id) id = this._readLocalDeviceId();
if (!id) id = this._generateDeviceId();
// GM 是跨子域的主存储;同步当前 origin 以兼容旧版本代码。
this._writeGlobalDeviceId(id);
this._writeLocalDeviceId(id);
return id;
},
// 视频播放配置
getVideoConfig() {
return this.get('cx_video_config') || { playbackRate: 2, autoAdvance: true, autoSkipQuiz: true, autoAnswerQuiz: true, quizMode: 'free' };
},
setVideoConfig(config) {
this.set('cx_video_config', config);
},
// 答题模块配置
getAnswerConfig() {
return this.get('cx_answer_config') || {
mode: 'free',
verifyValidUntil: 0,
verifyProof: '',
verifySessionToken: '',
activationCode: '',
aiApiKey: '',
aiCustomUrl: '',
aiCustomModel: '',
aiUnlockUntil: 0,
aiUnlockProof: '',
aiUnlockSessionToken: ''
};
},
setAnswerConfig(config) {
this.set('cx_answer_config', config);
},
normalizeValidUntil(timestamp) {
let value = Number(timestamp);
if (!Number.isFinite(value) || value <= 0) return 0;
// API 约定使用 Unix 秒,兼容偶尔返回的毫秒时间戳。
if (value > 1e12) value /= 1000;
return Math.floor(value);
},
makeAccessProof(scope, code, validUntil) {
const issuedAt = Date.now();
const nonce = Math.random().toString(36).slice(2) + issuedAt.toString(36);
const payload = {
scope,
family: CXUtils.hostFamily(),
deviceId: this.getDeviceId(),
validUntil: this.normalizeValidUntil(validUntil),
issuedAt,
nonce,
ua: CXUtils.hashString(navigator.userAgent || ''),
codeHash: CXUtils.hashString(String(code || '').trim())
};
const source = [
payload.scope,
payload.family,
payload.deviceId,
payload.validUntil,
payload.issuedAt,
payload.nonce,
payload.ua,
SCRIPT_VERSION,
payload.codeHash
].join('|');
payload.sig = CXUtils.hashString(source);
try { return btoa(JSON.stringify(payload)); } catch (_) { return ''; }
},
readAccessProof(raw) {
if (!raw) return null;
try { return JSON.parse(atob(raw)); } catch (_) { return null; }
},
isAccessProofValid(scope, rawProof, validUntil) {
const until = this.normalizeValidUntil(validUntil);
if (until <= Date.now() / 1000) return false;
const payload = this.readAccessProof(rawProof);
if (!payload || payload.scope !== scope) return false;
if (this.normalizeValidUntil(payload.validUntil) !== until) return false;
if (payload.deviceId !== this.getDeviceId()) return false;
if (payload.family !== CXUtils.hostFamily()) return false;
if (payload.ua !== CXUtils.hashString(navigator.userAgent || '')) return false;
if (!payload.sig || !payload.nonce || !payload.issuedAt || !payload.codeHash) return false;
if (Date.now() - Number(payload.issuedAt) > 30 * 60 * 60 * 1000) return false;
const proofVersions = [SCRIPT_VERSION, ...LEGACY_PROOF_VERSIONS];
return proofVersions.some(version => {
const source = [
payload.scope,
payload.family,
payload.deviceId,
payload.validUntil,
payload.issuedAt,
payload.nonce,
payload.ua,
version,
payload.codeHash
].join('|');
return payload.sig === CXUtils.hashString(source);
});
},
clearVerifySession() {
const cfg = this.getAnswerConfig();
cfg.verifyValidUntil = 0;
cfg.verifyProof = '';
cfg.verifySessionToken = '';
this.setAnswerConfig(cfg);
try {
if (typeof AccessGuard !== 'undefined' && AccessGuard._clearSessionCache) AccessGuard._clearSessionCache('free-answer');
} catch (_) {}
},
setVerifyValidUntil(timestamp, code = '', sessionToken = '') {
const cfg = this.getAnswerConfig();
let validUntil = this.normalizeValidUntil(timestamp);
// 会话复核没有原验证码,不能只改有效期而留下旧 proof。
if (!code && cfg.verifyProof) {
const proof = this.readAccessProof(cfg.verifyProof);
const proofUntil = this.normalizeValidUntil(proof && proof.validUntil);
if (proofUntil && proofUntil !== validUntil) validUntil = proofUntil;
}
cfg.verifyValidUntil = validUntil;
if (code) {
cfg.verifyProof = this.makeAccessProof('free-answer', code, validUntil);
cfg.verifySessionToken = String(sessionToken || '');
} else if (sessionToken) {
cfg.verifySessionToken = sessionToken;
}
this.setAnswerConfig(cfg);
if (code || sessionToken) {
try {
if (typeof AccessGuard !== 'undefined' && AccessGuard._clearSessionCache) AccessGuard._clearSessionCache('free-answer');
} catch (_) {}
}
},
getVerifySessionToken() {
return this.getAnswerConfig().verifySessionToken || '';
},
isVerifyValid() {
if (!__scriptVerificationV1.required('free-answer')) return true;
const cfg = this.getAnswerConfig();
const ok = this.isAccessProofValid('free-answer', cfg.verifyProof, cfg.verifyValidUntil);
if (!ok && cfg.verifyValidUntil) this.clearVerifySession();
return ok;
},
// 题库未命中时的兜底策略:ai(AI兜底,默认) | skip(跳过)
getUnmatchedFallback() {
const cfg = this.getAnswerConfig();
return cfg.unmatchedFallback || 'ai';
},
setUnmatchedFallback(strategy) {
const cfg = this.getAnswerConfig();
cfg.unmatchedFallback = strategy;
this.setAnswerConfig(cfg);
},
// AI Provider & Unlock 存储
getAIProvider() {
const cfg = this.getAnswerConfig();
const provider = cfg.aiProvider || 'zhipu';
return ['zhipu', 'doubao', 'deepseek', 'deepseek_v4', 'custom'].includes(provider) ? provider : 'zhipu';
},
setAIProvider(provider) {
const cfg = this.getAnswerConfig();
const previous = this.getAISettings();
cfg.aiProviderConfigs = { ...(cfg.aiProviderConfigs || {}) };
if (!cfg.aiProviderConfigs[previous.provider]) cfg.aiProviderConfigs[previous.provider] = previous;
cfg.aiProvider = Object.prototype.hasOwnProperty.call(AI_PROVIDERS, provider) || provider === 'custom' ? provider : 'zhipu';
const sharedDeepSeek = ['deepseek', 'deepseek_v4'].includes(cfg.aiProvider) && ['deepseek', 'deepseek_v4'].includes(previous.provider) ? previous.apiKey : '';
const next = cfg.aiProviderConfigs[cfg.aiProvider] || { ...this.getAISettings(cfg.aiProvider), apiKey: sharedDeepSeek || this.getAISettings(cfg.aiProvider).apiKey };
cfg.aiApiKey = next.apiKey;
this.setAnswerConfig(cfg);
},
getAISettings(provider = this.getAIProvider()) {
const cfg = this.getAnswerConfig();
const selected = Object.prototype.hasOwnProperty.call(AI_PROVIDERS, provider) || provider === 'custom' ? provider : 'zhipu';
const profiles = cfg.aiProviderConfigs && typeof cfg.aiProviderConfigs === 'object' ? cfg.aiProviderConfigs : {};
const own = profiles[selected] && typeof profiles[selected] === 'object' ? profiles[selected] : null;
const legacyProvider = ['zhipu', 'doubao', 'deepseek', 'deepseek_v4', 'custom'].includes(cfg.aiProvider) ? cfg.aiProvider : 'zhipu';
const legacyApplies = selected === legacyProvider;
const defaults = AI_PROVIDERS[selected] || {};
// 旧版只有一个全局 Key,只迁移给原先选中的来源,防止跨来源发送旧密钥。
const inheritedDeepSeekKey = !own && selected === 'deepseek_v4' ? profiles.deepseek?.apiKey : !own && selected === 'deepseek' ? profiles.deepseek_v4?.apiKey : '';
return {
provider: selected,
apiKey: String(own ? own.apiKey || '' : inheritedDeepSeekKey || (legacyApplies ? cfg.aiApiKey || '' : '')).trim(),
model: String(own?.model || (selected === 'custom' ? cfg.aiCustomModel || '' : defaults.model || '')).trim(),
url: String(selected === 'custom' ? own?.url ?? cfg.aiCustomUrl ?? '' : defaults.url || '').trim()
};
},
setAISettings(config) {
const provider = config?.provider || config?.key || this.getAIProvider();
if (!(Object.prototype.hasOwnProperty.call(AI_PROVIDERS, provider) || provider === 'custom')) throw new Error('请选择有效的 AI 来源');
const cfg = this.getAnswerConfig();
const prior = this.getAISettings(provider);
const previous = this.getAISettings();
cfg.aiProviderConfigs = { ...(cfg.aiProviderConfigs || {}) };
if (!cfg.aiProviderConfigs[previous.provider]) cfg.aiProviderConfigs[previous.provider] = previous;
cfg.aiProviderConfigs = { ...cfg.aiProviderConfigs, [provider]: {
apiKey: String(config.apiKey === undefined ? prior.apiKey : config.apiKey).trim(),
model: String(config.model === undefined ? prior.model : config.model).trim(),
url: String(config.url === undefined ? prior.url : config.url).trim()
} };
cfg.aiProvider = provider;
// 保留旧字段供旧版面板迁移;答题只读取来源隔离后的配置。
cfg.aiApiKey = cfg.aiProviderConfigs[provider].apiKey;
if (provider === 'custom') {
cfg.aiCustomUrl = cfg.aiProviderConfigs[provider].url;
cfg.aiCustomModel = cfg.aiProviderConfigs[provider].model;
}
this.setAnswerConfig(cfg);
return this.getAISettings(provider);
},
getAICustomUrl() {
return this.getAISettings('custom').url;
},
setAICustomUrl(url) {
const cfg = this.getAnswerConfig();
cfg.aiCustomUrl = String(url || '').trim();
cfg.aiProviderConfigs = { ...(cfg.aiProviderConfigs || {}), custom: { ...this.getAISettings('custom'), url: cfg.aiCustomUrl } };
this.setAnswerConfig(cfg);
},
getAICustomModel() {
return this.getAISettings('custom').model;
},
setAICustomModel(model) {
const cfg = this.getAnswerConfig();
cfg.aiCustomModel = String(model || '').trim();
cfg.aiProviderConfigs = { ...(cfg.aiProviderConfigs || {}), custom: { ...this.getAISettings('custom'), model: cfg.aiCustomModel } };
this.setAnswerConfig(cfg);
},
getAIUnlockUntil() {
const cfg = this.getAnswerConfig();
return this.normalizeValidUntil(cfg.aiUnlockUntil);
},
clearAIUnlockSession() {
const cfg = this.getAnswerConfig();
cfg.aiUnlockUntil = 0;
cfg.aiUnlockProof = '';
cfg.aiUnlockSessionToken = '';
this.setAnswerConfig(cfg);
try {
if (typeof AccessGuard !== 'undefined' && AccessGuard._clearSessionCache) AccessGuard._clearSessionCache('ai-unlock');
} catch (_) {}
},
setAIUnlockUntil(timestamp, code = '', sessionToken = '') {
const cfg = this.getAnswerConfig();
let validUntil = this.normalizeValidUntil(timestamp);
// 会话复核没有原解锁码,不能只改有效期而留下旧 proof。
if (!code && cfg.aiUnlockProof) {
const proof = this.readAccessProof(cfg.aiUnlockProof);
const proofUntil = this.normalizeValidUntil(proof && proof.validUntil);
if (proofUntil && proofUntil !== validUntil) validUntil = proofUntil;
}
cfg.aiUnlockUntil = validUntil;
if (code) {
cfg.aiUnlockProof = this.makeAccessProof('ai-unlock', code, validUntil);
// 新解锁没有返回 session_token 时清掉旧 token,避免旧会话把本地解锁误判为失效。
cfg.aiUnlockSessionToken = String(sessionToken || '');
} else if (sessionToken) {
cfg.aiUnlockSessionToken = sessionToken;
}
this.setAnswerConfig(cfg);
if (code || sessionToken) {
try {
if (typeof AccessGuard !== 'undefined' && AccessGuard._clearSessionCache) AccessGuard._clearSessionCache('ai-unlock');
} catch (_) {}
}
},
getAIUnlockSessionToken() {
return this.getAnswerConfig().aiUnlockSessionToken || '';
},
isAIUnlocked() {
if (!__scriptVerificationV1.required('ai-unlock')) return true;
const cfg = this.getAnswerConfig();
const ok = this.isAccessProofValid('ai-unlock', cfg.aiUnlockProof, cfg.aiUnlockUntil);
if (!ok && cfg.aiUnlockUntil) this.clearAIUnlockSession();
return ok;
},
_studyPurposeInMemory: false,
isStudyPurposeConfirmed() {
if (this._studyPurposeInMemory) return true;
try { return localStorage.getItem('cx_study_purpose_confirmed') === '1'; }
catch (_) { return false; }
},
setStudyPurposeConfirmed() {
this._studyPurposeInMemory = true;
try { localStorage.setItem('cx_study_purpose_confirmed', '1'); } catch (_) {}
},
// 状态按账号/课程/标签页/模块隔离;旧的无作用域状态不参与恢复。
_runStatePrefix: 'cx_run_state_v2:',
clearAllRunStates() {
try {
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key === 'cx_run_state' || key?.startsWith(this._runStatePrefix)) keys.push(key);
}
keys.forEach(key => localStorage.removeItem(key));
} catch (_) {}
},
getRunState(storageScope) {
if (!storageScope) return null;
try {
const state = JSON.parse(localStorage.getItem(this._runStatePrefix + storageScope) || 'null');
return state && state.schemaVersion === 2 && state.storageScope === storageScope &&
typeof state.runId === 'string' && state.runId && typeof state.ownerId === 'string' && state.ownerId ? state : null;
} catch (_) { return null; }
},
setRunState(state) {
if (!state?.storageScope || !state.runId) return false;
try {
localStorage.setItem(this._runStatePrefix + state.storageScope, JSON.stringify(state));
return true;
} catch (_) { return false; }
},
clearRunState(runId, storageScope) {
const state = this.getRunState(storageScope);
if (!state || !runId || state.runId !== runId) return;
try { localStorage.removeItem(this._runStatePrefix + storageScope); } catch (_) {}
}
};
// 当前来源、Key、模型和地址统一读取,旧全局设置按原来源迁移。
function getAIProviderConfig(provider = ConfigStore.getAIProvider()) {
const settings = ConfigStore.getAISettings(provider);
return { ...(AI_PROVIDERS[settings.provider] || { name: '自定义接口', free: false }), ...settings, key: settings.provider };
}
function createAIRequestBody(providerConf, prompt, temperature = 0.1, maxTokens = 2048) {
const body = { model: providerConf.model, messages: [{ role: 'user', content: prompt }], temperature, max_tokens: maxTokens, stream: false };
const provider = providerConf.provider || providerConf.key;
if (['deepseek', 'deepseek_v4'].includes(provider) && ['deepseek-flash', 'deepseek-v4-pro'].includes(providerConf.model)) body.thinking = { type: 'disabled' };
if (provider === 'zhipu' && providerConf.model === 'glm-5.3') { body.thinking = { type: 'enabled' }; body.reasoning_effort = 'low'; }
else if (provider === 'zhipu' && ['glm-4.7', 'glm-4.7-flash'].includes(providerConf.model)) body.thinking = { type: 'disabled' };
return body;
}
function getAIResponseText(json) {
const choice = json?.choices?.[0] || {};
if (['length', 'max_tokens'].includes(choice.finish_reason)) throw new Error('AI 输出达到长度上限,未使用不完整答案,请调整模型或输出额度后重试');
if (choice.finish_reason && !['stop', 'end_turn'].includes(choice.finish_reason)) throw new Error('AI 未正常生成最终文本,请稍后重试或调整模型');
let content = choice.message?.content ?? choice.text ?? '';
if (Array.isArray(content)) content = content.map(part => typeof part === 'string' ? part : (part?.text || '')).join('');
return String(content || '').trim();
}
const AISettingsService = {
getConfig(provider = ConfigStore.getAIProvider()) { return getAIProviderConfig(provider); },
validateConfig(config, { requireModel = true } = {}) {
const provider = config?.provider || config?.key;
if (!(Object.prototype.hasOwnProperty.call(AI_PROVIDERS, provider) || provider === 'custom')) return { ok: false, error: '请选择有效的 AI 来源', field: 'provider' };
const apiKey = String(config.apiKey || '').trim();
if (!apiKey) return { ok: false, error: '请填写当前来源的 API Key', field: 'apiKey' };
if (/\s|[\u0000-\u001f\u007f]/.test(apiKey)) return { ok: false, error: 'API Key 内不能包含空格或换行', field: 'apiKey' };
const model = String(config.model || '').trim();
if (requireModel && !model) return { ok: false, error: '请填写已开通的模型 ID;豆包也可填写 ep- 接入点 ID', field: 'model' };
if (model && (model.length > 200 || /\s|[\u0000-\u001f\u007f]/.test(model))) return { ok: false, error: '模型 ID 格式无效,请勿输入空格或换行', field: 'model' };
try { this.resolveEndpoint(config); } catch (error) { return { ok: false, error: error.message, field: 'url' }; }
return { ok: true, error: '', field: '' };
},
resolveEndpoint(config) {
const provider = config?.provider || config?.key;
if (!(Object.prototype.hasOwnProperty.call(AI_PROVIDERS, provider) || provider === 'custom')) throw new Error('请选择有效的 AI 来源');
const source = provider === 'custom' ? String(config.url || '').trim() : AI_PROVIDERS[provider].url;
if (!source) throw new Error('请填写自定义接口地址');
if (/[\u0000-\u0020\u007f\\]/.test(source)) throw new Error('接口地址不能含空白或反斜杠');
let parsed;
try { parsed = new URL(source); } catch (_) { throw new Error('接口地址无效,请填写完整的 http:// 或 https:// 地址'); }
if (!['https:', 'http:'].includes(parsed.protocol) || !parsed.hostname) throw new Error('接口仅支持 HTTP 或 HTTPS 协议');
if (parsed.username || parsed.password) throw new Error('接口地址不能内嵌用户名或密码,请在 API Key 栏填写密钥');
if (parsed.search || parsed.hash || source.includes('?') || source.includes('#')) throw new Error('接口地址不能包含查询参数或 # 片段');
let path = parsed.pathname.replace(/\/+$/, '');
if (!/\/chat\/completions$/i.test(path)) path += '/chat/completions';
parsed.pathname = path;
return parsed.toString();
},
_makeError(message, retryable = false, status = 0) {
const error = new Error(message); error.retryable = retryable; error.status = status; return error;
},
snapshot(config, options = {}) {
const check = this.validateConfig(config, options);
if (!check.ok) { const error = this._makeError(check.error); error.field = check.field; throw error; }
const provider = config.provider || config.key;
return Object.freeze({ ...(AI_PROVIDERS[provider] || { name: '自定义接口' }), provider, key: provider, apiKey: String(config.apiKey).trim(), model: String(config.model || '').trim(), url: this.resolveEndpoint(config) });
},
_snapshot(config) { return this.snapshot(config); },
_visionResults: new Map(),
_visionIdentity(config) {
const snapshot = this.snapshot(config);
return JSON.stringify([snapshot.provider, snapshot.url, snapshot.model, snapshot.apiKey]);
},
getVisionStatus(config) {
let key;
try { key = this._visionIdentity(config); } catch (_) { return null; }
const result = this._visionResults.get(key);
if (!result) return null;
const ttl = result.status === 'supported' ? 30 * 60 * 1000 : result.status === 'unsupported' ? 10 * 60 * 1000 : 60 * 1000;
const age = Date.now() - result.checkedAt;
if (age < 0 || age > ttl) { this._visionResults.delete(key); return null; }
return { ...result };
},
_setVisionStatus(config, result) {
const key = this._visionIdentity(config);
if (this._visionResults.size >= 32 && !this._visionResults.has(key)) this._visionResults.delete(this._visionResults.keys().next().value);
this._visionResults.set(key, { status: result.status, message: String(result.message || '').slice(0, 500), checkedAt: Date.now() });
try { window.dispatchEvent(new Event('cx-ai-vision-status')); } catch (_) {}
},
_modelVisionMetadata(model) {
// 模型名称不能证明图片能力;只有接口明确给出的输入模态/能力字段才作提示。
const flags = [model.supports_vision, model.supports_image_input, model.vision, model.capabilities?.vision, model.capabilities?.image_input]
.filter(value => typeof value === 'boolean');
const inputs = [model.input_modalities, model.supported_input_modalities, model.modalities?.input, model.architecture?.input_modalities, model.capabilities?.input_modalities];
for (const input of inputs) {
if (!Array.isArray(input) || !input.length || !input.every(value => typeof value === 'string')) continue;
flags.push(input.some(value => /^(?:image|images|vision)$/i.test(value.trim())));
}
if (!flags.length || flags.some(value => value !== flags[0])) return 'unknown';
return flags[0] ? 'supported' : 'unsupported';
},
async listModels(config) {
// 获取列表不要求预先填写模型 ID,但必须校验并固定本次来源、地址和 Key。
const snapshot = this._snapshot({ ...config, model: 'models-discovery' });
const endpoint = new URL(snapshot.url);
endpoint.pathname = endpoint.pathname.replace(/\/chat\/completions\/?$/i, '/models');
const raw = await new Promise((resolve, reject) => {
if (typeof GM_xmlhttpRequest !== 'function') return reject(this._makeError('无法获取模型,请用 Tampermonkey 运行脚本;也可手动填写模型 ID'));
let settled = false;
const finish = (fn, value) => { if (!settled) { settled = true; fn(value); } };
const fail = message => finish(reject, this._makeError(message));
try {
CXRequests.request({
method: 'GET', url: endpoint.href, timeout: 20000, anonymous: true,
headers: { 'Accept': 'application/json', 'Authorization': 'Bearer ' + snapshot.apiKey },
onload: response => {
const status = Number(response.status) || 0;
if (status >= 200 && status < 300) {
if (typeof response.responseText !== 'string' || response.responseText.length > 2 * 1024 * 1024) return fail('模型列表响应过大或无效,请手动填写模型 ID');
try { finish(resolve, JSON.parse(response.responseText)); }
catch (_) { fail('模型列表不是有效 JSON,该接口可能不提供模型发现;请手动填写模型 ID'); }
return;
}
const hints = { 401: 'API Key 无效或已过期', 402: '账户余额不足', 403: '当前 Key 没有获取列表的权限', 404: '该服务未提供标准模型列表接口', 405: '该服务不支持获取模型列表', 408: '获取模型列表超时', 429: '请求过于频繁或配额不足' };
// 远端错误正文可能包含凭据,仅显示本地固定的状态说明。
fail('HTTP ' + status + ' · ' + (hints[status] || (status >= 500 ? '模型列表服务暂时不可用' : '获取模型列表失败')) + ';可手动填写模型 ID');
},
onerror: () => fail('获取模型列表失败,请检查网络和脚本跨域授权;可手动填写模型 ID'),
ontimeout: () => fail('获取模型列表超时;可稍后重试或手动填写模型 ID'),
onabort: () => fail('获取模型列表已取消;可手动填写模型 ID'),
});
} catch (_) { fail('无法发出模型列表请求,请检查接口和脚本跨域授权;可手动填写模型 ID'); }
});
if (raw?.error) throw this._makeError('模型列表服务返回错误,请检查 Key 和接口权限;可手动填写模型 ID');
const entries = Array.isArray(raw?.data) ? raw.data : Array.isArray(raw?.models) ? raw.models : Array.isArray(raw) ? raw : null;
if (!entries) throw this._makeError('未识别到标准模型列表,请手动填写模型 ID');
const models = [];
const seen = new Set();
for (const entry of entries) {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
const id = typeof entry.id === 'string' ? entry.id.trim() : typeof entry.model === 'string' ? entry.model.trim() : '';
if (!id || id.length > 200 || /[\s\u0000-\u001f\u007f<>"']/.test(id) || /^(?:(?:https?|ftp|file|data|javascript|blob):|\/\/)/i.test(id) || seen.has(id)) continue;
seen.add(id);
const name = typeof entry.name === 'string' ? entry.name.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 120) : '';
models.push({ id, name: name || id, vision: this._modelVisionMetadata(entry) });
if (models.length >= 300) break;
}
return { models, message: models.length ? '列表不代表当前 Key 一定有调用权限;请测试连接,图片能力需单独检测。' : '接口未返回可选模型;仍可手动填写已开通的模型 ID。' };
},
_isVisionUnsupportedResponse(raw) {
// 只提取错误字段作本地分类,绝不把服务端原文写进异常、日志或页面。
let value = raw;
if (typeof value === 'string') {
if (value.length > 32768) return false;
try { value = JSON.parse(value); } catch (_) { return false; }
}
const error = value?.error;
const fields = typeof error === 'string' ? [error] : [error?.message, error?.code, error?.type];
const message = fields.filter(part => typeof part === 'string').join(' ').slice(0, 4000).toLowerCase();
if (!message) return false;
if (/(?:unsupported|not_supported)[_-](?:vision|multimodal|image_input|image_url)|(?:vision|image_input|image_url)[_-](?:unsupported|not_supported)/.test(message)) return true;
if (/(?:does not|doesn't|do not|cannot|can't)\s+(?:currently\s+)?support\s+(?:any\s+)?(?:image|images|vision|multimodal|multi-modal)|(?:image(?:_url)?|vision|multimodal|multi-modal)\s+(?:input\s+|content\s+)?(?:is\s+|are\s+)?(?:not supported|unsupported|not allowed|not permitted|only supported by)/.test(message)) return true;
if (/(?:model|endpoint)[\s\S]{0,60}(?:text-only|text only)|不支持[\s\S]{0,20}(?:图片输入|图像输入|图片内容|图像内容|视觉|多模态)|(?:图片输入|图像输入|图片内容|图像内容|视觉|多模态)[\s\S]{0,20}不支持/.test(message)) return true;
return false;
},
async probeVision(config) {
const snapshot = this._snapshot(config);
let challenge;
let image;
try {
const random = new Uint32Array(1);
if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') crypto.getRandomValues(random);
else random[0] = Math.floor(Math.random() * 0x100000000);
challenge = String(1000 + random[0] % 9000);
const canvas = document.createElement('canvas');
canvas.width = 360; canvas.height = 120;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('canvas');
ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#111111'; ctx.font = 'bold 68px monospace'; ctx.textBaseline = 'middle'; ctx.textAlign = 'center';
ctx.fillText(challenge, canvas.width / 2, canvas.height / 2);
image = canvas.toDataURL('image/png');
if (!/^data:image\/png;base64,[a-zA-Z0-9+/=]+$/.test(image)) throw new Error('canvas');
} catch (_) { return { status: 'unknown', message: '浏览器无法生成图片检测样本,尚未确认图片能力;图片题将暂停。' }; }
try {
// 挑战数字只出现在本地生成的图片中,文字提示不泄露答案。
const content = [{ type: 'text', text: '请读取图片正中央的四位阿拉伯数字。仅输出这四位数字,不加空格、标点或说明;看不到图片时请回答无法读取。' }, { type: 'image_url', image_url: { url: image } }];
const raw = await this._request(snapshot, this._buildBody(snapshot, content, true));
if (raw?.error && this._isVisionUnsupportedResponse(raw)) return { status: 'unsupported', message: '当前模型或接口明确不支持图片输入;请选择支持图片的模型后重新检测。' };
const answer = this._readContent(raw, true);
if (answer !== challenge) return { status: 'unknown', message: '模型未正确读出检测图中的数字,尚未确认图片能力;图片题将暂停,可更换模型或重新检测。' };
return { status: 'supported', message: '当前模型已正确读取检测图片,已确认支持本接口的图片输入。检测通过不代表图片题答案一定正确。' };
} catch (error) {
if (error?.visionUnsupported === true) return { status: 'unsupported', message: '当前模型或接口明确不支持图片输入;请选择支持图片的模型后重新检测。' };
const hints = { 400: '请求参数或模型配置需要检查', 401: 'API Key 无效或已过期', 402: '账户余额不足', 403: '当前 Key 没有模型调用权限', 404: '模型或接口不存在', 408: '检测超时', 429: '请求过于频繁或配额不足' };
const status = Number(error?.status) || 0;
const reason = hints[status] || (status >= 500 ? '服务暂时不可用' : /超时/.test(error?.message || '') ? '检测超时' : '接口未返回有效检测结果,请检查网络、Key 和模型配置');
return { status: 'unknown', message: reason + ',尚未确认图片能力;图片题将暂停,可调整配置后重新检测。' };
}
},
_visionChecks: new Map(),
async checkVision(config, options = {}) {
const force = options === true || options?.force === true;
const snapshot = this._snapshot(config);
const cached = !force && this.getVisionStatus(snapshot);
if (cached && ['supported', 'unsupported', 'unknown'].includes(cached.status)) return { status: cached.status, message: String(cached.message || '') };
// 仅内存合并同配置的并发检测;不把 Key 派生缓存键写入日志或持久化。
const key = JSON.stringify([snapshot.provider, snapshot.url, snapshot.model, snapshot.apiKey]);
if (this._visionChecks.has(key)) return this._visionChecks.get(key);
const pending = this.probeVision(snapshot).then(result => {
this._setVisionStatus(snapshot, result);
return result;
});
this._visionChecks.set(key, pending);
try { return await pending; }
finally { this._visionChecks.delete(key); }
},
_buildBody(config, prompt, test = false) {
return createAIRequestBody(config, prompt, 0.1, test ? config.model === 'glm-5.3' ? 512 : 256 : 4096);
},
_readContent(raw) {
if (raw?.error) throw this._makeError('AI 服务返回错误,请检查模型权限、Key 和账户状态');
const text = getAIResponseText(raw);
if (!text) throw this._makeError(raw?.choices?.[0]?.message?.reasoning_content ? 'AI 仅返回思考过程,未返回正式答案,请检查模型配置' : 'AI 未返回正式文本答案,请检查接口兼容性');
return text;
},
async _prepareImages(images, canContinue = () => true) {
const unique = new Map();
for (const image of images) {
const source = typeof image === 'string' ? image : image?.url;
if (typeof source !== 'string' || !source.trim()) throw this._makeError('有题图缺少有效地址,已停止作答,请等待图片加载后重试');
const url = source.trim();
if (!unique.has(url)) unique.set(url, { url, labels: [] });
const safeAlt = typeof image?.alt === 'string' ? image.alt
.replace(/(?:https?:\/\/|data:)[^\s]+/gi, '[图片地址]')
.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim().slice(0, 200) : '';
const role = image?.role === 'option' && Number.isInteger(image?.optionIndex) && image.optionIndex >= 0 && image.optionIndex < 26 ? '选项 ' + String.fromCharCode(65 + image.optionIndex) : '题干';
const order = Number.isInteger(image?.sourceIndex) && image.sourceIndex >= 0 ? '配图 ' + (image.sourceIndex + 1) : '';
const label = [role, order, safeAlt].filter(Boolean).join(' · ');
if (!unique.get(url).labels.includes(label)) unique.get(url).labels.push(label);
}
const records = Array.from(unique.values());
if (records.length > 6) throw this._makeError('本题图片超过 6 张,已停止自动作答,请手动检查');
const parts = [];
let total = 0;
for (let index = 0; index < records.length; index++) {
if (!canContinue()) throw Object.assign(new Error('题图读取已取消'), { name: 'AbortError' });
const result = await this._loadImage(records[index].url);
if (!canContinue()) throw Object.assign(new Error('题图读取已取消'), { name: 'AbortError' });
total += result.size;
if (total > 12 * 1024 * 1024) throw this._makeError('本题图片合计超过 12 MB,已停止自动作答');
parts.push({ type: 'text', text: '图片 ' + (index + 1) + (records[index].labels.length ? '(' + records[index].labels.join(';') + ')' : '') });
parts.push({ type: 'image_url', image_url: { url: result.url } });
}
return parts;
},
_imageData(bytes) {
if (!bytes?.length) throw this._makeError('题图内容为空,已停止作答,请刷新题图后重试');
if (bytes.length > 5 * 1024 * 1024) throw this._makeError('单张题图超过 5 MB,已停止自动作答');
const prefix = String.fromCharCode(...bytes.subarray(0, 12));
let mime = '';
if (bytes.length >= 8 && [137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value)) mime = 'image/png';
else if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) mime = 'image/jpeg';
else if (/^GIF8[79]a/.test(prefix)) mime = 'image/gif';
else if (prefix.startsWith('RIFF') && prefix.slice(8, 12) === 'WEBP') mime = 'image/webp';
if (!mime) throw this._makeError('题图不是支持的 PNG/JPEG/GIF/WebP 图片,或下载到登录页面,已停止作答');
let binary = '';
for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
return { url: 'data:' + mime + ';base64,' + btoa(binary), size: bytes.length };
},
async _loadImage(source) {
const maxBytes = 5 * 1024 * 1024;
if (/^data:/i.test(source)) {
const match = source.match(/^data:image\/(?:png|jpe?g|gif|webp);base64,([a-zA-Z0-9+/=\r\n]+)$/i);
if (!match) throw this._makeError('题图的内嵌图片格式不支持,已停止作答');
if (match[1].length > Math.ceil(maxBytes / 3) * 4 + 1024) throw this._makeError('单张题图超过 5 MB,已停止自动作答');
let binary;
try { binary = atob(match[1].replace(/\s/g, '')); }
catch (_) { throw this._makeError('题图编码无效,已停止作答'); }
return this._imageData(Uint8Array.from(binary, character => character.charCodeAt(0)));
}
let url;
try { url = new URL(source, typeof location !== 'undefined' ? location.href : undefined); }
catch (_) { throw this._makeError('题图地址无效,已停止作答'); }
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) throw this._makeError('题图地址仅支持 HTTP/HTTPS 或内嵌图片,已停止作答');
return new Promise((resolve, reject) => {
if (typeof GM_xmlhttpRequest !== 'function') return reject(this._makeError('无法读取题图,请通过 Tampermonkey 运行脚本'));
let settled = false;
let request;
let timer;
const finish = (fn, value) => { if (!settled) { settled = true; clearTimeout(timer); fn(value); } };
const fail = message => finish(reject, this._makeError(message));
const abort = message => { fail(message); try { request?.abort(); } catch (_) {} };
timer = setTimeout(() => abort('读取题图超时,已停止作答,请稍后重试'), 16000);
try {
request = CXRequests.taskRequest({
// 使用题图所在站点的正常登录态;此请求不会携带 AI 密钥,也不把原始图片地址发给 AI。
method: 'GET', url: url.href, responseType: 'arraybuffer', timeout: 15000,
anonymous: !/(^|\.)(?:chaoxing\.com|xuexitong\.com|edu\.cn)$/i.test(url.hostname),
onprogress: event => { if (Number(event.loaded) > maxBytes || Number(event.total) > maxBytes) abort('单张题图超过 5 MB,已停止自动作答'); },
onload: response => {
if (settled) return;
if (Number(response.status) < 200 || Number(response.status) >= 300) return fail('题图下载失败,已停止作答,请确认图片可正常打开');
try {
if (!response.response || Object.prototype.toString.call(response.response) !== '[object ArrayBuffer]') return fail('题图下载未返回有效图片数据,已停止作答');
finish(resolve, this._imageData(new Uint8Array(response.response)));
} catch (_) { fail('题图内容无效、过大或格式不支持,已停止作答,请检查图片'); }
},
onerror: () => fail('题图读取失败,已停止作答,请检查网络及脚本的跨域访问授权'),
ontimeout: () => fail('读取题图超时,已停止作答,请稍后重试'),
onabort: () => fail('题图读取已取消,已停止作答'),
});
} catch (_) { fail('无法发出题图请求,已停止作答,请检查脚本的跨域访问授权'); }
});
},
async testConnection(config) {
const snapshot = this._snapshot(config);
const raw = await this._request(snapshot, this._buildBody(snapshot, '请只回复 OK。', true));
const choice = raw?.choices?.[0];
const message = choice?.message;
if (!raw?.error && ['length', 'max_tokens'].includes(choice?.finish_reason) && message && (typeof message.content === 'string' || typeof message.reasoning_content === 'string')) {
return '接口连接成功;本次小额测试已达到输出上限,尚未验证完整答案。正式答题会使用更大额度,截断内容不会用于填答。';
}
this._readContent(raw, true);
return '连接成功,当前来源和模型已返回正式文本。';
},
_request(config, body) {
return new Promise((resolve, reject) => {
if (typeof GM_xmlhttpRequest !== 'function') return reject(this._makeError('GM_xmlhttpRequest 不可用,请用 Tampermonkey 安装本脚本'));
let settled = false;
const finish = (fn, value) => { if (!settled) { settled = true; fn(value); } };
const fail = (message, retryable = false, status = 0) => finish(reject, this._makeError(message, retryable, status));
try {
CXRequests.taskRequest({
method: 'POST', url: config.url, timeout: config.timeout || 60000, anonymous: true,
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + config.apiKey },
data: JSON.stringify(body),
onload: (resp) => {
const status = Number(resp.status) || 0;
if (status >= 200 && status < 300) {
try {
if (typeof resp.responseText !== 'string' || resp.responseText.length > 4 * 1024 * 1024) return fail('AI 响应内容过大或无效');
finish(resolve, JSON.parse(resp.responseText));
}
catch (_) { fail('AI 响应不是有效 JSON,请检查接口地址和兼容性'); }
return;
}
const hints = { 400: '请求参数或模型 ID 不被支持', 401: 'API Key 无效或已过期', 402: '账户余额不足', 403: '当前 Key 无权访问该模型', 404: '接口地址或模型不存在', 408: '服务请求超时', 429: '请求过于频繁或配额不足' };
const detail = hints[status] || (status >= 500 ? 'AI 服务暂时不可用' : 'AI 请求失败,请检查配置和网络');
// 不回显远端错误正文,避免中转服务把 Authorization / Key 带入日志。
const error = this._makeError('HTTP ' + status + ' · ' + detail, status === 0 || status === 408 || status === 429 || status >= 500, status);
if ((status === 400 || status === 422) && this._isVisionUnsupportedResponse(resp.responseText)) error.visionUnsupported = true;
finish(reject, error);
},
onerror: () => fail('网络请求失败,请检查网络和脚本跨域授权', true),
ontimeout: () => fail('AI 请求超时,请稍后重试', true),
onabort: () => fail('AI 请求已取消'),
});
} catch (_) { fail('AI 请求无法发出,请检查脚本跨域授权和接口配置'); }
});
},
};
// BEGIN generated service migration: only reviewed temporary authorization keys.
;(() => {
'use strict';
const service = "http://103.236.88.53:23123";
const marker = "__script_service_v1_chaoxing";
try {
if (typeof GM_getValue !== 'function' || typeof GM_setValue !== 'function') throw new Error('缺少同步 GM 存储权限');
if (GM_getValue(marker, '') !== service) {
ConfigStore.getDeviceId();
for (const key of []) GM_setValue(key, key === 'av_verify_state' ? { validUntil: 0 } : '');
const key = "cx_answer_config";
const raw = GM_getValue(key, undefined);
if (raw !== undefined && raw !== null) {
const value = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('原答题配置格式异常,未覆盖个人配置');
const next = { ...value };
for (const field of ["verifyValidUntil","verifyProof","verifySessionToken","aiUnlockUntil","aiUnlockProof","aiUnlockSessionToken"]) delete next[field];
GM_setValue(key, typeof raw === 'string' ? JSON.stringify(next) : next);
}
GM_setValue(marker, service);
}
} catch (error) {
console.warn('[脚本服务迁移] 临时授权迁移未完成,请重新验证;个人配置未整体清除。', error);
}
try {
if ([].length && localStorage.getItem(marker) !== service) {
for (const key of []) localStorage.removeItem(key);
localStorage.setItem(marker, service);
}
} catch (error) { console.warn('[脚本服务迁移] 当前页面禁止本地存储。', error); }
try {
if ([].length && sessionStorage.getItem(marker) !== service) {
for (const key of []) sessionStorage.removeItem(key);
sessionStorage.setItem(marker, service);
}
} catch (_) {}
})();
// END generated service migration.
const AccessGuard = {
// 会话复核只用于确认远端仍然有效,不应成为每道题的 12 秒前置等待。
// key 同时包含 scope、token、device 和本地 proof;切换任一凭据都会自然失效旧缓存。
_sessionCache: new Map(),
_sessionRequests: new Map(),
_sessionCacheTtl: 60 * 1000,
_sessionTransientTtl: 15 * 1000,
_getSessionIdentity(scope, token) {
const cfg = ConfigStore.getAnswerConfig();
const proof = scope === 'free-answer' ? cfg.verifyProof : cfg.aiUnlockProof;
const validUntil = scope === 'free-answer' ? cfg.verifyValidUntil : cfg.aiUnlockUntil;
const deviceId = ConfigStore.getDeviceId();
return {
scope,
token: String(token || ''),
deviceId: String(deviceId || ''),
proof: String(proof || ''),
validUntil: ConfigStore.normalizeValidUntil(validUntil),
key: [scope, String(token || ''), String(deviceId || ''), String(proof || ''), ConfigStore.normalizeValidUntil(validUntil)].join('|')
};
},
_isCurrentIdentity(identity) {
if (!identity) return false;
const token = identity.scope === 'free-answer'
? ConfigStore.getVerifySessionToken()
: ConfigStore.getAIUnlockSessionToken();
const current = this._getSessionIdentity(identity.scope, token);
return current.key === identity.key;
},
_cacheResult(identity, result, ttl) {
if (!identity) return;
const now = Date.now();
const localUntilMs = identity.validUntil > 0 ? identity.validUntil * 1000 : 0;
const maxTtl = localUntilMs > now ? localUntilMs - now : ttl;
this._sessionCache.set(identity.key, {
result,
expiresAt: now + Math.max(1000, Math.min(ttl, maxTtl || ttl))
});
// 不让旧账号/旧 proof 的缓存无限累积。
if (this._sessionCache.size > 24) {
const oldest = [...this._sessionCache.entries()].sort((a, b) => a[1].expiresAt - b[1].expiresAt)[0];
if (oldest) this._sessionCache.delete(oldest[0]);
}
},
_readCached(identity) {
const entry = identity && this._sessionCache.get(identity.key);
if (!entry) return undefined;
if (entry.expiresAt <= Date.now()) {
this._sessionCache.delete(identity.key);
return undefined;
}
return entry.result;
},
_clearSessionCache(scope) {
for (const [key] of this._sessionCache) {
if (String(key).startsWith(scope + '|')) this._sessionCache.delete(key);
}
// 取消旧身份的合并入口;已经发出的请求仍让其完成,但不会再影响新凭据。
for (const [key] of this._sessionRequests) {
if (String(key).startsWith(scope + '|')) this._sessionRequests.delete(key);
}
},
checkServerSession(scope, token) {
const identity = this._getSessionIdentity(scope, token);
if (!identity.token) {
// 旧版验证码接口可能不返回 session_token,本地 proof 仍是有效授权凭据。
return Promise.resolve(null);
}
const cached = this._readCached(identity);
if (cached !== undefined) return Promise.resolve(cached);
const existing = this._sessionRequests.get(identity.key);
if (existing) return existing;
const request = new Promise(resolve => {
let settled = false;
const finish = result => {
if (settled) return;
settled = true;
// 旧请求完成时不能把新解锁/新验证码的凭据覆盖或清掉。
if (!this._isCurrentIdentity(identity)) {
resolve(null);
return;
}
this._cacheResult(identity, result, result === null ? this._sessionTransientTtl : this._sessionCacheTtl);
resolve(result);
};
try {
CXRequests.request({
method: 'POST',
url: 'http://103.236.88.53:23123/index.php?s=/api/code/check_session',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: [
'scope=' + encodeURIComponent(scope),
'device_id=' + encodeURIComponent(identity.deviceId),
'session_token=' + encodeURIComponent(identity.token)
].join('&'),
timeout: 12000,
onload: res => {
// 401/403 本身就是明确拒绝,即使网关返回的正文不是 JSON 也不能把它误当成临时网络故障。
if (res.status === 401 || res.status === 403) {
finish(false);
return;
}
try {
const json = JSON.parse(res.responseText);
if (res.status === 200 && json.code === 1 && json.data && json.data.valid) {
if (this._isCurrentIdentity(identity)) {
if (scope === 'free-answer') {
ConfigStore.setVerifyValidUntil(json.data.valid_until || ConfigStore.getAnswerConfig().verifyValidUntil);
} else if (scope === 'ai-unlock') {
ConfigStore.setAIUnlockUntil(json.data.valid_until || ConfigStore.getAIUnlockUntil());
}
}
finish(true);
} else if (res.status === 200 && (json.code === 0 || json.data?.valid === false)) {
// 只有明确的服务端拒绝才视为授权失效;网络错误、网关错误、乱码响应都保留本地凭据。
finish(false);
} else {
finish(null);
}
} catch (_) {
finish(null);
}
},
onerror: () => finish(null),
ontimeout: () => finish(null)
});
} catch (_) {
finish(null);
}
});
this._sessionRequests.set(identity.key, request);
request.then(() => {
if (this._sessionRequests.get(identity.key) === request) this._sessionRequests.delete(identity.key);
});
return request;
},
async requireFreeAnswerAccess() {
await __scriptVerificationV1.refresh();
if (!__scriptVerificationV1.required('free-answer')) return true;
if (!ConfigStore.isVerifyValid()) { return false; }
const token = ConfigStore.getVerifySessionToken(), device = ConfigStore.getDeviceId(), until = ConfigStore.getAnswerConfig().verifyValidUntil;
const valid = await __scriptVerificationV1.checkSession('free-answer', device, token, until);
if (!valid) {
if (__scriptVerificationV1.sessionRejected('free-answer', device, token, until) && token === ConfigStore.getVerifySessionToken()) ConfigStore.clearVerifySession();
return false;
}
return ConfigStore.isVerifyValid();
},
async requireAIUnlockAccess() {
await __scriptVerificationV1.refresh();
if (!__scriptVerificationV1.required('ai-unlock')) return true;
if (!ConfigStore.isAIUnlocked()) return false;
const token = ConfigStore.getAIUnlockSessionToken(), device = ConfigStore.getDeviceId(), until = ConfigStore.getAIUnlockUntil();
const valid = await __scriptVerificationV1.checkSession('ai-unlock', device, token, until);
if (!valid && __scriptVerificationV1.sessionRejected('ai-unlock', device, token, until) && token === ConfigStore.getAIUnlockSessionToken()) ConfigStore.clearAIUnlockSession();
return valid && ConfigStore.isAIUnlocked();
}
};
// ==========================================
// Logger - 日志模块
// ==========================================
const Logger = {
_entries: [],
_onLog: null,
log(message, level = 'info') {
const entry = {
timestamp: new Date().toISOString(),
level,
message
};
this._entries.push(entry);
if (this._entries.length > 50) {
this._entries.shift();
}
if (typeof this._onLog === 'function') {
this._onLog(entry);
}
},
clearLogs() {
this._entries = [];
},
getEntries() {
return this._entries;
}
};
// 赞赏入口只展示公开套餐,不建单、不发码、不自动支付。
const installCXCommerce = (() => {
'use strict';
const configuredShopUrl = "https://120.79.20.248:24443/index.php?r=shop";
const cache = new Map();
const pending = new Map();
const installations = new WeakMap();
const maxAgeMs = 60000;
function endpoints() {
const shop = new URL(configuredShopUrl);
if (shop.protocol !== 'https:' || shop.username || shop.password || shop.hash ||
shop.searchParams.get('r') !== 'shop' || [...shop.searchParams.keys()].some(key => key !== 'r') ||
shop.searchParams.getAll('r').length !== 1 || !/\/index\.php$/.test(shop.pathname)) {
throw new Error('商城地址无效');
}
const products = new URL(shop.href);
products.search = '';
products.searchParams.set('r', 'api/shop/products');
return { shop: shop.href, products: products.href };
}
function safeInteger(value, minimum, maximum) {
// PHP PDO may serialize numeric columns as decimal strings.
if (typeof value === 'string' && !/^\d+$/.test(value)) return null;
if (typeof value !== 'string' && typeof value !== 'number') return null;
const number = Number(value);
return Number.isSafeInteger(number) && number >= minimum && number <= maximum ? number : null;
}
function readProducts(raw) {
if (raw?.code !== 1 || !Array.isArray(raw.data?.items) || raw.data.items.length > 1000) {
throw new Error('套餐响应无效');
}
const items = [];
const seen = new Set();
for (const row of raw.data.items) {
// Unscoped question-bank products apply to this helper. Other authorization
// types and script-scoped products cannot be assumed to apply to this script.
if (!row || row.kind !== 'question_bank' || row.script_id != null) continue;
const id = safeInteger(row.id, 1, 2147483647);
const price = safeInteger(row.price_cents, 1, 100000000);
const credits = safeInteger(row.credits, 1, 1000000000);
const bonus = safeInteger(row.bonus_credits ?? 0, 0, 1000000000);
const days = safeInteger(row.duration_days, 0, 36500);
const devices = safeInteger(row.device_limit, 0, 10000);
const trial = row.purchase_limit_key === 'trial_credits';
if ([id, price, credits, bonus, days, devices].some(value => value === null) || bonus >= credits || seen.has(id)) continue;
const base = credits - bonus;
if (row.base_credits !== undefined && safeInteger(row.base_credits, 1, 1000000000) !== base) continue;
seen.add(id);
items.push(Object.freeze({ id, price, credits, bonus, days, devices, trial }));
}
items.sort((a, b) => a.price - b.price || a.credits - b.credits || a.id - b.id);
return Object.freeze({ items: Object.freeze(items), paymentEnabled: raw.data.payment_enabled === true });
}
function getProducts(url, force) {
const stored = cache.get(url);
const age = stored ? Date.now() - stored.at : -1;
if (!force && stored && age >= 0 && age < maxAgeMs) return Promise.resolve(stored.value);
if (pending.has(url)) return pending.get(url);
const request = new Promise((resolve, reject) => {
let settled = false;
let handle = null;
const finish = (error, value) => {
if (settled) return;
settled = true;
clearTimeout(watchdog);
if (error) reject(error);
else { cache.set(url, { at: Date.now(), value }); resolve(value); }
};
const watchdog = setTimeout(() => {
finish(new Error('套餐读取超时'));
try { handle?.abort?.(); } catch (_) { }
}, 14000);
try {
if (typeof GM_xmlhttpRequest !== 'function') throw new Error('跨域请求不可用');
handle = CXRequests.request({
method: 'GET', url, anonymous: true, timeout: 12000,
headers: { Accept: 'application/json' },
onload(response) {
try {
if (Number(response.status) !== 200 || typeof response.responseText !== 'string' || response.responseText.length > 1048576) {
throw new Error('套餐读取失败');
}
if (response.finalUrl && new URL(response.finalUrl).href !== url) throw new Error('套餐来源不符');
finish(null, readProducts(JSON.parse(response.responseText)));
} catch (error) { finish(error); }
},
onerror: () => finish(new Error('套餐网络错误')),
ontimeout: () => finish(new Error('套餐读取超时')),
onabort: () => finish(new Error('套餐请求已取消'))
});
} catch (error) { finish(error); }
});
pending.set(url, request);
request.then(() => pending.delete(url), () => pending.delete(url));
return request;
}
return function installCXCommerce(doc) {
// The source panel owns its single blue support link; never create another.
doc?.getElementById('cx-shop-link')?.remove();
const root = doc?.getElementById('cx-shop-products');
if (!root) return { ready: Promise.resolve(false), refresh: () => Promise.resolve(false) };
const installed = installations.get(root);
if (installed) return installed;
let urls;
try { urls = endpoints(); }
catch (_) {
root.textContent = '暂未获取阶梯,请前往赞赏页查看';
const existing = doc.getElementById('cx-support-link');
existing?.removeAttribute('href');
return { ready: Promise.resolve(false), refresh: () => Promise.resolve(false) };
}
const shortcut = doc.getElementById('cx-support-link');
if (shortcut?.tagName === 'A') {
shortcut.href = urls.shop;
shortcut.target = '_blank';
shortcut.rel = 'noopener noreferrer';
shortcut.referrerPolicy = 'no-referrer';
shortcut.setAttribute('aria-label', '去赞赏,领积分(在新标签页打开)');
}
if (!doc.getElementById('cx-commerce-style')) {
const style = doc.createElement('style');
style.id = 'cx-commerce-style';
style.textContent = '#cx-shop-products{line-height:1.5;font-size:13px;color:#334155}#cx-shop-products ul{list-style:none;padding:0;margin:0}#cx-shop-products li{margin:2px 0}#cx-shop-products p{margin:4px 0}#cx-shop-products button{font:inherit;font-size:11px;color:#475569;background:#fff;border:1px solid #cbd5e1;border-radius:4px;padding:2px 7px;cursor:pointer}#cx-support-link:focus-visible,#cx-shop-products button:focus-visible{outline:2px solid #1d4ed8;outline-offset:3px}#cx-shop-products button:disabled{cursor:wait}';
(doc.head || doc.documentElement).appendChild(style);
}
const status = doc.createElement('p');
status.setAttribute('role', 'status');
const content = doc.createElement('div');
const controls = doc.createElement('p');
const refreshButton = doc.createElement('button');
refreshButton.type = 'button';
refreshButton.textContent = '刷新';
controls.append(refreshButton);
root.replaceChildren(status, content, controls);
root.setAttribute('aria-live', 'polite');
let currentLoad = null;
async function refresh(force = false) {
if (currentLoad) return currentLoad;
if (root.isConnected === false) return false;
refreshButton.disabled = true;
root.setAttribute('aria-busy', 'true');
status.hidden = false;
status.textContent = '正在读取阶梯…';
content.replaceChildren();
currentLoad = (async () => {
try {
const result = await getProducts(urls.products, force);
if (root.isConnected === false) return false;
if (!result.items.length) {
status.textContent = '暂未获取阶梯,请前往赞赏页查看';
return true;
}
const list = doc.createElement('ul');
for (const item of result.items) {
const row = doc.createElement('li');
const amount = (item.price / 100).toFixed(2).replace(/\.00$/, '').replace(/(\.\d)0$/, '$1');
row.textContent = `¥${amount} · ${item.credits}积分${item.bonus ? '(赠' + item.bonus + ')' : ''}`;
list.appendChild(row);
}
content.appendChild(list);
status.textContent = result.items.some(item => item.trial) ? '体验套餐限领规则以赞赏页为准' :
result.items.some(item => item.days || item.devices) ? '具体规则以赞赏页面为准' : '';
status.hidden = !status.textContent;
return true;
} catch (_) {
if (root.isConnected !== false) status.textContent = '暂未获取阶梯,请前往赞赏页查看';
return false;
} finally {
refreshButton.disabled = false;
root.setAttribute('aria-busy', 'false');
}
})();
try { return await currentLoad; }
finally { currentLoad = null; }
}
refreshButton.addEventListener('click', () => { void refresh(true); });
const controller = { ready: null, refresh };
installations.set(root, controller);
controller.ready = refresh();
return controller;
};
})();
// ==========================================
// UIPanel - UI 面板模块
// ==========================================
const UIPanel = {
_iframe: null,
_doc: null,
_isMinimized: false,
_activeTab: 'video',
_settingsVisible: false,
_running: false,
_startTime: null,
_timerInterval: null,
_purposeResolver: null,
// 2.1 - init(): 创建 iframe 并注入面板 HTML/CSS
init() {
if (this._iframe) return;
const iframe = document.createElement('iframe');
iframe.id = 'cx-helper-iframe';
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowtransparency', 'true');
Object.assign(iframe.style, {
position: 'fixed',
top: '20px',
right: '20px',
left: 'auto',
width: '480px',
maxWidth: 'calc(100vw - 24px)',
height: '560px',
maxHeight: 'calc(100vh - 24px)',
zIndex: '999999',
border: 'none',
borderRadius: '14px',
background: '#fff',
overflow: 'hidden',
boxShadow: '0 20px 60px rgba(0,0,0,0.12), 0 8px 20px rgba(0,0,0,0.06)'
});
document.body.appendChild(iframe);
this._iframe = iframe;
const doc = iframe.contentDocument || iframe.contentWindow.document;
this._doc = doc;
doc.open();
doc.write(this._buildHTML());
doc.close();
// 绑定事件
this._bindEvents();
// 启用标题栏拖拽
this.enableDrag(doc.getElementById('cx-header'));
// 连接 Logger
Logger._onLog = (entry) => this.log(entry.message, entry.level);
// 渲染已有日志
Logger.getEntries().forEach(e => this.log(e.message, e.level));
},
// 2.1 - destroy(): 移除 iframe
destroy() {
if (this._iframe) {
this._iframe.remove();
this._iframe = null;
this._doc = null;
}
if (this._timerInterval) {
clearInterval(this._timerInterval);
this._timerInterval = null;
}
Logger._onLog = null;
},
// 2.2 - enableDrag(): 绑定标题栏拖拽
enableDrag(handleEl) {
if (!handleEl || !this._iframe) return;
const iframe = this._iframe;
const doc = this._doc;
let isDragging = false;
let startX = 0, startY = 0, startLeft = 0, startTop = 0;
const onMove = (e) => {
if (!isDragging) return;
const dx = e.screenX - startX;
const dy = e.screenY - startY;
const maxLeft = Math.max(0, window.innerWidth - iframe.offsetWidth);
const maxTop = Math.max(0, window.innerHeight - iframe.offsetHeight);
iframe.style.left = Math.min(Math.max(0, startLeft + dx), maxLeft) + 'px';
iframe.style.top = Math.min(Math.max(0, startTop + dy), maxTop) + 'px';
iframe.style.right = 'auto';
};
const stopDrag = () => {
if (!isDragging) return;
isDragging = false;
iframe.style.transition = '';
doc.body.style.userSelect = '';
};
handleEl.addEventListener('mousedown', (e) => {
if (e.button !== 0 || e.target.closest?.('button, a, input, select, textarea, [role="button"], .cx-header-tools')) return;
isDragging = true;
startX = e.screenX;
startY = e.screenY;
// Convert right-positioned to left-positioned for dragging
const rect = iframe.getBoundingClientRect();
startLeft = rect.left;
startTop = rect.top;
iframe.style.left = startLeft + 'px';
iframe.style.right = 'auto';
iframe.style.transition = 'none';
doc.body.style.userSelect = 'none';
e.preventDefault();
});
doc.addEventListener('mousemove', onMove);
window.addEventListener('mousemove', onMove);
doc.addEventListener('mouseup', stopDrag);
window.addEventListener('mouseup', stopDrag);
window.addEventListener('blur', stopDrag);
},
// 2.3 - minimize(): 收缩为 50×50 悬浮图标
minimize() {
if (this._isMinimized || !this._iframe) return;
this._isMinimized = true;
const doc = this._doc;
doc.getElementById('cx-panel').style.display = 'none';
doc.getElementById('cx-mini').classList.add('show');
this._iframe.style.width = '50px';
this._iframe.style.height = '50px';
this._iframe.style.borderRadius = '50%';
},
// 2.3 - restore(): 恢复完整面板
restore() {
if (!this._isMinimized || !this._iframe) return;
this._isMinimized = false;
const doc = this._doc;
doc.getElementById('cx-panel').style.display = '';
doc.getElementById('cx-mini').classList.remove('show');
this._iframe.style.width = '480px';
this._iframe.style.maxWidth = 'calc(100vw - 24px)';
this._iframe.style.height = '560px';
this._iframe.style.maxHeight = 'calc(100vh - 24px)';
this._iframe.style.borderRadius = '14px';
},
// 2.4 - switchTab(): 切换标签页
switchTab(tab) {
if (!this._doc) return;
this._activeTab = tab;
const doc = this._doc;
// 更新标签按钮样式
doc.querySelectorAll('.cx-tab-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === tab);
});
// 更新内容区
doc.querySelectorAll('.cx-tab-content').forEach(el => {
el.style.display = el.dataset.tab === tab ? 'block' : 'none';
});
},
// 2.5 - showSettings(): 显示设置面板
showSettings() {
if (!this._doc) return;
this._settingsVisible = !this._settingsVisible;
this._doc.getElementById('cx-settings').style.display = this._settingsVisible ? 'block' : 'none';
},
// 2.6 - log(): 在日志区域追加日志
log(message, level = 'info') {
if (!this._doc) return;
const logArea = this._doc.getElementById('cx-log-area');
if (!logArea) return;
const distanceFromBottom = logArea.scrollHeight - logArea.scrollTop - logArea.clientHeight;
const shouldFollow = distanceFromBottom <= 24;
const div = this._doc.createElement('div');
div.className = 'cx-log-entry cx-log-' + level;
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false });
const icon = level === 'success' ? '✓' : level === 'error' ? '✗' : level === 'warn' ? '!' : '·';
const iconEl = this._doc.createElement('span');
iconEl.className = 'cx-log-icon';
iconEl.textContent = icon;
const timeEl = this._doc.createElement('time');
timeEl.className = 'cx-log-time';
timeEl.textContent = time;
const messageEl = this._doc.createElement('span');
messageEl.className = 'cx-log-message';
messageEl.textContent = String(message ?? '');
div.append(iconEl, timeEl, messageEl);
logArea.appendChild(div);
// 限制最多 50 条
while (logArea.children.length > 50) {
logArea.removeChild(logArea.firstChild);
}
const countEl = this._doc.getElementById('cx-log-count');
if (countEl) countEl.textContent = `${logArea.children.length} 条`;
if (shouldFollow) logArea.scrollTop = logArea.scrollHeight;
},
// 2.6 - clearLogs(): 清空日志区域
clearLogs() {
if (!this._doc) return;
const logArea = this._doc.getElementById('cx-log-area');
if (logArea) logArea.innerHTML = '';
const countEl = this._doc.getElementById('cx-log-count');
if (countEl) countEl.textContent = '0 条';
},
// 2.6 - setStatus(): 设置状态栏文字
setStatus(text, type = 'info') {
if (!this._doc) return;
const el = this._doc.getElementById('cx-status-text');
if (!el) return;
el.textContent = text;
el.className = 'cx-status-text cx-status-' + type;
},
// 2.6 - setRunning(): 设置运行状态
setRunning(isRunning) {
this._running = isRunning;
if (!this._doc) return;
const indicator = this._doc.getElementById('cx-status-indicator');
const timerEl = this._doc.getElementById('cx-status-timer');
// 先清理旧的定时器,防止内存泄漏
if (this._timerInterval) {
clearInterval(this._timerInterval);
this._timerInterval = null;
}
if (isRunning) {
this._startTime = Date.now();
if (indicator) indicator.className = 'cx-status-indicator running';
this._timerInterval = setInterval(() => {
if (timerEl && this._startTime) {
const elapsed = Math.floor((Date.now() - this._startTime) / 1000);
const h = String(Math.floor(elapsed / 3600)).padStart(2, '0');
const m = String(Math.floor((elapsed % 3600) / 60)).padStart(2, '0');
const s = String(elapsed % 60).padStart(2, '0');
timerEl.textContent = `${h}:${m}:${s}`;
}
}, 1000);
} else {
this._startTime = null;
if (indicator) indicator.className = 'cx-status-indicator';
if (timerEl) timerEl.textContent = '00:00:00';
if (this._timerInterval) {
clearInterval(this._timerInterval);
this._timerInterval = null;
}
}
},
// 2.6 - setProgress(): 设置进度
setProgress(current, total) {
if (!this._doc) return;
const el = this._doc.getElementById('cx-status-progress');
if (el) el.textContent = total > 0 ? `${current}/${total}` : '';
},
// 2.6 - setCountdown(): 设置倒计时
setCountdown(seconds) {
if (!this._doc) return;
const el = this._doc.getElementById('cx-status-countdown');
if (!el) return;
if (seconds > 0) {
const h = String(Math.floor(seconds / 3600)).padStart(2, '0');
const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
const s = String(seconds % 60).padStart(2, '0');
el.textContent = `倒计时 ${h}:${m}:${s}`;
el.style.display = 'inline';
} else {
el.textContent = '';
el.style.display = 'none';
}
},
// 2.6 - setButtonEnabled(): 设置按钮启用/禁用
setButtonEnabled(buttonId, enabled) {
if (!this._doc) return;
const btn = this._doc.getElementById(buttonId);
if (btn) btn.disabled = !enabled;
},
// 2.6 - setButtonLoading(): 设置按钮加载状态
setButtonLoading(buttonId, loading) {
if (!this._doc) return;
const btn = this._doc.getElementById(buttonId);
if (!btn) return;
if (loading) {
btn._origText = btn._origText || btn.textContent;
btn.textContent = '处理中...';
btn.disabled = true;
} else {
btn.textContent = btn._origText || btn.textContent;
btn.disabled = false;
}
},
_updatePurposeConfirmState() {
const doc = this._doc;
if (!doc) return;
const check = doc.getElementById('cx-purpose-check');
const confirm = doc.getElementById('cx-purpose-confirm');
if (confirm && check) confirm.disabled = check.disabled || !check.checked;
},
_markPurposeReadIfScrolled() {
const doc = this._doc;
if (!doc) return;
const scroll = doc.getElementById('cx-purpose-scroll');
const check = doc.getElementById('cx-purpose-check');
const hint = doc.getElementById('cx-purpose-hint');
if (!scroll || !check || !hint) return;
if (scroll.scrollTop + scroll.clientHeight >= scroll.scrollHeight - 4) {
check.disabled = false;
hint.textContent = '已阅读到末尾,可以勾选确认。';
}
this._updatePurposeConfirmState();
},
_closePurposeDialog(confirmed) {
const doc = this._doc;
if (!doc) return;
const dialog = doc.getElementById('cx-purpose-dialog');
if (dialog) dialog.style.display = 'none';
if (confirmed) ConfigStore.setStudyPurposeConfirmed();
if (this._purposeResolver) {
const resolve = this._purposeResolver;
this._purposeResolver = null;
resolve(!!confirmed);
}
},
confirmStudyPurpose() {
if (ConfigStore.isStudyPurposeConfirmed()) return Promise.resolve(true);
const doc = this._doc;
if (!doc) return Promise.resolve(false);
return new Promise(resolve => {
this._purposeResolver = resolve;
const dialog = doc.getElementById('cx-purpose-dialog');
const scroll = doc.getElementById('cx-purpose-scroll');
const check = doc.getElementById('cx-purpose-check');
const confirm = doc.getElementById('cx-purpose-confirm');
const hint = doc.getElementById('cx-purpose-hint');
if (check) {
check.checked = false;
check.disabled = true;
}
if (confirm) confirm.disabled = true;
if (hint) hint.textContent = '请先阅读到末尾,再勾选确认。';
if (dialog) dialog.style.display = 'flex';
if (scroll) {
scroll.scrollTop = 0;
setTimeout(() => {
this._markPurposeReadIfScrolled();
try { scroll.focus(); } catch (_) {}
}, 0);
}
});
},
// 内部:构建面板 HTML
_buildHTML() {
return `
免费验证码模式
📱
扫码观看广告获取验证码
验证后免费使用24小时
AI 答题配置
图片识别
检测会发送一张小测试图,可能产生少量费用。遇到图片题会先检查;未确认支持时跳过该题。
测试连接会发送一条短请求,按所选模型计费。
🚀 AI 限速解锁
默认答题间隔35秒,扫码观看广告获取解锁码后可加速至≈1.5秒
数据管理
清除所有存储数据,包括账号、密码、配置和日志。此操作不可撤销。
开始前请确认用途
本功能仅用于课程复习、回看和辅助整理学习进度,请完整阅读后再继续。
请先阅读到末尾,再勾选确认。
`;
},
// 内部:构建 CSS
_buildCSS() {
return `
html, body { margin:0; padding:0; overflow:hidden; height:100%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", Arial, sans-serif;
color: #2c3e50; background: transparent; font-size: 13px; }
* { box-sizing:border-box; }
/* 最小化图标 */
.cx-mini { position:absolute; inset:0; background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; border-radius:50%;
display:none; align-items:center; justify-content:center; cursor:pointer;
font-size:22px; box-shadow:0 4px 16px rgba(99,102,241,0.45); transition:all .3s; }
.cx-mini:hover { transform:scale(1.1); box-shadow:0 6px 22px rgba(99,102,241,0.55); }
.cx-mini.show { display:flex; }
/* 主面板 */
.cx-panel { width:100%; height:100%; background:#f8fafc; border-radius:16px;
position:relative; overflow:hidden; display:flex; flex-direction:column; max-height:100vh; }
/* 标题栏 */
.cx-header { height:48px; background:linear-gradient(135deg,#6366f1 0%,#8b5cf6 50%,#a78bfa 100%); color:#fff;
display:flex; align-items:center; justify-content:space-between; gap:8px; padding:0 14px;
cursor:move; flex-shrink:0; user-select:none; }
.cx-header-title { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
font-size:14px; font-weight:700; text-shadow:0 1px 3px rgba(0,0,0,0.12); }
.cx-header-tools { display:flex; align-items:center; gap:6px; flex-shrink:0; }
.cx-header-wechat { min-height:28px; min-width:112px; padding:3px 7px; border:1px solid rgba(255,255,255,.5);
border-radius:6px; background:rgba(255,255,255,.12); color:#fff;
font-family:inherit; font-size:11px; font-weight:500; line-height:1.5; white-space:nowrap; cursor:pointer; }
.cx-header-wechat:hover { background:rgba(255,255,255,.22); }
.cx-header-wechat:focus-visible { outline:2px solid #fff; outline-offset:2px; }
.cx-tool-btn { cursor:pointer; font-size:15px; opacity:.85; transition:all .2s; padding:4px 6px;
border-radius:6px; }
.cx-tool-btn:hover { opacity:1; transform:scale(1.12); background:rgba(255,255,255,0.18); }
/* 标签栏 */
.cx-tab-bar { display:flex; gap:12px; background:#f8fafc; border-bottom:1px solid #e2e8f0; flex-shrink:0; padding:6px 14px; }
.cx-tab-btn { flex:1; min-height:48px; display:flex; align-items:center; justify-content:center;
text-align:center; padding:10px 12px; font-size:14px; cursor:pointer;
color:#64748b; transition:all .2s; border:1px solid transparent; font-weight:600;
margin:0; border-radius:10px; }
.cx-tab-btn:hover { color:#6366f1; background:rgba(99,102,241,0.04); }
.cx-tab-btn.active { color:#4f46e5; border-color:#c7d2fe; font-weight:700; background:#eef2ff; box-shadow:0 2px 6px rgba(99,102,241,.12); }
/* 内容区 — 关键:允许滚动 */
.cx-body { flex:1 1 0; overflow-y:auto; overflow-x:hidden; padding:14px; min-height:0; background:#f8fafc; }
.cx-body::-webkit-scrollbar { width:5px; }
.cx-body::-webkit-scrollbar-track { background:transparent; }
.cx-body::-webkit-scrollbar-thumb { background:#cbd5e1; border-radius:10px; }
.cx-body::-webkit-scrollbar-thumb:hover { background:#94a3b8; }
/* 设置面板 */
.cx-settings { display:none; position:absolute; top:108px; bottom:138px; left:0; width:100%;
height:auto; background:#f8fafc; z-index:99; overflow-y:auto;
box-sizing:border-box; }
.cx-panel.cx-log-collapsed .cx-settings { bottom:62px; }
.cx-settings::-webkit-scrollbar { width:5px; }
.cx-settings::-webkit-scrollbar-thumb { background:#cbd5e1; border-radius:3px; }
.cx-settings-header { display:flex; justify-content:space-between; align-items:center;
padding:14px 18px; background:#fff; border-bottom:1px solid #e2e8f0; font-weight:700; font-size:14px; color:#1e293b; }
.cx-settings-close { cursor:pointer; font-size:16px; color:#94a3b8; transition:all .2s; width:28px; height:28px;
display:flex; align-items:center; justify-content:center; border-radius:8px; }
.cx-settings-close:hover { color:#ef4444; background:#fef2f2; }
.cx-settings-body { padding:14px; }
.cx-settings-section { background:#fff; border-radius:12px; padding:16px; margin-bottom:12px;
box-shadow:0 1px 3px rgba(0,0,0,0.04); border:1px solid #e2e8f0; transition:box-shadow .2s; }
.cx-settings-section:hover { box-shadow:0 2px 8px rgba(0,0,0,0.06); }
.cx-settings-title { font-weight:700; font-size:13px; margin-bottom:10px; color:#1e293b; }
.cx-settings-danger-zone { border:1px solid #fecaca; background:#fef2f2; }
.cx-form-item { margin-bottom:10px; }
.cx-form-item label { font-size:13px; color:#64748b; }
.cx-form-item select { padding:7px 12px; border:1.5px solid #e2e8f0; border-radius:8px;
font-size:13px; background:#fff; margin-left:8px; outline:none; transition:border-color .2s; }
.cx-form-item select:focus { border-color:#6366f1; }
.cx-checkbox-label { display:flex; align-items:center; gap:8px; cursor:pointer; padding:6px 8px;
border-radius:8px; transition:background .2s; }
.cx-checkbox-label:hover { background:#eef2ff; }
.cx-checkbox-label input { margin:0; width:16px; height:16px; cursor:pointer; accent-color:#6366f1; }
.cx-radio-group { display:flex; flex-direction:column; gap:4px; }
.cx-radio-option { display:flex; align-items:center; gap:8px; padding:8px 10px; border-radius:8px;
cursor:pointer; transition:background .2s; font-size:13px; }
.cx-radio-option:hover { background:#eef2ff; }
.cx-radio-option input { margin:0; cursor:pointer; accent-color:#6366f1; }
.cx-settings-footer { display:flex; gap:10px; justify-content:center; margin-top:14px; }
/* 按钮 */
.cx-btn { min-height:42px; padding:10px 20px; border:none; border-radius:10px; font-size:13px; font-weight:600;
cursor:pointer; transition:all .2s; letter-spacing:0.2px; }
.cx-btn:hover { transform:translateY(-1px); box-shadow:0 4px 12px rgba(0,0,0,0.08); }
.cx-btn:active { transform:translateY(0); }
.cx-btn-primary { background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; }
.cx-btn-primary:hover { box-shadow:0 4px 16px rgba(99,102,241,0.35); }
.cx-btn-secondary { background:#f1f5f9; color:#64748b; }
.cx-btn-secondary:hover { background:#e2e8f0; box-shadow:0 2px 8px rgba(0,0,0,0.04); }
.cx-btn-success { background:linear-gradient(135deg,#10b981,#059669); color:#fff; }
.cx-btn-success:hover { box-shadow:0 4px 16px rgba(16,185,129,0.35); }
.cx-btn-warning { background:linear-gradient(135deg,#f59e0b,#d97706); color:#fff; }
.cx-btn-warning:hover { box-shadow:0 4px 16px rgba(245,158,11,0.35); }
.cx-btn-danger { background:linear-gradient(135deg,#ef4444,#dc2626); color:#fff; width:100%; }
.cx-btn-danger:hover { box-shadow:0 4px 16px rgba(239,68,68,0.35); }
.cx-btn-info { background:#f1f5f9; color:#64748b; }
.cx-btn-info:hover { background:#e2e8f0; }
.cx-btn:disabled { opacity:.45; cursor:not-allowed; transform:none; box-shadow:none; }
/* 日志区域 */
.cx-log-wrap { flex:0 0 106px; height:106px; position:relative; border-top:1px solid #e2e8f0; background:#f8fafc; }
.cx-log-head { height:30px; display:flex; align-items:center; justify-content:space-between;
padding:0 14px; box-sizing:border-box; background:#fff; border-bottom:1px solid #eef2f7; }
.cx-log-title { display:flex; align-items:center; gap:7px; color:#475569; font-size:11px; font-weight:700; }
.cx-log-title-mark { width:7px; height:7px; border-radius:50%; background:#10b981; box-shadow:0 0 0 3px #d1fae5; }
.cx-log-count { color:#94a3b8; font-size:10px; font-weight:500; }
.cx-log-actions { display:flex; align-items:center; gap:6px; }
.cx-log-toggle,
.cx-log-clear { padding:3px 7px; border:1px solid #e2e8f0; border-radius:5px; background:#fff;
color:#94a3b8; cursor:pointer; font-size:10px; line-height:1.2; transition:all .18s ease; }
.cx-log-toggle:hover,
.cx-log-clear:hover { color:#6366f1; border-color:#c7d2fe; background:#eef2ff; }
.cx-log-toggle:focus-visible,
.cx-log-clear:focus-visible { outline:3px solid rgba(99,102,241,.2); outline-offset:1px; }
.cx-log-area { height:76px; overflow-y:auto; padding:6px 14px 8px; box-sizing:border-box;
font-size:11px; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;
scroll-behavior:auto; }
.cx-log-wrap.is-collapsed { flex-basis:30px; height:30px; }
.cx-log-wrap.is-collapsed .cx-log-area { display:none; }
.cx-log-area::-webkit-scrollbar { width:3px; }
.cx-log-area::-webkit-scrollbar-track { background:transparent; }
.cx-log-area::-webkit-scrollbar-thumb { background:#cbd5e1; border-radius:3px; }
.cx-log-entry { display:grid; grid-template-columns:14px 56px minmax(0,1fr); align-items:start; gap:6px;
padding:5px 8px; margin:3px 0; line-height:1.45; border-radius:7px; font-size:11px;
border:1px solid transparent; animation:cx-log-in .18s cubic-bezier(.16,1,.3,1); }
.cx-log-icon { text-align:center; font-weight:800; }
.cx-log-time { color:#94a3b8; font-variant-numeric:tabular-nums; white-space:nowrap; }
.cx-log-message { min-width:0; overflow-wrap:anywhere; }
@keyframes cx-log-in { from{opacity:0;transform:translateY(4px);} to{opacity:1;transform:translateY(0);} }
.cx-log-info { color:#475569; background:#f8fafc; border-color:#e2e8f0; }
.cx-log-info .cx-log-icon { color:#64748b; }
.cx-log-success { color:#047857; background:#ecfdf5; border-color:#bbf7d0; }
.cx-log-success .cx-log-icon { color:#059669; }
.cx-log-warn { color:#a16207; background:#fffbeb; border-color:#fde68a; }
.cx-log-warn .cx-log-icon { color:#d97706; }
.cx-log-error { color:#b91c1c; background:#fef2f2; border-color:#fecaca; }
.cx-log-error .cx-log-icon { color:#dc2626; }
@media (prefers-reduced-motion: reduce) {
.cx-log-entry, .cx-status-indicator.running { animation:none; }
}
/* 状态栏 */
.cx-status-bar { height:32px; background:#fff; border-top:1px solid #e2e8f0;
display:flex; align-items:center; justify-content:space-between; padding:0 14px;
font-size:11px; color:#94a3b8; flex-shrink:0; }
.cx-status-left { display:flex; align-items:center; gap:8px; }
.cx-status-right { display:flex; align-items:center; }
.cx-status-indicator { width:7px; height:7px; border-radius:50%; background:#cbd5e1; display:inline-block; }
.cx-status-indicator.running { background:#10b981; animation:cx-pulse 1.5s infinite; }
@keyframes cx-pulse { 0%,100%{opacity:1;} 50%{opacity:.4;} }
.cx-status-text { color:#64748b; }
.cx-status-text.cx-status-info { color:#64748b; }
.cx-status-text.cx-status-success { color:#10b981; }
.cx-status-text.cx-status-error { color:#ef4444; }
.cx-status-progress { color:#6366f1; font-weight:700; }
.cx-status-countdown { color:#f59e0b; font-weight:700; }
.cx-status-timer { font-family:'JetBrains Mono',Consolas,"Courier New",monospace; color:#94a3b8; font-size:11px; }
/* 表单通用 */
.cx-form-row { display:flex; flex-direction:column; gap:4px; }
.cx-form-row-inline { flex-direction:row; gap:10px; }
.cx-form-col { flex:1; display:flex; flex-direction:column; gap:4px; }
.cx-form-label { font-size:12px; color:#64748b; font-weight:600; }
.cx-required { color:#ef4444; margin-left:2px; }
.cx-input { padding:9px 12px; border:1.5px solid #e2e8f0; border-radius:10px; font-size:13px;
outline:none; transition:all .2s; box-sizing:border-box; width:100%; background:#fff; }
.cx-input:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,0.1); }
.cx-input.cx-input-error { border-color:#ef4444; box-shadow:0 0 0 3px rgba(239,68,68,0.1); }
.cx-form-error { font-size:11px; color:#ef4444; min-height:14px; }
/* 加载动画 */
.cx-loading::after { content:''; display:inline-block; width:12px; height:12px;
border:2px solid rgba(255,255,255,0.4); border-top-color:#fff; border-radius:50%;
animation:cx-spin .6s linear infinite; margin-left:6px; vertical-align:middle; }
@keyframes cx-spin { to{transform:rotate(360deg);} }
/* 视频面板 */
.cx-video-panel { display:flex; flex-direction:column; gap:12px; }
.cx-video-status-card { background:#fff; border-radius:14px; padding:16px;
box-shadow:0 1px 3px rgba(0,0,0,0.04); border:1px solid #e2e8f0; transition:box-shadow .2s; }
.cx-video-status-card:hover { box-shadow:0 2px 8px rgba(0,0,0,0.06); }
.cx-video-info-row { display:flex; align-items:center; margin-bottom:8px; font-size:13px; }
.cx-video-label { color:#94a3b8; min-width:80px; flex-shrink:0; font-weight:500; }
.cx-video-value { color:#1e293b; font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.cx-video-progress-wrap { margin-top:6px; }
.cx-video-progress-track { height:6px; background:#e2e8f0; border-radius:3px; overflow:hidden; }
.cx-video-progress-bar { height:100%; background:linear-gradient(90deg,#6366f1,#10b981);
border-radius:3px; transition:width .5s ease; min-width:0; }
.cx-video-actions { display:flex; gap:10px; }
.cx-video-actions .cx-btn { flex:1; min-height:46px; padding:11px 0; font-size:13px; }
/* 答题模块 */
.cx-answer-panel { display:flex; flex-direction:column; gap:10px; }
.cx-answer-mode-bar { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; background:#fff; border-radius:14px; padding:6px;
border:1px solid #e2e8f0; }
.cx-answer-mode-option { min-height:56px; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:3px;
padding:8px 6px; border-radius:10px; cursor:pointer; font-size:13px; line-height:1.25; font-weight:600;
transition:all .2s; text-align:center; color:#64748b; }
.cx-mode-icon { font-size:18px; line-height:1; }
.cx-answer-mode-option:hover { background:#eef2ff; color:#6366f1; }
.cx-answer-mode-option input { display:none; }
.cx-answer-mode-option:has(input:checked) { background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff;
box-shadow:0 2px 8px rgba(99,102,241,0.3); }
.cx-fallback-row { display:grid; grid-template-columns:110px minmax(0,1fr); align-items:center; gap:10px; }
.cx-fallback-row .cx-form-label { margin:0; white-space:nowrap; }
.cx-fallback-row .cx-input { min-width:0; }
.cx-answer-area { }
.cx-answer-card { background:#fff; border-radius:14px; padding:16px;
box-shadow:0 1px 3px rgba(0,0,0,0.04); border:1px solid #e2e8f0; transition:box-shadow .2s; }
.cx-answer-card:hover { box-shadow:0 2px 8px rgba(0,0,0,0.06); }
.cx-answer-card-title { font-weight:700; font-size:13px; color:#1e293b; margin-bottom:12px; }
.cx-free-qr-placeholder { display:flex; flex-direction:column; align-items:center; gap:8px;
padding:20px; background:#f8fafc; border-radius:12px; border:1.5px dashed #c7d2fe; }
.cx-free-qr-icon { font-size:36px; }
.cx-free-qr-text { font-size:12px; color:#94a3b8; }
.cx-input-group { display:flex; gap:8px; align-items:center; }
.cx-btn-sm { min-height:40px; padding:9px 18px; font-size:12px; }
.cx-btn-xs { min-height:34px; padding:7px 12px; font-size:11px; border-radius:7px; }
.cx-answer-status { font-size:12px; margin-top:10px; min-height:16px; }
/* AI 配置沿用面板的浅色卡片、紫色重点和表单间距。 */
#cx-answer-ai-area .cx-ai-fields { display:flex; flex-direction:column; gap:12px; min-width:0; }
#cx-answer-ai-area .cx-ai-fields .cx-input { min-width:0; color:#1e293b; background:#fff; }
#cx-answer-ai-area select option { background:#fff; color:#1e293b; }
#cx-answer-ai-area .cx-input-group .cx-input { flex:1; }
#cx-answer-ai-area .cx-input-group .cx-btn { flex-shrink:0; }
.cx-ai-label-row { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:2px; }
.cx-ai-help { color:#64748b; font-size:11px; line-height:1.6; overflow-wrap:anywhere; }
.cx-ai-help a { color:#4f46e5; text-underline-offset:2px; }
.cx-ai-model-current { display:flex; flex-direction:column; gap:3px; background:#f8fafc; border-left:3px solid #818cf8;
border-radius:5px; padding:9px 11px; min-width:0; color:#475569; font-size:11px; line-height:1.5; overflow-wrap:anywhere; }
.cx-ai-model-current strong { color:#1e293b; font-size:12px; font-weight:600; }
.cx-ai-model-current strong:empty { display:none; }
.cx-ai-manual { margin-top:4px; font-size:12px; }
.cx-ai-manual summary { color:#4f46e5; cursor:pointer; width:fit-content; padding:5px 0; }
.cx-ai-manual[open] summary { margin-bottom:5px; }
.cx-ai-manual label { display:block; margin-bottom:5px; }
.cx-ai-manual .cx-ai-help { margin-top:5px; }
.cx-ai-vision { border-top:1px solid #e2e8f0; padding-top:10px; }
#cx-ai-status { margin-top:0; color:#475569; line-height:1.6; }
#cx-ai-status[data-state="error"], #cx-ai-vision-status[data-state="error"], #cx-ai-model-status[data-state="error"] { color:#b91c1c; }
#cx-ai-status[data-state="success"], #cx-ai-vision-status[data-state="success"] { color:#047857; }
.cx-ai-unlock-section { border-top:1px solid #e2e8f0; margin:16px 0 0; padding-top:14px; }
#cx-answer-ai-area .cx-btn:focus-visible, #cx-answer-ai-area summary:focus-visible {
outline:3px solid #818cf8; outline-offset:2px; }
#cx-answer-ai-area .cx-input[aria-invalid="true"] { border-color:#dc2626; }
.cx-paid-credits-row { display:flex; align-items:center; gap:10px; padding:12px 14px;
background:#f8fafc; border-radius:10px; border:1px solid #e2e8f0; }
.cx-paid-credits-label { font-size:13px; color:#64748b; }
.cx-paid-credits-value { font-size:20px; font-weight:800; color:#6366f1; }
.cx-support-entry { width:100%; min-height:40px; display:flex; align-items:center;
justify-content:center; gap:8px; box-sizing:border-box; margin-top:10px; padding:8px 12px;
border:1px solid #4a90e2; border-radius:8px; background:#eaf3ff; color:#2f6fca;
font-size:14px; line-height:1.5; font-weight:600; text-decoration:none; }
.cx-support-entry:hover { background:#e5f0ff; border-color:#2f6fca; }
.cx-support-entry:focus-visible { outline:2px solid #2f6fca; outline-offset:2px; }
.cx-answer-actions { display:flex; gap:10px; margin-top:6px; }
.cx-answer-actions .cx-btn { flex:1; min-height:46px; }
/* 公开套餐阶梯,金额与赠送以后台商品为准。 */
.cx-buy-info { margin-top:8px; padding:10px 12px; border:1px solid #e2e8f0;
border-radius:6px; background:#f8fafc; font-size:13px; line-height:1.6; }
.cx-buy-info-title { margin-bottom:4px; color:#64748b; font-size:13px; font-weight:600; }
#cx-shop-products { color:#334155; font-size:13px; font-variant-numeric:tabular-nums; }
@media (max-width:520px) {
.cx-answer-mode-option { min-height:50px; font-size:12px; }
.cx-mode-icon { font-size:16px; }
.cx-fallback-row { grid-template-columns:1fr; gap:6px; }
.cx-answer-actions { flex-direction:column; }
}
@media (max-width:380px) {
.cx-header { gap:5px; padding:0 10px; }
.cx-header-title { font-size:12px; }
.cx-header-tools { gap:2px; }
.cx-header-wechat { min-width:104px; padding:3px 5px; }
}
@media (max-height:700px) {
.cx-body { padding:10px; }
.cx-tab-bar { padding:4px 10px; }
.cx-tab-btn { min-height:44px; }
.cx-log-wrap:not(.is-collapsed) { flex-basis:104px; height:104px; }
.cx-log-wrap:not(.is-collapsed) .cx-log-area { height:74px; }
}
/* AI 答题提示 */
.cx-ai-hint { font-size:12px; color:#64748b; margin-bottom:12px; line-height:1.6; }
.cx-ai-link { color:#6366f1; text-decoration:none; font-weight:500; }
.cx-ai-link:hover { text-decoration:underline; }
.cx-ai-free-tip { margin-top:8px; font-size:11px; color:#94a3b8; }
/* 视频内联设置卡片 */
.cx-video-settings-card { background:#fff; border-radius:14px; padding:14px 16px; margin-top:12px;
box-shadow:0 1px 3px rgba(0,0,0,0.04); border:1px solid #e2e8f0; transition:box-shadow .2s; }
.cx-video-settings-card:hover { box-shadow:0 2px 8px rgba(0,0,0,0.06); }
.cx-card-title { font-weight:700; font-size:13px; color:#1e293b; margin-bottom:10px; }
.cx-inline-setting { display:flex; align-items:center; padding:6px 0; }
.cx-setting-label { font-size:13px; color:#64748b; margin-right:10px; font-weight:500; }
.cx-select-inline { padding:6px 10px; border:1.5px solid #e2e8f0; border-radius:10px;
font-size:13px; background:#fff; outline:none; transition:border-color .2s; cursor:pointer; }
.cx-select-inline:focus { border-color:#6366f1; }
.cx-toggle-label { display:flex; align-items:center; gap:8px; cursor:pointer; font-size:13px;
color:#64748b; padding:2px 0; }
.cx-toggle-label input { margin:0; width:16px; height:16px; cursor:pointer; accent-color:#6366f1; }
/* 用途确认弹窗 */
.cx-purpose-dialog { display:none; position:absolute; inset:0; z-index:150; background:rgba(15,23,42,.48);
align-items:center; justify-content:center; padding:18px; backdrop-filter:blur(2px); }
.cx-purpose-card { width:100%; max-width:430px; max-height:92%; background:#fff; border-radius:14px;
border:1px solid #e2e8f0; box-shadow:0 22px 54px rgba(15,23,42,.24); padding:18px; display:flex; flex-direction:column; gap:12px; }
.cx-purpose-head h3 { margin:0 0 6px; font-size:16px; color:#111827; }
.cx-purpose-head p { margin:0; font-size:12px; color:#64748b; line-height:1.6; }
.cx-purpose-scroll { max-height:132px; overflow:auto; padding:12px; border:1px solid #dbe3ee; border-radius:10px;
background:#f8fafc; color:#334155; font-size:12px; line-height:1.7; outline:none; }
.cx-purpose-scroll p { margin:0 0 10px; }
.cx-purpose-scroll p:last-child { margin-bottom:0; }
.cx-purpose-hint { margin:0; font-size:12px; color:#d97706; font-weight:700; }
.cx-purpose-check { display:flex; gap:9px; align-items:flex-start; font-size:12px; color:#334155; line-height:1.6; }
.cx-purpose-check input { width:18px; height:18px; margin-top:1px; flex:0 0 auto; accent-color:#2563eb; }
.cx-purpose-actions { display:flex; gap:12px; }
.cx-purpose-actions button { flex:1; min-height:42px; border-radius:10px; border:1px solid #cbd5e1;
font-size:13px; font-weight:800; cursor:pointer; transition:all .15s; }
.cx-purpose-actions button:disabled { opacity:.5; cursor:not-allowed; }
.cx-purpose-cancel { background:#f8fafc; color:#334155; }
.cx-purpose-confirm { background:#2563eb; color:#fff; border-color:#2563eb; }
/* 底部留白防止滚动不到底 */
.cx-tab-content { padding-bottom:8px; }
`;
},
// 内部:绑定事件
_bindEvents() {
const doc = this._doc;
// 最小化按钮
doc.getElementById('cx-btn-minimize').addEventListener('click', () => this.minimize());
// 最小化图标点击恢复
doc.getElementById('cx-mini').addEventListener('click', () => this.restore());
// 日志区可收起,内容区与日志区始终保持独立,不互相遮挡
const logWrap = doc.querySelector('.cx-log-wrap');
const logToggle = doc.getElementById('cx-btn-toggle-logs');
logToggle?.addEventListener('click', () => {
const collapsed = logWrap?.classList.toggle('is-collapsed') || false;
doc.getElementById('cx-panel')?.classList.toggle('cx-log-collapsed', collapsed);
logToggle.setAttribute('aria-expanded', String(!collapsed));
logToggle.textContent = collapsed ? '展开' : '收起';
});
// 日志工具栏:只清空当前日志,不影响账号和其它配置
doc.getElementById('cx-btn-clear-logs')?.addEventListener('click', () => {
Logger.clearLogs();
this.clearLogs();
this.setStatus('日志已清空', 'info');
});
// 仅匿名读取公开套餐;赞赏页由用户点击链接后打开。
installCXCommerce(doc);
doc.getElementById('cx-purpose-scroll')?.addEventListener('scroll', () => this._markPurposeReadIfScrolled());
doc.getElementById('cx-purpose-check')?.addEventListener('change', () => this._updatePurposeConfirmState());
doc.getElementById('cx-purpose-cancel')?.addEventListener('click', () => this._closePurposeDialog(false));
doc.getElementById('cx-purpose-confirm')?.addEventListener('click', () => {
const btn = doc.getElementById('cx-purpose-confirm');
if (btn && !btn.disabled) this._closePurposeDialog(true);
});
doc.addEventListener('keydown', e => {
if (e.key === 'Escape' && doc.getElementById('cx-purpose-dialog')?.style.display === 'flex') {
this._closePurposeDialog(false);
}
});
// 反馈微信号复制
const feedbackWechat = doc.getElementById('cx-feedback-wechat');
let wechatResetTimer;
feedbackWechat?.addEventListener('click', async () => {
try {
if (typeof GM_setClipboard === 'function') await GM_setClipboard('C919irt', 'text');
else if (navigator.clipboard?.writeText) await navigator.clipboard.writeText('C919irt');
else throw new Error('clipboard');
feedbackWechat.textContent = '已复制 ✅';
feedbackWechat.title = '微信号已复制:C919irt';
} catch (_) {
feedbackWechat.textContent = '微信:C919irt';
feedbackWechat.title = '复制失败,请手动复制微信号:C919irt';
}
clearTimeout(wechatResetTimer);
wechatResetTimer = setTimeout(() => {
feedbackWechat.textContent = '微信:C919irt 📋';
feedbackWechat.title = '反馈BUG需提供账号;点击复制微信号';
}, 1500);
});
// 设置按钮
doc.getElementById('cx-btn-settings').addEventListener('click', () => this.showSettings());
// 设置面板关闭
doc.getElementById('cx-settings-close').addEventListener('click', () => {
this._settingsVisible = false;
doc.getElementById('cx-settings').style.display = 'none';
});
// 设置面板保存
doc.getElementById('cx-settings-save').addEventListener('click', () => {
// 保存视频配置
const playbackRate = parseFloat(doc.getElementById('cx-cfg-playback-rate').value) || 2;
const autoAdvance = doc.getElementById('cx-cfg-auto-advance').checked;
const autoSkipQuiz = doc.getElementById('cx-cfg-auto-skip-quiz').checked;
const autoAnswerQuiz = doc.getElementById('cx-cfg-auto-answer-quiz')?.checked !== false;
const quizMode = doc.getElementById('cx-cfg-quiz-mode')?.value || 'free';
ConfigStore.setVideoConfig({ playbackRate, autoAdvance, autoSkipQuiz, autoAnswerQuiz, quizMode });
// 立即更新当前视频速度
if (typeof VideoModule !== 'undefined' && VideoModule.isPlaying()) {
VideoModule.setPlaybackRate(playbackRate);
}
// 同步到内联设置控件
const rateInline = doc.getElementById('cx-video-rate-inline');
if (rateInline) rateInline.value = String(playbackRate);
const advInline = doc.getElementById('cx-video-advance-inline');
if (advInline) advInline.checked = autoAdvance;
const skipInline = doc.getElementById('cx-video-skip-quiz-inline');
if (skipInline) skipInline.checked = autoSkipQuiz;
const autoAnswerInline = doc.getElementById('cx-video-auto-answer-quiz-inline');
if (autoAnswerInline) autoAnswerInline.checked = autoAnswerQuiz;
const quizModeInline = doc.getElementById('cx-video-quiz-mode-inline');
if (quizModeInline) {
quizModeInline.value = quizMode;
quizModeInline.disabled = !autoAnswerQuiz;
}
// 保存答题模式配置
const answerMode = doc.querySelector('input[name="cx-answer-mode"]:checked')?.value || 'free';
const answerCfg = ConfigStore.getAnswerConfig();
answerCfg.mode = answerMode;
ConfigStore.setAnswerConfig(answerCfg);
Logger.log('设置已保存', 'success');
this._settingsVisible = false;
doc.getElementById('cx-settings').style.display = 'none';
});
// 设置面板取消
doc.getElementById('cx-settings-cancel').addEventListener('click', () => {
this._settingsVisible = false;
doc.getElementById('cx-settings').style.display = 'none';
});
// 标签页切换
doc.querySelectorAll('.cx-tab-btn').forEach(btn => {
btn.addEventListener('click', () => this.switchTab(btn.dataset.tab));
});
// 播放倍速即时更新
doc.getElementById('cx-cfg-playback-rate').addEventListener('change', (e) => {
const rate = parseFloat(e.target.value) || 2;
if (typeof VideoModule !== 'undefined' && VideoModule.isPlaying()) {
VideoModule.setPlaybackRate(rate);
}
});
// 清除数据按钮
doc.getElementById('cx-btn-clear-data')?.addEventListener('click', () => {
if (confirm('确定要清除所有数据吗?此操作不可撤销,将删除所有账号、密码、配置和日志。')) {
RunStateManager.stopModule();
ConfigStore.clearAll();
Logger.clearLogs();
this.clearLogs();
this.setRunning(false);
this.setStatus('数据已清除', 'info');
Logger.log('所有数据已清除', 'success');
}
});
// 视频内联设置 — 倍速
doc.getElementById('cx-video-rate-inline')?.addEventListener('change', (e) => {
const rate = parseFloat(e.target.value) || 2;
const cfg = ConfigStore.getVideoConfig();
cfg.playbackRate = rate;
ConfigStore.setVideoConfig(cfg);
// 同步设置面板
const settingsRate = doc.getElementById('cx-cfg-playback-rate');
if (settingsRate) settingsRate.value = String(rate);
if (typeof VideoModule !== 'undefined' && VideoModule.isPlaying()) {
VideoModule.setPlaybackRate(rate);
}
Logger.log(`播放倍速已设为 ${rate}x`, 'info');
});
// 视频内联设置 — 自动推进
doc.getElementById('cx-video-advance-inline')?.addEventListener('change', (e) => {
const cfg = ConfigStore.getVideoConfig();
cfg.autoAdvance = e.target.checked;
ConfigStore.setVideoConfig(cfg);
const settingsCb = doc.getElementById('cx-cfg-auto-advance');
if (settingsCb) settingsCb.checked = e.target.checked;
Logger.log(`自动推进章节: ${e.target.checked ? '开启' : '关闭'}`, 'info');
});
// 视频内联设置 — 跳过弹窗测验
doc.getElementById('cx-video-skip-quiz-inline')?.addEventListener('change', (e) => {
const cfg = ConfigStore.getVideoConfig();
cfg.autoSkipQuiz = e.target.checked;
ConfigStore.setVideoConfig(cfg);
const settingsCb = doc.getElementById('cx-cfg-auto-skip-quiz');
if (settingsCb) settingsCb.checked = e.target.checked;
Logger.log(`自动跳过弹窗测验: ${e.target.checked ? '开启' : '关闭'}`, 'info');
});
// 视频内联设置 — 自动答章节测验复选框
doc.getElementById('cx-video-auto-answer-quiz-inline')?.addEventListener('change', (e) => {
const cfg = ConfigStore.getVideoConfig();
cfg.autoAnswerQuiz = e.target.checked;
ConfigStore.setVideoConfig(cfg);
// 联动下拉框禁用状态
const modeSelect = doc.getElementById('cx-video-quiz-mode-inline');
if (modeSelect) modeSelect.disabled = !e.target.checked;
// 同步设置面板
const settingsCb = doc.getElementById('cx-cfg-auto-answer-quiz');
if (settingsCb) settingsCb.checked = e.target.checked;
const settingsSelect = doc.getElementById('cx-cfg-quiz-mode');
if (settingsSelect) settingsSelect.disabled = !e.target.checked;
Logger.log(`自动答章节测验: ${e.target.checked ? '开启' : '关闭'}`, 'info');
});
// 视频内联设置 — 章节测验模式
doc.getElementById('cx-video-quiz-mode-inline')?.addEventListener('change', (e) => {
const cfg = ConfigStore.getVideoConfig();
cfg.quizMode = e.target.value;
ConfigStore.setVideoConfig(cfg);
const settingsSelect = doc.getElementById('cx-cfg-quiz-mode');
if (settingsSelect) settingsSelect.value = e.target.value;
const modeNames = { free: '免费题库', paid: '付费题库', ai: 'AI 答题' };
Logger.log(`章节测验模式: ${modeNames[e.target.value] || e.target.value}`, 'info');
});
// 二维码图片加载失败时显示文字占位
const qrImg = doc.getElementById('cx-free-qr-img');
const qrFallback = doc.getElementById('cx-free-qr-fallback');
if (qrImg) {
qrImg.onload = () => { qrImg.style.display = 'block'; if (qrFallback) qrFallback.style.display = 'none'; };
qrImg.onerror = () => { qrImg.style.display = 'none'; if (qrFallback) qrFallback.style.display = 'block'; };
}
}
};
// ==========================================
// FrameMediaBridge - 顶层控制器 / 视频 frame worker 通信
// ==========================================
const FrameMediaBridge = {
CHANNEL: 'cx-learning-helper-media-v1',
_session: '',
_workerId: '',
_workerSession: '',
_workerChapterEpoch: 0,
_workerPlayToken: '',
_controllerOrigin: '*',
_workers: new Map(),
_activeWorkerId: '',
_controllerReady: false,
_workerReady: false,
_chapterEpoch: 1,
_playSequence: 0,
_reloadedSources: new WeakSet(),
_lastWorkerReportAt: 0,
_workerReportTimer: null,
_workerObserver: null,
_newId(prefix) {
let random = '';
try {
const bytes = new Uint32Array(2);
crypto.getRandomValues(bytes);
random = Array.from(bytes, value => value.toString(36)).join('');
} catch (_) {
random = Math.random().toString(36).slice(2);
}
return `${prefix}-${Date.now().toString(36)}-${random}`;
},
_isTrustedOrigin(origin) {
try {
const host = new URL(origin).hostname.toLowerCase();
return /(^|\.)(?:chaoxing|xuexitong)\.com$/.test(host);
} catch (_) {
return false;
}
},
_applyWorkerSnapshot(worker, snapshot) {
if (!worker || !snapshot || typeof snapshot !== 'object') return;
if ('hasVideo' in snapshot) worker.hasVideo = !!snapshot.hasVideo;
if ('hasMore' in snapshot) worker.hasMore = !!snapshot.hasMore;
if ('progress' in snapshot) {
const progress = Number(snapshot.progress);
if (Number.isFinite(progress)) worker.progress = Math.max(0, Math.min(100, progress));
}
const allowedStates = ['missing', 'pending', 'ready', 'playing', 'finished', 'unsupported', 'unavailable', 'reloading', 'awaiting'];
if (allowedStates.includes(snapshot.state)) worker.state = snapshot.state;
},
_findSourceFrameOrder(source) {
let order = 0;
let found = -1;
const seen = new Set();
const visit = (doc, depth) => {
if (!doc || seen.has(doc) || depth > 4 || found >= 0) return;
seen.add(doc);
let frames = [];
try { frames = Array.from(doc.querySelectorAll('iframe,frame')); } catch (_) { return; }
for (const frame of frames) {
const currentOrder = order++;
let frameWindow = null;
try { frameWindow = frame.contentWindow; } catch (_) {}
if (frameWindow === source) {
found = currentOrder;
return;
}
try {
const childDoc = frame.contentDocument || frameWindow?.document;
if (childDoc) visit(childDoc, depth + 1);
} catch (_) {}
if (found >= 0) return;
}
};
visit(document, 0);
return found;
},
initController() {
if (this._controllerReady || _isMediaWorkerFrame) return;
this._controllerReady = true;
this._session = this._newId('controller');
window.addEventListener('message', event => this._handleControllerMessage(event));
},
_handleControllerMessage(event) {
const data = event?.data;
if (!data || data.channel !== this.CHANNEL || data.direction !== 'worker') return;
if (!this._isTrustedOrigin(event.origin) || !event.source) return;
if (data.type === 'HELLO') {
const workerId = String(data.workerId || '');
if (!workerId) return;
// iframe reload 后 WindowProxy 保持不变,用新 worker id 替换旧记录。
for (const [oldId, oldWorker] of this._workers) {
if (oldId !== workerId && oldWorker.source === event.source) {
this._workers.delete(oldId);
if (this._activeWorkerId === oldId) this._activeWorkerId = workerId;
}
}
const worker = this._workers.get(workerId) || {
id: workerId,
source: event.source,
origin: event.origin,
state: 'pending',
hasVideo: false,
videoHint: !!data.videoHint,
progress: 0,
lastSeen: 0,
playToken: '',
playAcknowledged: false
};
worker.source = event.source;
worker.origin = event.origin;
worker.videoHint = !!data.videoHint;
worker.lastSeen = Date.now();
this._applyWorkerSnapshot(worker, data.snapshot);
this._workers.set(workerId, worker);
this._send(worker, 'INIT', {
playbackRate: ConfigStore.getVideoConfig().playbackRate || 2,
chapterEpoch: this._chapterEpoch
});
if (VideoModule._playing && !VideoModule._videoEl) {
setTimeout(() => VideoModule._tryPlayVideo(), 0);
}
return;
}
const worker = this._workers.get(String(data.workerId || ''));
if (!worker || worker.source !== event.source || worker.origin !== event.origin || data.session !== this._session) return;
const messageEpoch = Number(data.chapterEpoch || 0);
if (messageEpoch !== this._chapterEpoch) return;
if (data.type === 'LOG') {
if (worker.playToken && data.playToken !== worker.playToken) return;
worker.lastSeen = Date.now();
const entry = data.entry || {};
if (entry.message) Logger.log(`[视频帧] ${entry.message}`, entry.level || 'info');
return;
}
if (data.type === 'STATE') {
// RELOAD 后旧 document 可能短暂上报,必须等待新 worker 的 HELLO。
if (worker.state === 'reloading') return;
if (worker.playToken && data.playToken !== worker.playToken) return;
worker.lastSeen = Date.now();
const wasUsable = this._isWorkerUsable(worker);
this._applyWorkerSnapshot(worker, data.snapshot);
if (worker.playToken && data.playToken === worker.playToken && worker.state === 'playing') {
worker.playAcknowledged = true;
}
delete worker.awaitingSince;
if (!wasUsable && this._isWorkerUsable(worker) && VideoModule._playing && !VideoModule._videoEl) {
setTimeout(() => VideoModule._tryPlayVideo(), 0);
}
return;
}
if (data.type !== 'EVENT') return;
if (worker.id !== this._activeWorkerId || !worker.playToken || data.playToken !== worker.playToken) return;
// 同一坏源事件可能由尚未取消的旧重试链重复上报;首次 RELOAD 已足够。
if (data.event === 'SOURCE_EXHAUSTED' && worker.state === 'reloading') return;
worker.lastSeen = Date.now();
this._applyWorkerSnapshot(worker, data.snapshot);
if (data.event === 'ENDED') {
const hasMore = !!worker.hasMore;
worker.state = hasMore && ['ready', 'pending', 'unsupported'].includes(worker.state) ? worker.state : (hasMore ? 'ready' : 'finished');
worker.hasVideo = hasMore;
worker.playToken = '';
worker.playAcknowledged = false;
this._activeWorkerId = '';
VideoModule._handleRemoteVideoEnded();
} else if (data.event === 'SOURCE_EXHAUSTED') {
// 一个跨域 frame 可以包含多个视频;坏源只跳过当前视频,继续处理剩余视频。
if (worker.hasMore) {
worker.state = ['ready', 'pending', 'unsupported'].includes(worker.state) ? worker.state : 'ready';
worker.hasVideo = true;
worker.playToken = '';
worker.playAcknowledged = false;
this._activeWorkerId = '';
VideoModule._handleRemoteVideoUnavailable(data.detail || '当前视频源不可用');
return;
}
if (!this._reloadedSources.has(worker.source)) {
this._reloadedSources.add(worker.source);
worker.state = 'reloading';
Logger.log('跨域视频源持续不可用,已重载一次视频播放器', 'info');
if (this._send(worker, 'COMMAND', {
command: 'RELOAD',
chapterEpoch: this._chapterEpoch,
playToken: worker.playToken
})) {
const workerId = worker.id;
const source = worker.source;
const epoch = this._chapterEpoch;
setTimeout(() => {
const current = this._workers.get(workerId);
if (!current || current.source !== source || current.state !== 'reloading' || this._chapterEpoch !== epoch) return;
current.state = 'unavailable';
current.playToken = '';
current.playAcknowledged = false;
if (this._activeWorkerId === workerId) this._activeWorkerId = '';
VideoModule._handleRemoteVideoUnavailable('视频播放器重载后未响应');
}, 12000);
} else {
worker.state = 'unavailable';
worker.playToken = '';
worker.playAcknowledged = false;
this._activeWorkerId = '';
VideoModule._handleRemoteVideoUnavailable('无法重载视频播放器');
}
} else {
worker.state = 'unavailable';
worker.playToken = '';
worker.playAcknowledged = false;
this._activeWorkerId = '';
VideoModule._handleRemoteVideoUnavailable(data.detail || '');
}
}
},
_send(worker, type, payload = {}) {
try {
worker.source.postMessage({
channel: this.CHANNEL,
direction: 'controller',
type,
workerId: worker.id,
session: this._session,
payload
}, worker.origin);
return true;
} catch (_) {
return false;
}
},
_watchActiveWorker(workerId, playToken) {
const maxSilence = 90000;
const check = () => {
const worker = this._workers.get(workerId);
if (!worker || this._activeWorkerId !== workerId || worker.playToken !== playToken || worker.chapterEpoch !== this._chapterEpoch) return;
const silence = Date.now() - Number(worker.lastSeen || 0);
if (silence >= maxSilence) {
worker.state = 'unavailable';
worker.playToken = '';
worker.playAcknowledged = false;
this._activeWorkerId = '';
VideoModule._handleRemoteVideoUnavailable('视频工作帧连接超时');
return;
}
setTimeout(check, Math.max(10000, maxSilence - silence));
};
setTimeout(check, 30000);
},
_isWorkerUsable(worker) {
if (!worker || !worker.source) return false;
if (worker.state === 'finished' || worker.state === 'unavailable' || worker.state === 'reloading' || worker.state === 'awaiting') return false;
return worker.hasVideo || worker.videoHint || worker.state === 'ready' || worker.state === 'pending' || worker.state === 'unsupported';
},
hasVideoWorker() {
return Array.from(this._workers.values()).some(worker => this._isWorkerUsable(worker));
},
playNextWorker() {
let worker = this._workers.get(this._activeWorkerId);
// token 存在即表示该 PLAY 尚未终结,pending/ready 状态也不能重复下发。
if (this._isWorkerUsable(worker) && worker.playToken && worker.chapterEpoch === this._chapterEpoch) return true;
const now = Date.now();
for (const [workerId, candidate] of this._workers) {
if (candidate.state === 'awaiting' && now - Number(candidate.awaitingSince || now) > 5000) {
this._workers.delete(workerId);
}
}
const candidates = Array.from(this._workers.values())
.filter(candidate => this._isWorkerUsable(candidate))
.sort((left, right) => {
const leftOrder = this._findSourceFrameOrder(left.source);
const rightOrder = this._findSourceFrameOrder(right.source);
if (leftOrder >= 0 && rightOrder >= 0) return leftOrder - rightOrder;
if (leftOrder >= 0) return -1;
if (rightOrder >= 0) return 1;
return Number(right.lastSeen || 0) - Number(left.lastSeen || 0);
});
const cfg = ConfigStore.getVideoConfig();
for (worker of candidates) {
this._activeWorkerId = worker.id;
worker.state = 'starting';
worker.chapterEpoch = this._chapterEpoch;
worker.playToken = `${this._chapterEpoch}-${++this._playSequence}-${this._newId('play')}`;
worker.playAcknowledged = false;
const sent = this._send(worker, 'COMMAND', {
command: 'PLAY',
chapterEpoch: this._chapterEpoch,
playToken: worker.playToken,
playbackRate: cfg.playbackRate || 2,
autoSkipQuiz: cfg.autoSkipQuiz !== false,
autoAnswerQuiz: cfg.autoAnswerQuiz !== false,
quizMode: cfg.quizMode || 'free'
});
if (!sent) {
worker.state = 'unavailable';
worker.playToken = '';
worker.playAcknowledged = false;
this._activeWorkerId = '';
continue;
}
const workerId = worker.id;
const playToken = worker.playToken;
const epoch = this._chapterEpoch;
worker.lastSeen = Date.now();
this._watchActiveWorker(workerId, playToken);
setTimeout(() => {
const current = this._workers.get(workerId);
if (!current || this._chapterEpoch !== epoch || this._activeWorkerId !== workerId || current.playToken !== playToken) return;
if (current.playAcknowledged || current.state === 'playing') return;
this._send(current, 'COMMAND', {
command: 'STOP',
chapterEpoch: epoch,
playToken
});
current.state = 'unavailable';
current.playToken = '';
current.playAcknowledged = false;
this._activeWorkerId = '';
VideoModule._handleRemoteVideoUnavailable('视频工作帧未响应');
}, 30000);
return true;
}
return false;
},
stopWorkers() {
for (const worker of this._workers.values()) {
this._send(worker, 'COMMAND', {
command: 'STOP',
chapterEpoch: this._chapterEpoch,
playToken: worker.playToken || ''
});
worker.playToken = '';
worker.playAcknowledged = false;
if (['starting', 'playing', 'pending', 'ready'].includes(worker.state)) worker.state = 'ready';
}
this._activeWorkerId = '';
},
setPlaybackRate(rate) {
for (const worker of this._workers.values()) {
this._send(worker, 'COMMAND', {
command: 'SET_RATE',
chapterEpoch: this._chapterEpoch,
playbackRate: rate
});
}
},
getActiveProgress() {
const worker = this._workers.get(this._activeWorkerId);
return worker && Number.isFinite(Number(worker.progress)) ? Number(worker.progress) : null;
},
resetChapter() {
this._chapterEpoch++;
this._playSequence = 0;
this._activeWorkerId = '';
this._reloadedSources = new WeakSet();
for (const worker of this._workers.values()) {
worker.state = 'awaiting';
worker.awaitingSince = Date.now();
worker.hasVideo = false;
worker.progress = 0;
worker.playToken = '';
worker.playAcknowledged = false;
worker.chapterEpoch = this._chapterEpoch;
this._send(worker, 'COMMAND', { command: 'RESET', chapterEpoch: this._chapterEpoch });
const workerId = worker.id;
const chapterEpoch = this._chapterEpoch;
setTimeout(() => {
const current = this._workers.get(workerId);
if (current === worker && current.state === 'awaiting' && current.chapterEpoch === chapterEpoch) {
this._workers.delete(workerId);
}
}, 6000);
}
},
initWorker() {
if (this._workerReady || !_isMediaWorkerFrame) return;
this._workerReady = true;
this._workerId = this._newId('worker');
window.addEventListener('message', event => this._handleWorkerMessage(event));
Logger._onLog = entry => {
if (this._workerSession) this._workerPost('LOG', { entry });
};
const scheduleReport = () => this._scheduleWorkerReport();
try {
if (typeof MutationObserver === 'function' && document.documentElement) {
this._workerObserver = new MutationObserver(scheduleReport);
this._workerObserver.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['src']
});
}
document.addEventListener('loadedmetadata', scheduleReport, true);
document.addEventListener('canplay', scheduleReport, true);
} catch (_) {}
this._announceWorker(0);
},
_scheduleWorkerReport(delay = 120) {
if (!this._workerSession) return;
if (this._workerReportTimer) clearTimeout(this._workerReportTimer);
this._workerReportTimer = setTimeout(() => {
this._workerReportTimer = null;
this.reportWorkerState(true);
}, delay);
},
_announceWorker(attempt) {
if (this._workerSession || attempt >= 5) return;
this._workerPost('HELLO', {
videoHint: _hasVideoUrlHint,
snapshot: this._workerSnapshot()
}, true);
setTimeout(() => this._announceWorker(attempt + 1), 750 * (attempt + 1));
},
_handleWorkerMessage(event) {
const data = event?.data;
if (!data || data.channel !== this.CHANNEL || data.direction !== 'controller') return;
if (event.source !== window.top || !this._isTrustedOrigin(event.origin)) return;
if (data.workerId !== this._workerId) return;
if (data.type === 'INIT') {
this._workerSession = String(data.session || '');
this._workerChapterEpoch = Number(data.payload?.chapterEpoch || 0);
this._workerPlayToken = '';
this._controllerOrigin = event.origin;
const rate = Number(data.payload?.playbackRate || 2);
const video = VideoModule._findVideoElement();
if (video) video.playbackRate = rate;
this.reportWorkerState(true);
return;
}
if (!this._workerSession || data.session !== this._workerSession || event.origin !== this._controllerOrigin) return;
if (data.type !== 'COMMAND') return;
const command = data.payload?.command;
const commandEpoch = Number(data.payload?.chapterEpoch || 0);
if (command === 'RESET') {
// RESET 是唯一允许推进 epoch 的命令;延迟到达的旧 RESET 不能回退 worker。
if (!commandEpoch || commandEpoch < this._workerChapterEpoch) return;
this._workerChapterEpoch = commandEpoch;
this._workerPlayToken = '';
VideoModule.stop();
VideoModule._videoEl = null;
VideoModule._resetVideoSourceWait(true);
this._scheduleWorkerReport(800);
setTimeout(() => this.reportWorkerState(true), 2500);
setTimeout(() => this.reportWorkerState(true), 5000);
return;
}
if (!commandEpoch || commandEpoch !== this._workerChapterEpoch) return;
if (command === 'PLAY') {
const playToken = String(data.payload?.playToken || '');
if (!playToken) return;
this._workerPlayToken = playToken;
const cfg = ConfigStore.getVideoConfig();
cfg.playbackRate = Number(data.payload?.playbackRate || cfg.playbackRate || 2);
cfg.autoSkipQuiz = data.payload?.autoSkipQuiz !== false;
cfg.autoAnswerQuiz = data.payload?.autoAnswerQuiz !== false;
cfg.quizMode = data.payload?.quizMode || cfg.quizMode || 'free';
ConfigStore.setVideoConfig(cfg);
if (!VideoModule._playing) VideoModule.start();
else VideoModule._tryPlayVideo();
this.reportWorkerState(true);
} else if (command === 'STOP') {
const stopToken = String(data.payload?.playToken || '');
if (stopToken && this._workerPlayToken && stopToken !== this._workerPlayToken) return;
this._workerPlayToken = '';
VideoModule.stop();
this.reportWorkerState(true);
} else if (command === 'SET_RATE') {
const rate = Number(data.payload?.playbackRate || 2);
const video = VideoModule._videoEl || VideoModule._findVideoElement();
if (video) video.playbackRate = rate;
} else if (command === 'RELOAD') {
if (!this._workerPlayToken || data.payload?.playToken !== this._workerPlayToken) return;
try { window.location.reload(); } catch (_) {}
}
},
_workerPost(type, payload = {}, hello = false, context = null) {
try {
window.top.postMessage({
channel: this.CHANNEL,
direction: 'worker',
type,
workerId: this._workerId,
session: hello ? '' : this._workerSession,
chapterEpoch: context?.chapterEpoch ?? this._workerChapterEpoch,
playToken: context?.playToken ?? this._workerPlayToken,
...payload
}, hello ? '*' : this._controllerOrigin);
} catch (_) {}
},
_workerSnapshot() {
const all = VideoModule._findAllVideoElements();
const remaining = all.filter(video => video.dataset?.cxFinished !== '1' && video.dataset?.cxSourceUnavailable !== '1' && !video.ended);
const video = VideoModule._videoEl || VideoModule._findVideoElement();
const mediaState = video ? VideoModule._getVideoMediaState(video) : null;
const progress = video && Number(video.duration) > 0
? Math.max(0, Math.min(100, Math.round((Number(video.currentTime) / Number(video.duration)) * 100)))
: 0;
return {
hasVideo: remaining.length > 0,
hasMore: remaining.length > 0,
state: video && !video.paused && !video.ended
? 'playing'
: (mediaState?.state || (all.length ? 'finished' : (_hasVideoUrlHint ? 'pending' : 'missing'))),
progress
};
},
reportWorkerState(force = false) {
if (!_isMediaWorkerFrame || !this._workerSession) return;
const now = Date.now();
if (!force && now - this._lastWorkerReportAt < 900) return;
this._lastWorkerReportAt = now;
this._workerPost('STATE', { snapshot: this._workerSnapshot() });
},
notifyWorkerEnded() {
if (!_isMediaWorkerFrame) return;
const context = {
chapterEpoch: this._workerChapterEpoch,
playToken: this._workerPlayToken
};
setTimeout(() => this._workerPost('EVENT', { event: 'ENDED', snapshot: this._workerSnapshot() }, false, context), 0);
},
notifyWorkerSourceExhausted(detail = '') {
if (!_isMediaWorkerFrame) return;
this._workerPost('EVENT', {
event: 'SOURCE_EXHAUSTED',
detail: String(detail || ''),
snapshot: this._workerSnapshot()
});
}
};
// ==========================================
// VideoModule - 视频自动播放模块
// ==========================================
const VideoModule = {
_playing: false,
_currentChapter: '',
_progress: 0,
_videoEl: null,
_antiPauseHandlers: [],
_pauseCheckInterval: null,
_quizCheckInterval: null,
_progressInterval: null,
_loadRetryCount: 0,
_maxLoadRetries: 3,
_userPaused: false,
_quizAnswering: false,
_playGeneration: 0,
_lastQuizCloseTime: 0,
_lastPauseTime: 0,
_tryingPlay: false,
_pendingPlayTimeout: null,
_advanceInFlight: false,
_lastNextControl: null,
_lastNextSnapshot: '',
_snapshotNodeIds: new WeakMap(),
_nextSnapshotNodeId: 1,
_documentStateKey: '',
_documentNoProgressCount: 0,
_sourceWaitVideo: null,
_sourceWaitCount: 0,
_maxSourceWaits: 8,
_sourceFrameReloaded: false,
_sourceReloadedTargets: new WeakSet(),
_scheduledTimeouts: new Set(),
_quizModeState: null,
_isCurrent(generation) {
return this._playing && generation === this._playGeneration;
},
// 仅用于操作回调;Promise 的延迟仍正常结算,不能因取消丢失 resolve。
_schedule(callback, delay, generation = this._playGeneration) {
const timer = setTimeout(() => {
this._scheduledTimeouts.delete(timer);
if (this._isCurrent(generation)) callback();
}, delay);
this._scheduledTimeouts.add(timer);
return timer;
},
_restoreQuizMode(state) {
if (!state || this._quizModeState !== state) return;
if (!AnswerModule._answering && AnswerModule._mode === state.mode) AnswerModule._mode = state.previous;
this._quizModeState = null;
},
// 6.1 - start(): 开始自动播放
start() {
if (this._playing) return;
this._playGeneration++;
this._playing = true;
const generation = this._playGeneration;
if (!AnswerModule._answering) AnswerModule._stopRequested = false;
const cfg = ConfigStore.getVideoConfig();
Logger.log('视频自动播放已启动', 'success');
UIPanel.setRunning(true);
UIPanel.setStatus('运行中', 'success');
this._loadRetryCount = 0;
this._userPaused = false;
this._advanceInFlight = false;
this._lastNextControl = null;
this._lastNextSnapshot = '';
this._documentStateKey = '';
this._documentNoProgressCount = 0;
this._resetVideoSourceWait(true);
this.installAntiPause();
this.playCurrentVideo();
// 启动视频中途弹题/测验弹窗检测
if (cfg.autoSkipQuiz || cfg.autoAnswerQuiz !== false) {
this._quizCheckInterval = setInterval(() => { if (this._isCurrent(generation)) this.detectAndCloseQuiz(); }, 2000);
}
// 启动进度更新
this._progressInterval = setInterval(() => { if (this._isCurrent(generation)) this._updateProgress(); }, 1000);
this._updateVideoUI();
},
// 6.1 - stop(): 停止自动播放
stop() {
this._playGeneration++;
CXRequests.cancelGroup('video');
for (const timer of this._scheduledTimeouts) clearTimeout(timer);
this._scheduledTimeouts.clear();
this._restoreQuizMode(this._quizModeState);
this._quizAnswering = false;
const activeVideo = this._videoEl;
if (!this._playing) {
try {
if (activeVideo && !activeVideo.paused && !activeVideo.ended) activeVideo.pause();
} catch (_) {}
return;
}
this._playing = false;
if (!_isMediaWorkerFrame) FrameMediaBridge.stopWorkers();
this.removeAntiPause();
try {
if (activeVideo && !activeVideo.paused && !activeVideo.ended) activeVideo.pause();
} catch (_) {}
if (this._quizCheckInterval) {
clearInterval(this._quizCheckInterval);
this._quizCheckInterval = null;
}
if (this._progressInterval) {
clearInterval(this._progressInterval);
this._progressInterval = null;
}
if (this._pauseCheckInterval) {
clearInterval(this._pauseCheckInterval);
this._pauseCheckInterval = null;
}
if (this._pendingPlayTimeout) {
clearTimeout(this._pendingPlayTimeout);
this._pendingPlayTimeout = null;
}
this._tryingPlay = false;
this._advanceInFlight = false;
this._videoEl = null;
this._documentStateKey = '';
this._documentNoProgressCount = 0;
this._resetVideoSourceWait(true);
Logger.log('视频自动播放已停止', 'info');
UIPanel.setRunning(false);
UIPanel.setStatus('已停止', 'info');
this._updateVideoUI();
},
// 6.1 - playCurrentVideo(): 检测页面视频元素并播放
async playCurrentVideo() {
if (!this._playing) return;
this._loadRetryCount = 0;
await this._tryPlayVideo();
},
// 内部:尝试查找并播放视频,15秒超时重试
async _tryPlayVideo() {
if (!this._playing) return;
const generation = this._playGeneration;
if (this._tryingPlay) {
Logger.log('_tryPlayVideo 已在执行中,跳过重复调用', 'info');
return;
}
this._tryingPlay = true;
try {
await this._tryPlayVideoInner(generation);
} finally {
if (generation === this._playGeneration) this._tryingPlay = false;
}
},
async _tryPlayVideoInner(generation = this._playGeneration) {
if (!this._isCurrent(generation)) return;
const video = this._findVideoElement();
if (video) {
const mediaState = this._getVideoMediaState(video);
if (mediaState.state !== 'ready') {
this._queueVideoSourceRetry(video, mediaState);
return;
}
this._videoEl = video;
this._bindVideoEvents(video);
this._installVideoPauseHook(video);
if (this._isVideoQuizBlocking()) {
this._lastPauseTime = Date.now();
return;
}
const cfg = ConfigStore.getVideoConfig();
video.playbackRate = cfg.playbackRate || 2;
video.muted = false;
let played = false;
try {
await video.play();
if (!this._isCurrent(generation)) return;
played = true;
} catch (error) {
if (!this._isCurrent(generation)) return;
// 只有浏览器的自动播放限制适合通过静音重试;空源/坏源静音没有意义。
if (this._isAutoplayBlockedError(error)) {
video.muted = true;
try {
await video.play();
if (!this._isCurrent(generation)) return;
played = true;
Logger.log('视频已静音播放(浏览器限制)', 'info');
} catch (retryError) {
if (!this._isCurrent(generation)) return;
this._queueVideoSourceRetry(video, this._getVideoMediaState(video), retryError);
return;
}
} else {
this._queueVideoSourceRetry(video, this._getVideoMediaState(video), error);
return;
}
}
if (!played || !this._isCurrent(generation)) return;
this._resetVideoSourceWait();
this._loadRetryCount = 0;
Logger.log(`视频开始播放,倍速 ${video.playbackRate}x`, 'success');
this._updateChapterName();
this._updateVideoUI();
return;
}
// 视频未找到,检查是否为章节测验页面(等待iframe加载)
await new Promise(r => setTimeout(r, 3000));
if (!this._isCurrent(generation)) return;
// 跨域视频由其 iframe 内的轻量 worker 播放,结束后再由顶层统一推进章节。
if (!_isMediaWorkerFrame && FrameMediaBridge.playNextWorker()) {
Logger.log('已连接跨域视频播放器,等待媒体源就绪', 'info');
UIPanel.setStatus('正在连接视频播放器', 'info');
return;
}
if (_isMediaWorkerFrame) {
if (this._loadRetryCount < this._maxLoadRetries) {
Logger.log(`视频工作帧尚未创建播放器,5秒后重试 (${this._loadRetryCount + 1}/${this._maxLoadRetries})`, 'info');
await new Promise(resolve => setTimeout(resolve, 5000));
if (!this._isCurrent(generation)) return;
this._loadRetryCount++;
await this._tryPlayVideoInner(generation);
} else {
const detail = '视频工作帧内未检测到视频元素';
Logger.log(detail, 'error');
FrameMediaBridge.notifyWorkerSourceExhausted(detail);
this.stop();
}
return;
}
const quizDoc = this._findChapterQuizDoc();
if (quizDoc) {
const videoCfg = ConfigStore.getVideoConfig();
const autoAnswer = videoCfg.autoAnswerQuiz !== false;
const quizMode = videoCfg.quizMode || 'free';
if (autoAnswer) {
const modeNames = { free: '免费题库', paid: '付费题库', ai: 'AI 答题' };
Logger.log(`检测到章节测验,模式: ${modeNames[quizMode] || quizMode}`, 'info');
} else {
Logger.log('检测到章节测验,未开启自动答题,跳过', 'info');
}
await this._autoAnswerChapterQuiz(quizDoc, generation);
return;
}
// 学习目标、PPT、PDF、课件等页面本来就没有 video,直接走内容推进。
// 只有存在明确的非视频内容证据时才提前推进,避免误跳仍在加载的视频。
if (await this._handleNonVideoContent(false, generation)) return;
if (!this._isCurrent(generation)) return;
// 视频未找到,等待加载
if (this._loadRetryCount < this._maxLoadRetries) {
Logger.log(`未检测到视频元素,15秒后重试 (${this._loadRetryCount + 1}/${this._maxLoadRetries})`, 'info');
await new Promise(resolve => setTimeout(resolve, 15000));
if (!this._isCurrent(generation)) return;
this._loadRetryCount++;
// 刷新当前章节iframe
this._refreshCurrentFrame();
await new Promise(resolve => setTimeout(resolve, 3000));
if (!this._isCurrent(generation)) return;
await this._tryPlayVideoInner(generation);
} else {
// 重试耗尽后再检查一次明确的非视频内容;未知空白页不能盲目跳过。
if (await this._handleNonVideoContent(true, generation)) return;
if (!this._isCurrent(generation)) return;
Logger.log('视频加载失败,且未识别到学习目标或文档内容', 'error');
this.stop();
UIPanel.setStatus('视频加载失败', 'error');
}
},
// 内部:查找下一个**未播完**的视频元素(包括iframe内部,最多4层)
// 一个课时页面可能放多个视频任务点(截图:3. xxx / 4. xxx),需要逐个播
_findVideoElement() {
const all = this._findAllVideoElements();
let pending = null;
let unsupported = null;
for (const v of all) {
if (v.isConnected === false || v.hidden || v.getAttribute?.('aria-hidden') === 'true') continue;
try {
const style = (v.ownerDocument?.defaultView || window).getComputedStyle(v);
if (style.display === 'none' || style.visibility === 'hidden') continue;
if (v.closest?.('[hidden], .hide, .hidden, [aria-hidden="true"]')) continue;
} catch (_) {}
const source = this._getVideoSourceKey(v);
if (v.dataset.cxSourceUnavailable === '1') {
const unavailableSource = v.dataset.cxSourceUnavailableSrc || '';
// SPA 复用 video 节点时,新媒体源仍应重新尝试。
if (source && source !== unavailableSource) {
delete v.dataset.cxSourceUnavailable;
delete v.dataset.cxSourceUnavailableSrc;
} else {
continue;
}
}
if (v.dataset.cxFinished === '1') {
const finishedSource = v.dataset.cxFinishedSrc || '';
// SPA 可能复用同一个 video 节点;仅当媒体来源确实变化时清除完成态。
if (finishedSource && source && finishedSource !== source) {
delete v.dataset.cxFinished;
delete v.dataset.cxFinishedSrc;
} else {
continue;
}
}
if (v.ended) {
v.dataset.cxFinished = '1';
if (source) v.dataset.cxFinishedSrc = source;
continue;
}
const mediaState = this._getVideoMediaState(v);
if (mediaState.state === 'ready') return v;
if (mediaState.state === 'pending' && !pending) pending = v;
if (mediaState.state === 'unsupported' && !unsupported) unsupported = v;
}
return pending || unsupported;
},
_getVideoSourceKey(video) {
if (!video) return '';
try {
return String(
video.currentSrc ||
video.src ||
video.getAttribute?.('src') ||
video.querySelector?.('source[src]')?.src ||
''
).trim();
} catch (_) {
return '';
}
},
_getVideoMediaState(video) {
if (!video) return { state: 'pending', source: '', errorCode: 0, networkState: 0, readyState: 0 };
const source = this._getVideoSourceKey(video);
let hasSrcObject = false;
try { hasSrcObject = !!video.srcObject; } catch (_) {}
const errorCode = Number(video.error?.code || 0);
const networkState = Number(video.networkState ?? 0);
// HTMLMediaElement 始终提供 readyState;测试替身没有该字段时按已有来源处理。
const readyState = typeof video.readyState === 'number'
? Number(video.readyState)
: ((!!source || hasSrcObject) ? 4 : 0);
const unsupported = errorCode === 4 || (networkState === 3 && !!source && !hasSrcObject);
const hasSource = !!source || hasSrcObject;
const state = unsupported ? 'unsupported' : (hasSource && readyState >= 1 ? 'ready' : 'pending');
return { state, source, hasSrcObject, errorCode, networkState, readyState };
},
_isVideoSourceReady(video) {
return this._getVideoMediaState(video).state === 'ready';
},
_isAutoplayBlockedError(error) {
return String(error?.name || '') === 'NotAllowedError';
},
_isSourcePlayError(error) {
const name = String(error?.name || '');
const message = String(error?.message || error || '');
return name === 'NotSupportedError' || name === 'AbortError' ||
/no supported sources|source.*not supported|MEDIA_ERR_SRC_NOT_SUPPORTED/i.test(message);
},
_getVideoReloadTarget(video) {
if (!video) return null;
try {
return video.ownerDocument?.defaultView?.frameElement || video;
} catch (_) {
return video;
}
},
_resetVideoSourceWait(resetReloadHistory = false) {
this._sourceWaitVideo = null;
this._sourceWaitCount = 0;
this._sourceFrameReloaded = false;
if (resetReloadHistory) this._sourceReloadedTargets = new WeakSet();
},
_queueVideoSourceRetry(video, mediaState = null, playError = null) {
if (!this._playing) return;
if (this._sourceWaitVideo !== video) {
this._sourceWaitVideo = video;
this._sourceWaitCount = 0;
const reloadTarget = this._getVideoReloadTarget(video);
this._sourceFrameReloaded = !!(reloadTarget && this._sourceReloadedTargets.has(reloadTarget));
}
this._sourceWaitCount++;
this._videoEl = null;
const state = mediaState || this._getVideoMediaState(video);
if (state.state === 'pending' && state.source && state.readyState < 1 && video?.dataset) {
if (video.dataset.cxLoadRequestedSrc !== state.source) {
video.dataset.cxLoadRequestedSrc = state.source;
try { video.load?.(); } catch (_) {}
}
}
const sourceFailure = state.state === 'unsupported' || this._isSourcePlayError(playError);
const waitLabel = sourceFailure ? '视频源暂不可用' : '等待视频源加载';
if (this._sourceWaitCount <= this._maxSourceWaits) {
if (this._sourceWaitCount === 1 || this._sourceWaitCount === this._maxSourceWaits) {
Logger.log(`${waitLabel},稍后重试 (${this._sourceWaitCount}/${this._maxSourceWaits})`, 'info');
}
UIPanel.setStatus(waitLabel, 'info');
if (this._pendingPlayTimeout) clearTimeout(this._pendingPlayTimeout);
this._pendingPlayTimeout = this._schedule(() => {
this._pendingPlayTimeout = null;
if (this._playing) this._tryPlayVideo();
}, 2000);
return;
}
if (!this._sourceFrameReloaded) {
this._sourceFrameReloaded = true;
if (this._refreshCurrentFrame(true)) {
const reloadTarget = this._getVideoReloadTarget(video);
if (reloadTarget) this._sourceReloadedTargets.add(reloadTarget);
this._sourceWaitCount = 0;
Logger.log('视频源持续不可用,已重载一次视频播放器', 'info');
UIPanel.setStatus('正在重载视频播放器', 'info');
if (this._pendingPlayTimeout) clearTimeout(this._pendingPlayTimeout);
this._pendingPlayTimeout = this._schedule(() => {
this._pendingPlayTimeout = null;
if (this._playing) this._tryPlayVideo();
}, 3000);
return;
}
}
const detail = String(playError?.message || '').trim();
Logger.log(`视频源不可用${detail ? `: ${detail}` : ''}`, 'error');
if (video?.dataset) {
video.dataset.cxSourceUnavailable = '1';
const source = this._getVideoSourceKey(video);
if (source) video.dataset.cxSourceUnavailableSrc = source;
}
this._sourceWaitVideo = null;
this._sourceWaitCount = 0;
const nextVideo = this._findVideoElement();
if (nextVideo && nextVideo !== video) {
Logger.log('已跳过不可用的视频源,继续下一个视频任务点', 'info');
UIPanel.setStatus('继续下一个视频', 'info');
this._pendingPlayTimeout = this._schedule(() => {
this._pendingPlayTimeout = null;
if (this._playing) this._tryPlayVideo();
}, 1000);
return;
}
if (_isMediaWorkerFrame) {
FrameMediaBridge.notifyWorkerSourceExhausted(detail);
return;
}
if (FrameMediaBridge.playNextWorker()) {
Logger.log('已跳过不可用的视频源,继续跨域视频任务点', 'info');
UIPanel.setStatus('继续下一个视频', 'info');
return;
}
const cfg = ConfigStore.getVideoConfig();
if (cfg.autoAdvance !== false) {
Logger.log('当前视频源不可用,继续检查测验或下一章节', 'info');
UIPanel.setStatus('跳过不可用视频', 'info');
this._pendingPlayTimeout = this._schedule(() => {
this._pendingPlayTimeout = null;
if (!this._playing) return;
if (cfg.autoAnswerQuiz !== false) this._checkAndHandleChapterQuiz();
else this.advanceToNextChapter();
}, 1000);
} else {
UIPanel.setStatus('视频源不可用', 'error');
}
},
// 收集当前页面(含所有可访问 iframe)的全部 video 元素
_findAllVideoElements() {
const result = [];
const collect = (doc) => {
try { doc.querySelectorAll('video').forEach(v => result.push(v)); } catch (_) {}
};
collect(document);
const searchIframes = (doc, depth) => {
if (depth > 4) return;
try {
const iframes = doc.querySelectorAll('iframe');
for (const iframe of iframes) {
try {
if (iframe.id === 'cx-helper-iframe' || !this._isUsableNavigationElement(iframe)) continue;
const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
if (!iframeDoc) continue;
collect(iframeDoc);
searchIframes(iframeDoc, depth + 1);
} catch (_) { /* 跨域iframe忽略 */ }
}
} catch (_) {}
};
searchIframes(document, 1);
return result;
},
_isUsableNavigationElement(el) {
if (!el || el.disabled || el.getAttribute?.('aria-disabled') === 'true') return false;
const cls = String(el.className || '');
if (/\b(disabled|is-disabled|forbid|readonly)\b/i.test(cls)) return false;
try {
const win = el.ownerDocument?.defaultView || window;
const style = win.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false;
} catch (_) {}
const rect = el.getBoundingClientRect?.();
return !(rect && rect.width === 0 && rect.height === 0);
},
_controlText(el) {
const raw = el?.innerText || el?.textContent || el?.value ||
el?.getAttribute?.('aria-label') || el?.getAttribute?.('title') || '';
return String(raw).replace(/\s+/g, '').replace(/[›»→>]+$/g, '');
},
// 查找课程级“下一节”,明确排除 PDF/PPT 阅读器内的“下一页”。
_findPageNextButton() {
const docs = CXUtils.listAccessibleDocs(document, 4);
const selectors = [
'button', 'a', '[role="button"]', 'input[type="button"]', 'input[type="submit"]',
'[onclick]', '[data-action*="next" i]', '[class*="next" i]', '[id*="next" i]'
].join(',');
const exactNext = /^(下一节|下一节课|下一小节|下一章|下一课|下一个任务)$/;
const excludedContext = [
'#cx-helper-iframe', '[role="dialog"]', '.modal', '.layui-layer',
'.question', '.quiz', '.exam', '.test', '.ans-attach-ct', '.pagination', '.swiper',
'.pdf-viewer', '.ppt-viewer', '.document-reader'
].join(',');
for (const doc of docs) {
if (!doc || doc === UIPanel._doc) continue;
let candidates = [];
try { candidates = Array.from(doc.querySelectorAll(selectors)); } catch (_) {}
for (const el of candidates) {
if (!this._isUsableNavigationElement(el)) continue;
const text = this._controlText(el);
if (!exactNext.test(text)) continue;
try {
if (el.closest?.(excludedContext)) continue;
} catch (_) {}
return el;
}
}
return null;
},
_detectNonVideoContentType() {
const docs = CXUtils.listAccessibleDocs(document, 4);
const documentSelectors = [
'embed[type*="pdf" i]', 'object[type*="pdf" i]',
'iframe[src*=".pdf" i]', 'iframe[src*=".ppt" i]',
'iframe[src*="/pdf/" i]', 'iframe[src*="/ppt/" i]', 'iframe[src*="office" i]',
'iframe[module*="insertppt" i]', 'iframe[module*="insertpdf" i]',
'iframe[module*="insertdoc" i]', 'iframe[module*="insertbook" i]',
'.ans-doc', '.ans-ppt', '.pdf-viewer', '.ppt-viewer', '.document-reader'
].join(',');
const activeSelectors = [
'[role="tab"][aria-selected="true"]',
'.prev_ul li.active', '.prev_ul li.on', '.prev_tab li.active', '.prev_tab li.on',
'.chapter_tab .active', '.chapter_tab .on', '.ans-cc-tab .active', '.ans-cc-tab .on',
'.tab-item.active', '.tab-item.on', '[class*="tab"] button.active',
'[class*="tab"] a.active', '[class*="tab"] li.active',
'[class*="tab"] .active', '[class*="tab"] .on'
].join(',');
const contentHeadingSelectors = [
'main h1', 'main h2', 'main h3', '.main-content h1', '.main-content h2',
'.content-title', '.chapter-title', '.knowledge-title'
].join(',');
const nonVideoLabel = /(?:学习|教学|课程)(?:目标|要求)|PPT|PDF|课件|文档|图文|阅读|资料|附件|讲义/i;
const goalHeading = /^(?:\d+(?:\.\d+)*[、.\s]*)?(?:学习|教学|课程)(?:目标|要求)$/;
for (const doc of docs) {
if (!doc || doc === UIPanel._doc) continue;
let markers = [];
try { markers = Array.from(doc.querySelectorAll(documentSelectors)); } catch (_) {}
if (markers.some(el => this._isUsableNavigationElement(el))) return 'PPT/PDF/文档';
let activeItems = [];
try { activeItems = Array.from(doc.querySelectorAll(activeSelectors)); } catch (_) {}
for (const item of activeItems) {
if (!this._isUsableNavigationElement(item)) continue;
const text = this._controlText(item);
const match = text.match(nonVideoLabel);
if (match) return match[0].toUpperCase();
}
let headings = [];
try { headings = Array.from(doc.querySelectorAll(contentHeadingSelectors)); } catch (_) {}
for (const heading of headings) {
if (!this._isUsableNavigationElement(heading)) continue;
const text = this._controlText(heading);
if (goalHeading.test(text)) return text.replace(/^\d+(?:\.\d+)*[、.]*/, '') || '学习目标';
}
}
return '';
},
_isDocumentContentType(contentType) {
return /PPT|PDF|文档|课件|讲义/i.test(String(contentType || ''));
},
_collectDocumentContexts() {
const docs = CXUtils.listAccessibleDocs(document, 4);
const contexts = [];
const seen = new Set();
const framePattern = /(?:\/ananas\/modules\/(?:pdf|ppt|doc|book)\/|\.(?:pdf|ppt|pptx|doc|docx)(?:[?#]|$)|(?:^|[\/_.?=&-])(?:pdf|pptx?|docx?|book|office)(?:[\/_.?=&-]|$)|[?&](?:type|module)=(?:pdf|ppt|doc|book))/i;
const markerSelector = [
'.ans-doc', '.ans-ppt', '.pdf-viewer', '.ppt-viewer', '.document-reader',
'.pdfViewer', '.ppt-container', '.document-viewer',
'embed[type*="pdf" i]', 'object[type*="pdf" i]',
'iframe[src*=".pdf" i]', 'iframe[src*=".ppt" i]',
'iframe[src*="/pdf/" i]', 'iframe[src*="/ppt/" i]', 'iframe[src*="office" i]',
'iframe[module*="insertppt" i]', 'iframe[module*="insertpdf" i]',
'iframe[module*="insertdoc" i]', 'iframe[module*="insertbook" i]'
].join(',');
const addContext = (doc, root, frame) => {
const key = root || doc;
if (!doc || seen.has(key)) return;
seen.add(key);
contexts.push({ doc, root: root || doc, frame: frame || null });
};
for (const doc of docs) {
if (!doc || doc === UIPanel._doc) continue;
let frame = null;
let frameSrc = '';
try {
frame = doc.defaultView?.frameElement || null;
frameSrc = String(frame?.src || frame?.getAttribute?.('src') || '');
} catch (_) {}
if (framePattern.test(frameSrc) && (!frame || this._isUsableNavigationElement(frame))) {
addContext(doc, doc.documentElement || doc.body || doc, frame);
}
let markers = [];
try { markers = Array.from(doc.querySelectorAll(markerSelector)); } catch (_) {}
for (const marker of markers) {
if (!this._isUsableNavigationElement(marker)) continue;
let root = marker;
try {
root = marker.closest?.('.ans-attach-ct, .ans-job, .ans-cc, .task-point, .courseware, .attachment') || marker;
} catch (_) {}
addContext(doc, root, frame);
try {
const childDoc = marker.contentDocument || marker.contentWindow?.document;
if (childDoc) addContext(childDoc, childDoc.documentElement || childDoc.body || childDoc, marker);
} catch (_) {}
}
}
return contexts;
},
_hasDocumentCompletionEvidence(contexts) {
const completedSelector = [
'.ans-job-finished', '.ans-job-icon.finished', '.ans-job-icon.job-finished',
'.ans-job-icon[class*="finish" i]', '.job-finished', '.task-finished', '.task-complete',
'[data-finished="true"]', '[data-status="finished"]', '[data-job-status="finished"]'
].join(',');
for (const context of contexts) {
const scope = context.root?.querySelectorAll ? context.root : context.doc;
try {
if (scope.matches?.(completedSelector)) return true;
const markers = Array.from(scope.querySelectorAll(completedSelector));
if (markers.some(marker => marker.getAttribute?.('aria-hidden') !== 'true')) return true;
} catch (_) {}
}
return false;
},
_readDocumentPageProgress(contexts) {
const indicatorSelector = [
'.page-num', '.page-number', '.page-count', '.page-index', '.current-page',
'.ppt-page', '.pdf-page-number', '[class*="pageNum"]', '[class*="page-num"]',
'[class*="page-number"]', '.pagination', '.swiper-pagination'
].join(',');
for (const context of contexts) {
const scope = context.root?.querySelectorAll ? context.root : context.doc;
// PDF.js 使用两个独立控件表示页码,不能依赖合并后的 "1/10" 文本。
try {
const currentEl = scope.querySelector?.('#pageNumber');
const totalEl = scope.querySelector?.('#numPages');
const current = Number.parseInt(String(currentEl?.value || currentEl?.textContent || '').match(/\d{1,4}/)?.[0] || '0', 10);
const total = Number.parseInt(String(totalEl?.value || totalEl?.textContent || '').match(/\d{1,4}/)?.[0] || '0', 10);
if (current > 0 && total > 0 && current <= total) {
return { current, total, key: `${current}/${total}` };
}
} catch (_) {}
let indicators = [];
try { indicators = Array.from(scope.querySelectorAll(indicatorSelector)); } catch (_) {}
for (const indicator of indicators) {
const text = String(indicator.innerText || indicator.textContent || indicator.value || '').replace(/\s+/g, ' ');
const match = text.match(/(?:第\s*)?(\d{1,4})\s*(?:页\s*)?(?:\/|/|of|页[,,]?\s*共|共)\s*(\d{1,4})/i) ||
text.match(/当前\s*(\d{1,4})\s*页[^\d]{0,12}共\s*(\d{1,4})\s*页/i);
if (!match) continue;
const current = Number(match[1]);
const total = Number(match[2]);
if (current > 0 && total > 0 && current <= total) {
return { current, total, key: `${current}/${total}` };
}
}
const slides = this._findDocumentSlides([{ ...context, root: scope }]);
if (slides.length > 0) {
const activeIndex = slides.findIndex(slide => {
const cls = String(slide.className || '');
return /(?:^|\s)(?:active|current|on|swiper-slide-active)(?:\s|$)/i.test(cls) ||
/^(?:true|page)$/.test(String(slide.getAttribute?.('aria-current') || ''));
});
if (activeIndex >= 0) {
return { current: activeIndex + 1, total: slides.length, key: `${activeIndex + 1}/${slides.length}` };
}
}
}
return { current: 0, total: 0, key: '' };
},
_findDocumentSlides(contexts) {
const selector = [
'.swiper-wrapper .swiper-slide', '.ppt-page-list li', '.ppt-slide-list li',
'.slide-list li', '.thumb-list li', '.thumbnail-list li', '.page-list li',
'[class*="slide-list"] li', '[class*="page-list"] li',
'[class*="thumbnail"]', '[class*="thumb"]'
].join(',');
const slides = [];
const seen = new Set();
for (const context of contexts) {
const scope = context.root?.querySelectorAll ? context.root : context.doc;
let nodes = [];
try { nodes = Array.from(scope.querySelectorAll(selector)); } catch (_) {}
for (const node of nodes) {
if (!node || seen.has(node)) continue;
const text = String(node.innerText || node.textContent || '').trim();
const hasMedia = !!node.querySelector?.('img, canvas, svg, [style*="background-image"]');
const numbered = /(?:第\s*)?\d{1,4}\s*页|^\s*\d{1,4}\s*$/.test(text) ||
!!node.getAttribute?.('data-page') || !!node.getAttribute?.('data-index');
if (!hasMedia && !numbered && !/swiper-slide/i.test(String(node.className || ''))) continue;
seen.add(node);
slides.push(node);
}
}
return slides.slice(0, 500);
},
_isDocumentNextControl(el) {
if (!el) return false;
const text = this._controlText(el);
const aria = String(el.getAttribute?.('aria-label') || el.getAttribute?.('title') || '').replace(/\s+/g, '');
const cls = String(el.className || '');
const id = String(el.id || el.getAttribute?.('id') || '');
return /^(下一页|下页|下一张|下一屏|后一页|NEXT)$/i.test(text) ||
/^(下一页|下页|下一张|下一屏|后一页|NEXT)$/i.test(aria) ||
id === 'next' ||
/(?:swiper-button-next|next-page|page-next|nextPage|nextBtn|turnPageRight|rightArrow|mkeRbtn)(?:\s|$)/i.test(cls) ||
/next-page/i.test(String(el.getAttribute?.('data-action') || ''));
},
_isDocumentControlDisabled(el) {
if (!el) return true;
const cls = String(el.className || '');
if (!!el.disabled || el.getAttribute?.('aria-disabled') === 'true' ||
/(?:^|\s)(?:disabled|is-disabled|swiper-button-disabled|forbid)(?:\s|$)/i.test(cls)) return true;
try {
const win = el.ownerDocument?.defaultView || window;
const style = win.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return true;
} catch (_) {}
const rect = el.getBoundingClientRect?.();
return !!(rect && rect.width === 0 && rect.height === 0);
},
_isLegacyDocumentNext(el) {
if (!el || !/(?:^|\s)mkeRbtn(?:\s|$)/i.test(String(el.className || ''))) return false;
try { return !!el.closest?.('.imglook'); } catch (_) { return false; }
},
_findDocumentNextControl(contexts, includeDisabled = false) {
const selector = [
'.imglook > .mkeRbtn', '#next',
'.swiper-button-next', '.next-page', '.page-next', '.nextPage', '.nextBtn',
'.turnPageRight', '.rightArrow', '[data-action="next-page"]',
'[aria-label*="下一页"]', '[title*="下一页"]',
'[aria-label*="下一张"]', '[title*="下一张"]',
'[aria-label*="下一屏"]', '[title*="下一屏"]',
'button', 'a', '[role="button"]', '[onclick]'
].join(',');
for (const context of contexts) {
const scope = context.root?.querySelectorAll ? context.root : context.doc;
let candidates = [];
try { candidates = Array.from(scope.querySelectorAll(selector)); } catch (_) {}
for (const candidate of candidates) {
if (!this._isDocumentNextControl(candidate)) continue;
if (includeDisabled) return candidate;
if (!this._isDocumentControlDisabled(candidate) && this._isUsableNavigationElement(candidate)) return candidate;
}
}
return null;
},
_findDocumentScrollTarget(contexts) {
const selector = [
'#viewerContainer', '.pdfViewer', '.pdf-viewer', '.document-reader',
'.document-viewer', '.viewerContainer', '.view-container', '[class*="scroll"]'
].join(',');
const candidates = [];
const seen = new Set();
const add = el => {
if (!el || seen.has(el)) return;
seen.add(el);
const scrollHeight = Number(el.scrollHeight || 0);
const clientHeight = Number(el.clientHeight || 0);
if (scrollHeight > clientHeight + 20) candidates.push(el);
};
for (const context of contexts) {
const scope = context.root?.querySelectorAll ? context.root : context.doc;
try { Array.from(scope.querySelectorAll(selector)).forEach(add); } catch (_) {}
try { add(context.doc.scrollingElement); } catch (_) {}
}
candidates.sort((a, b) => (b.scrollHeight - b.clientHeight) - (a.scrollHeight - a.clientHeight));
return candidates[0] || null;
},
_documentProgressSnapshot(contexts) {
const parts = [];
const progress = this._readDocumentPageProgress(contexts);
if (progress.key) parts.push(progress.key);
for (const context of contexts) {
try {
const src = String(context.frame?.src || context.frame?.getAttribute?.('src') || '');
if (src) parts.push(src);
const scope = context.root?.querySelector ? context.root : context.doc;
const active = scope.querySelector?.('.swiper-slide-active, .page-item.active, .thumbnail.active, [aria-current="page"]');
if (active) {
parts.push([
this._controlText(active).slice(0, 80),
active.getAttribute?.('data-index') || active.getAttribute?.('data-page') || '',
active.getAttribute?.('id') || ''
].join(':'));
}
const legacyImage = scope.querySelector?.('.imglook img');
if (legacyImage) {
parts.push([
'legacy-image',
String(legacyImage.currentSrc || legacyImage.src || legacyImage.getAttribute?.('data-src') || legacyImage.getAttribute?.('data-original') || '').slice(0, 300),
legacyImage.getAttribute?.('data-page') || legacyImage.getAttribute?.('data-index') || '',
String(legacyImage.getAttribute?.('style') || '').match(/background-image\s*:[^;]+/i)?.[0] || ''
].join(':'));
}
} catch (_) {}
}
const scrollTarget = this._findDocumentScrollTarget(contexts);
if (scrollTarget) {
parts.push(`scroll:${Math.round(Number(scrollTarget.scrollTop || 0))}/${Math.round(Number(scrollTarget.scrollHeight || 0))}`);
}
return parts.join('|');
},
_documentHasRenderedPage(contexts) {
const selector = 'canvas, .page, .pdf-page, .ppt-page, .swiper-slide, .slide, embed[type*="pdf" i], object[type*="pdf" i]';
return contexts.some(context => {
const scope = context.root?.querySelector ? context.root : context.doc;
try { return !!scope.querySelector(selector); } catch (_) { return false; }
});
},
_documentNoProgressResult(status, limit = 3) {
this._documentNoProgressCount++;
if (this._documentNoProgressCount >= limit) {
return {
complete: true,
moved: false,
status: `${status},已等待 ${this._documentNoProgressCount} 轮后继续`
};
}
return {
complete: false,
moved: false,
status: `${status}(等待 ${this._documentNoProgressCount}/${limit})`
};
},
async _progressDocumentContent(generation = this._playGeneration) {
const stopped = { complete: false, moved: false, status: '已停止' };
if (!this._isCurrent(generation)) return stopped;
let contexts = this._collectDocumentContexts();
if (contexts.length === 0) {
this._documentStateKey = 'document-context-missing';
return this._documentNoProgressResult('文档正在加载');
}
if (this._hasDocumentCompletionEvidence(contexts)) {
return { complete: true, moved: false, status: '平台已标记完成' };
}
let progress = this._readDocumentPageProgress(contexts);
if (progress.total > 0 && progress.current >= progress.total) {
return { complete: true, moved: false, status: `已浏览到第 ${progress.total} 页` };
}
const before = this._documentProgressSnapshot(contexts);
const next = this._findDocumentNextControl(contexts);
if (next) {
try {
next.scrollIntoView?.({ block: 'center' });
next.click();
} catch (_) {
return this._documentNoProgressResult('文档翻页按钮暂不可用');
}
await new Promise(resolve => setTimeout(resolve, 1200));
if (!this._isCurrent(generation)) return stopped;
contexts = this._collectDocumentContexts();
progress = this._readDocumentPageProgress(contexts);
const after = this._documentProgressSnapshot(contexts);
const moved = !!after && after !== before;
this._documentStateKey = after || before;
if (this._hasDocumentCompletionEvidence(contexts) || (progress.total > 0 && progress.current >= progress.total)) {
return { complete: true, moved: true, status: progress.total ? `已浏览到第 ${progress.total} 页` : '平台已标记完成' };
}
if (!moved) return this._documentNoProgressResult('等待文档完成翻页');
this._documentNoProgressCount = 0;
return {
complete: false,
moved: true,
status: progress.key ? `正在浏览第 ${progress.current}/${progress.total} 页` : '已翻到下一页'
};
}
const disabledNext = this._findDocumentNextControl(contexts, true);
if (disabledNext && this._isDocumentControlDisabled(disabledNext) &&
(this._isLegacyDocumentNext(disabledNext) || progress.current > 0 || this._documentNoProgressCount > 0)) {
return { complete: true, moved: false, status: '文档已到末页' };
}
const slides = this._findDocumentSlides(contexts);
if (slides.length > 1) {
let activeIndex = slides.findIndex(slide => {
const cls = String(slide.className || '');
return /(?:^|\s)(?:active|is-active|current|on|swiper-slide-active)(?:\s|$)/i.test(cls) ||
/^(?:true|page)$/.test(String(slide.getAttribute?.('aria-current') || ''));
});
if (activeIndex < 0 && progress.current > 0) activeIndex = Math.min(slides.length - 1, progress.current - 1);
if (activeIndex >= slides.length - 1) {
return { complete: true, moved: false, status: `已浏览到第 ${slides.length} 页` };
}
const targetIndex = activeIndex >= 0 ? activeIndex + 1 : 1;
const slide = slides[targetIndex];
const clickTarget = slide?.querySelector?.('button, a, [role="button"], img') || slide;
try {
clickTarget?.scrollIntoView?.({ block: 'nearest' });
clickTarget?.click?.();
} catch (_) {
return this._documentNoProgressResult('课件缩略页暂不可用');
}
await new Promise(resolve => setTimeout(resolve, 1200));
if (!this._isCurrent(generation)) return stopped;
contexts = this._collectDocumentContexts();
const after = this._documentProgressSnapshot(contexts);
const moved = !!after && after !== before;
this._documentStateKey = after || before;
if (!moved) return this._documentNoProgressResult('等待课件缩略页切换');
this._documentNoProgressCount = 0;
return { complete: false, moved: true, status: `正在浏览第 ${targetIndex + 1}/${slides.length} 页` };
}
const scrollTarget = this._findDocumentScrollTarget(contexts);
if (scrollTarget) {
const oldTop = Number(scrollTarget.scrollTop || 0);
const maxTop = Math.max(0, Number(scrollTarget.scrollHeight || 0) - Number(scrollTarget.clientHeight || 0));
if (oldTop < maxTop - 4) {
const nextTop = Math.min(maxTop, oldTop + Math.max(240, Number(scrollTarget.clientHeight || 600) * 0.85));
try {
if (typeof scrollTarget.scrollTo === 'function') scrollTarget.scrollTo({ top: nextTop, behavior: 'smooth' });
else scrollTarget.scrollTop = nextTop;
scrollTarget.dispatchEvent?.(new Event('scroll', { bubbles: true }));
} catch (_) { try { scrollTarget.scrollTop = nextTop; } catch (_) {} }
await new Promise(resolve => setTimeout(resolve, 900));
if (!this._isCurrent(generation)) return stopped;
const moved = Number(scrollTarget.scrollTop || 0) > oldTop;
this._documentStateKey = this._documentProgressSnapshot(contexts);
if (!moved) return this._documentNoProgressResult('等待文档滚动');
this._documentNoProgressCount = 0;
return { complete: false, moved: true, status: nextTop >= maxTop - 4 ? '已滚动到文档末页,等待完成状态' : '正在向下浏览文档' };
}
return { complete: true, moved: false, status: '文档已浏览到底' };
}
const snapshot = this._documentProgressSnapshot(contexts);
if (snapshot === this._documentStateKey) {
return this._documentNoProgressResult(
this._documentHasRenderedPage(contexts) ? '单页文档已停留' : '无法读取文档内部状态'
);
}
this._documentNoProgressCount = 0;
this._documentStateKey = snapshot;
return { complete: false, moved: false, status: '等待文档页码或完成状态' };
},
_scheduleDocumentRecheck(delay = 2500) {
if (this._pendingPlayTimeout) clearTimeout(this._pendingPlayTimeout);
this._pendingPlayTimeout = this._schedule(() => {
this._pendingPlayTimeout = null;
if (this._playing) this._tryPlayVideo();
}, delay);
},
async _handleNonVideoContent(retriesExhausted = false, generation = this._playGeneration) {
if (!this._isCurrent(generation)) return true;
const contentType = this._detectNonVideoContentType();
if (!contentType) return false;
const cfg = ConfigStore.getVideoConfig();
const label = contentType;
if (!cfg.autoAdvance) {
Logger.log(`检测到${label},自动推进已关闭,等待手动操作`, 'info');
UIPanel.setStatus(`${label},等待手动操作`, 'info');
return true;
}
if (this._isDocumentContentType(contentType)) {
const result = await this._progressDocumentContent(generation);
if (!this._isCurrent(generation)) return true;
if (!result.complete) {
const waitText = retriesExhausted && !result.moved ? `${result.status},继续等待` : result.status;
Logger.log(`${label}:${waitText}`, 'info');
UIPanel.setStatus(waitText, 'info');
this._scheduleDocumentRecheck(result.moved ? 1800 : 3000);
return true;
}
Logger.log(`${label}浏览完成(${result.status}),准备推进到下一节`, 'success');
UIPanel.setStatus(`${label}已完成,准备下一节`, 'success');
await new Promise(resolve => setTimeout(resolve, 1200));
} else {
Logger.log(`检测到${label},短暂停留后推进到下一节`, 'info');
UIPanel.setStatus(`${label},准备下一节`, 'info');
await new Promise(resolve => setTimeout(resolve, 1500));
}
if (!this._isCurrent(generation)) return true;
this._documentStateKey = '';
this._documentNoProgressCount = 0;
const advanced = this.advanceToNextChapter();
if (!advanced) {
Logger.log(`${label}处理完成,但未找到下一节`, 'info');
this.stop();
UIPanel.setStatus('未找到下一节', 'info');
}
return true;
},
_snapshotNodeId(node) {
if (!node || (typeof node !== 'object' && typeof node !== 'function')) return '';
try {
if (!this._snapshotNodeIds.has(node)) this._snapshotNodeIds.set(node, this._nextSnapshotNodeId++);
return this._snapshotNodeIds.get(node);
} catch (_) {
return '';
}
},
_lessonSnapshot() {
const parts = [`url:${String(location.href || '')}`];
const docs = CXUtils.listAccessibleDocs(document, 3);
const currentSelectors = [
'.posCatalog_active', '.currents', '[aria-current="page"]',
'[role="tab"][aria-selected="true"]', '.prev_ul .active', '.prev_tab .active',
'.chapter_tab .active', '.ans-cc-tab .active', '.tab-item.active', '.tab-item.on',
'[class*="tab"] button.active', '[class*="tab"] a.active', '[class*="tab"] li.active',
'[class*="tab"] .active', '[class*="tab"] .on'
].join(',');
for (const doc of docs) {
if (!doc || doc === UIPanel._doc) continue;
try {
parts.push(`title:${String(doc.title || '').replace(/\s+/g, ' ').trim().slice(0, 120)}`);
Array.from(doc.querySelectorAll(currentSelectors)).slice(0, 6).forEach(el => {
parts.push([
`current#${this._snapshotNodeId(el)}`,
this._controlText(el),
el.getAttribute?.('data-id') || '',
el.getAttribute?.('data-knowledge-id') || '',
el.getAttribute?.('href') || ''
].join(':'));
});
const headingSelectors = [
'main h1', 'main h2', 'main h3', '.main-content h1', '.main-content h2',
'.content-title', '.chapter-title', '.knowledge-title', '.course-title', '.task-title'
].join(',');
Array.from(doc.querySelectorAll(headingSelectors)).slice(0, 8).forEach(el => {
parts.push([
`heading#${this._snapshotNodeId(el)}`,
this._controlText(el).slice(0, 160),
el.getAttribute?.('data-id') || el.getAttribute?.('data-knowledge-id') || '',
el.getAttribute?.('id') || ''
].join(':'));
});
const taskSelectors = [
'[data-jobid]', '[data-job-id]', '[data-objectid]', '[data-object-id]',
'[data-attachment-id]', '[data-knowledge-id]', '[data-task-id]'
].join(',');
Array.from(doc.querySelectorAll(taskSelectors)).slice(0, 12).forEach(el => {
parts.push([
`task#${this._snapshotNodeId(el)}`,
el.getAttribute?.('data-jobid') || el.getAttribute?.('data-job-id') || '',
el.getAttribute?.('data-objectid') || el.getAttribute?.('data-object-id') || '',
el.getAttribute?.('data-attachment-id') || '',
el.getAttribute?.('data-knowledge-id') || '',
el.getAttribute?.('data-task-id') || ''
].join(':'));
});
const contentSelectors = '.ans-attach-ct, .chapter-content, .course-content, .main-content, main';
Array.from(doc.querySelectorAll(contentSelectors)).slice(0, 5).forEach(el => {
const text = String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 180);
parts.push(`content#${this._snapshotNodeId(el)}:${text}`);
});
Array.from(doc.querySelectorAll('iframe[src],object[data],embed[src]')).slice(0, 8).forEach(el => {
if (el.id === 'cx-helper-iframe') return;
parts.push([
`frame#${this._snapshotNodeId(el)}`,
el.getAttribute?.('src') || el.getAttribute?.('data') || '',
el.getAttribute?.('module') || '',
el.getAttribute?.('data-jobid') || el.getAttribute?.('data-objectid') || ''
].join(':'));
});
} catch (_) {}
}
return parts.join('|');
},
// 内部:刷新当前章节iframe
_refreshCurrentFrame(includeBrokenVideo = false, targetVideo = this._sourceWaitVideo) {
const docs = CXUtils.listAccessibleDocs(document, 4);
for (const doc of docs) {
let iframes = [];
try { iframes = Array.from(doc.querySelectorAll('iframe')); } catch (_) {}
for (const iframe of iframes) {
if (iframe.id === 'cx-helper-iframe') continue;
try {
const src = String(iframe.src || iframe.getAttribute?.('src') || '');
const moduleName = String(iframe.getAttribute?.('module') || '');
let frameVideos = null;
let hasDocumentMarker = false;
try {
const childDoc = iframe.contentDocument || iframe.contentWindow?.document;
if (childDoc) {
frameVideos = Array.from(childDoc.querySelectorAll?.('video') || []);
hasDocumentMarker = !!childDoc.querySelector?.('.ans-doc, .ans-ppt, .pdf-viewer, .ppt-viewer, .document-reader, .pdfViewer, .document-viewer');
}
} catch (_) { frameVideos = null; }
const isDocumentFrame = /(?:\/ananas\/modules\/(?:pdf|ppt|doc|book)\/|\.(?:pdf|ppt|pptx|doc|docx)(?:[?#]|$)|(?:^|[\/_.?=&-])(?:pdf|pptx?|docx?|book|office)(?:[\/_.?=&-]|$))/i.test(src) ||
/insert(?:ppt|pdf|doc|book)/i.test(moduleName) || hasDocumentMarker;
if (isDocumentFrame) continue;
const looksLikeVideoFrame = (
/\/ananas\/modules\/video\//i.test(src) ||
/(?:^|[\/_.?=&-])(video|player|m3u8|mp4|flv|hls)(?:[\/_.?=&-]|$)/i.test(src)
);
const containsTarget = !!(targetVideo && frameVideos?.includes?.(targetVideo));
const allVideosUnavailable = !!(frameVideos?.length) && frameVideos.every(video => {
if (video.dataset?.cxFinished === '1' || video.ended) return false;
return this._getVideoMediaState(video).state !== 'ready';
});
// 常规重试只刷新尚未创建 video 的播放器;媒体源重试耗尽时允许刷新
// 包含目标坏节点(或全部节点均无可用源)的纯视频 iframe 一次。
const shouldReloadBroken = includeBrokenVideo && (containsTarget || allVideosUnavailable);
if (looksLikeVideoFrame && src && (!frameVideos || frameVideos.length === 0 || shouldReloadBroken)) {
iframe.src = src;
return true;
}
} catch (_) { /* 跨域iframe只按 src 特征判断 */ }
}
}
return false;
},
// 内部:在iframe中查找章节测验页面(支持最多4层嵌套iframe)
_findChapterQuizDoc() {
const quizSelectors = '.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId, .TiMu, .mark_table';
// 先检查主页面
if (document.querySelector(quizSelectors)) return document;
// 递归搜索iframe,最多4层深度
const searchIframes = (doc, depth) => {
if (depth > 4) return null;
try {
const iframes = doc.querySelectorAll('iframe');
for (const iframe of iframes) {
try {
const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
if (!iframeDoc) continue;
if (iframeDoc.querySelector(quizSelectors)) return iframeDoc;
// 递归搜索更深层
const found = searchIframes(iframeDoc, depth + 1);
if (found) return found;
} catch (_) { /* 跨域iframe忽略 */ }
}
} catch (_) {}
return null;
};
return searchIframes(document, 1);
},
// 内部:自动答章节测验
async _autoAnswerChapterQuiz(quizDoc, generation = this._playGeneration) {
if (!this._isCurrent(generation)) return;
// 防止重复调用
if (this._quizAnswering) {
Logger.log('章节测验正在进行中,跳过重复调用', 'info');
return;
}
this._quizAnswering = true;
try {
await this._doAutoAnswerChapterQuiz(quizDoc, generation);
} finally {
if (generation === this._playGeneration) this._quizAnswering = false;
}
},
async _doAutoAnswerChapterQuiz(quizDoc, generation = this._playGeneration) {
const canContinue = () => this._isCurrent(generation) && !AnswerModule._stopRequested;
if (!canContinue()) return;
const videoCfg = ConfigStore.getVideoConfig();
const autoAnswer = videoCfg.autoAnswerQuiz !== false;
const quizMode = videoCfg.quizMode || 'free';
// 未勾选自动答题:直接推进下一章
if (!autoAnswer) {
Logger.log('章节测验:未开启自动答题,推进下一章节', 'info');
if (this._playing) {
this._schedule(() => this.advanceToNextChapter(), 2000);
}
return;
}
// 检查对应答题模式是否可用
const answerCfg = ConfigStore.getAnswerConfig();
if (quizMode === 'free') {
if (!ConfigStore.isVerifyValid()) {
Logger.log('章节测验:免费验证码未验证或已过期,跳过答题', 'info');
if (this._playing) {
this._schedule(() => this.advanceToNextChapter(), 2000);
}
return;
}
} else if (quizMode === 'ai') {
if (!answerCfg.aiApiKey) {
Logger.log('章节测验:未配置AI API Key,跳过答题', 'info');
if (this._playing) {
this._schedule(() => this.advanceToNextChapter(), 2000);
}
return;
}
}
// 付费模式不做前置检查,直接尝试答题(积分不足时API会返回错误)
// 临时切换答题模式为视频设置中选择的模式(不持久化)
const prevMode = AnswerModule._mode;
const modeState = { generation, previous: prevMode, mode: quizMode };
this._quizModeState = modeState;
AnswerModule._mode = quizMode;
try {
let allAnswered = true;
const containers = quizDoc.querySelectorAll(
'.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId'
);
if (containers.length === 0) {
Logger.log('章节测验未找到题目,跳过', 'info');
if (this._playing) {
this._schedule(() => this.advanceToNextChapter(), 2000);
}
return;
}
Logger.log(`章节测验共 ${containers.length} 题,开始自动答题(模式: ${quizMode})`, 'info');
for (let i = 0; i < containers.length; i++) {
if (!canContinue()) return;
const container = containers[i];
// 跳过已完成题目
if (AnswerModule._isQuestionCompleted(container)) {
Logger.log(`章节测验第 ${i + 1} 题已完成,跳过`, 'info');
continue;
}
const _qzLabel = `章节测验第 ${i + 1} 题`;
try {
const qData = await Solver.recognize(container, { canContinue });
if (!canContinue()) return;
if (!qData.question) {
allAnswered = false;
Logger.log(`${_qzLabel} 识别失败,跳过`, 'error');
continue;
}
const bankResult = await AnswerModule._queryAnswer(qData.question, qData.options, qData.type, qData.images || []);
if (!canContinue()) return;
// 智能匹配 + AI 兜底(_applyAnswer 内部已处理无命中场景)
const ok = await AnswerModule._applyAnswer(qData, container, _qzLabel, bankResult, canContinue);
if (!canContinue()) return;
if (ok && AnswerModule._isQuestionCompleted(container)) {
// 章节测验逐题自动提交
await Solver._clickSubmit(container, canContinue);
if (!canContinue()) return;
Logger.log(`${_qzLabel} 已作答`, 'success');
} else {
allAnswered = false;
}
} catch (e) {
if (!canContinue()) return;
allAnswered = false;
Logger.log(`${_qzLabel} 异常: ${e.message || e}`, 'error');
}
// 题间延迟(AI模式:解锁后1.5秒,未解锁35秒;其他1-2秒)
if (i < containers.length - 1) {
const delay = await AnswerModule._getQuestionDelay();
if (!canContinue()) return;
if (quizMode === 'ai' && delay > 10000) Logger.log(`AI模式冷却中,${Math.round(delay/1000)}秒后继续(解锁后可加速)...`, 'info');
await AnswerModule._delay(delay);
if (!canContinue()) return;
}
}
if (!canContinue()) return;
if (!allAnswered || !AnswerModule._canSubmitQuestions(containers, '章节测验')) {
Logger.log('章节测验未完整作答,已暂停并保留答案,请检查后继续', 'error');
this.stop();
return;
}
const submitted = await Solver._clickFinalSubmit(quizDoc, '章节测验', canContinue);
if (!canContinue()) return;
if (!submitted) {
Logger.log('章节测验未提交,已暂停,请检查页面', 'info');
this.stop();
return;
}
// 答完推进下一章,恢复之前的答题模式
if (this._playing) {
Logger.log('章节测验完成,推进下一章节', 'info');
await new Promise(r => setTimeout(r, 3000));
if (canContinue()) this.advanceToNextChapter();
}
} finally {
this._restoreQuizMode(modeState);
}
},
// 内部:绑定视频事件
_bindVideoEvents(video) {
// 防止重复绑定 ended 监听器(_tryPlayVideoInner 可能在同一 video 上多次调用)
if (video.dataset.cxEndedBound === '1') return;
video.dataset.cxEndedBound = '1';
const generation = this._playGeneration;
// 监听视频结束事件
const onEnded = () => {
if (!this._isCurrent(generation)) return;
Logger.log('当前视频播放完毕', 'success');
// 标记此视频已完成,避免下次查找时重复返回
video.dataset.cxFinished = '1';
const finishedSource = this._getVideoSourceKey(video);
if (finishedSource) video.dataset.cxFinishedSrc = finishedSource;
// 清除之前的待执行播放定时器
if (this._pendingPlayTimeout) {
clearTimeout(this._pendingPlayTimeout);
this._pendingPlayTimeout = null;
}
if (_isMediaWorkerFrame) {
this._videoEl = null;
FrameMediaBridge.notifyWorkerEnded();
return;
}
const cfg = ConfigStore.getVideoConfig();
if (!cfg.autoAdvance) {
Logger.log('自动推进已关闭,等待手动操作', 'info');
UIPanel.setStatus('视频播放完毕', 'info');
return;
}
// 优先检查:当前课时页面是否还有未播放的其他视频任务点
// (学习通一个课时常放多个视频,截图:3. xxx / 4. xxx)
const nextVideo = this._findVideoElement();
if (nextVideo && nextVideo !== video) {
Logger.log('检测到同课时还有其他视频任务点,继续播放下一个', 'info');
this._videoEl = null; // 清当前引用,避免脏状态
this._pendingPlayTimeout = this._schedule(() => {
if (!this._playing) return;
// 滚动到下一个视频,让 lazy-loaded 的播放器初始化
try { nextVideo.scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (_) {}
// 等 1.5s 让 scroll + 任务点上报完成
this._schedule(() => this._tryPlayVideo(), 1500);
}, 1500);
return;
}
if (FrameMediaBridge.playNextWorker()) {
Logger.log('检测到同课时还有跨域视频任务点,继续播放', 'info');
this._videoEl = null;
return;
}
// 当前课时所有视频均已播完 → 检查测验或推进下一章
const autoAnswer = cfg.autoAnswerQuiz !== false;
if (autoAnswer) {
this._schedule(() => this._checkAndHandleChapterQuiz(), 1500);
} else {
this._schedule(() => this.advanceToNextChapter(), 1500);
}
};
video.addEventListener('ended', onEnded);
// 保存引用以便清理
this._antiPauseHandlers.push({ target: video, event: 'ended', handler: onEnded, capture: false });
},
_handleRemoteVideoEnded() {
if (!this._playing) return;
Logger.log('跨域视频播放完毕', 'success');
const cfg = ConfigStore.getVideoConfig();
if (cfg.autoAdvance === false) {
UIPanel.setStatus('视频播放完毕', 'info');
return;
}
if (FrameMediaBridge.playNextWorker()) {
Logger.log('检测到同课时还有其他视频任务点,继续播放下一个', 'info');
return;
}
if (cfg.autoAnswerQuiz !== false) {
this._schedule(() => this._checkAndHandleChapterQuiz(), 1500);
} else {
this._schedule(() => this.advanceToNextChapter(), 1500);
}
},
_handleRemoteVideoUnavailable(detail = '') {
if (!this._playing) return;
Logger.log(`跨域视频源不可用${detail ? `: ${detail}` : ''},继续后续任务`, 'error');
if (FrameMediaBridge.playNextWorker()) return;
const cfg = ConfigStore.getVideoConfig();
if (cfg.autoAdvance === false) {
UIPanel.setStatus('视频源不可用', 'error');
return;
}
if (cfg.autoAnswerQuiz !== false) {
this._schedule(() => this._checkAndHandleChapterQuiz(), 1000);
} else {
this._schedule(() => this.advanceToNextChapter(), 1000);
}
},
// 6.1 - setPlaybackRate(): 设置倍速
setPlaybackRate(rate) {
const video = this._videoEl || this._findVideoElement();
if (video) {
video.playbackRate = rate;
Logger.log(`播放倍速已设置为 ${rate}x`, 'info');
}
if (!_isMediaWorkerFrame) FrameMediaBridge.setPlaybackRate(rate);
// 同步到配置
const cfg = ConfigStore.getVideoConfig();
cfg.playbackRate = rate;
ConfigStore.setVideoConfig(cfg);
},
// 6.2 - installAntiPause(): 安装防暂停钩子
installAntiPause() {
this.removeAntiPause();
const generation = this._playGeneration;
// 拦截 visibilitychange(capture阶段阻止传播)
const onVisibilityChange = (e) => {
if (!this._isCurrent(generation)) return;
e.stopImmediatePropagation();
e.preventDefault();
};
document.addEventListener('visibilitychange', onVisibilityChange, true);
this._antiPauseHandlers.push({ target: document, event: 'visibilitychange', handler: onVisibilityChange, capture: true });
// 拦截 mouseout
const onMouseOut = (e) => {
if (this._isCurrent(generation)) {
e.stopImmediatePropagation();
}
};
document.addEventListener('mouseout', onMouseOut, true);
this._antiPauseHandlers.push({ target: document, event: 'mouseout', handler: onMouseOut, capture: true });
// 拦截 blur
const onBlur = (e) => {
if (this._isCurrent(generation)) {
e.stopImmediatePropagation();
}
};
window.addEventListener('blur', onBlur, true);
this._antiPauseHandlers.push({ target: window, event: 'blur', handler: onBlur, capture: true });
// 监听视频 pause 事件 — 非用户主动暂停时自动恢复
this._installVideoPauseHook();
// 3秒超时自动恢复:定时检查视频状态
this._pauseCheckInterval = setInterval(() => {
if (!this._isCurrent(generation)) return;
const video = this._videoEl || this._findVideoElement();
if (video && video.paused && !video.ended && !this._userPaused && !this._isVideoQuizBlocking() && this._isVideoSourceReady(video)) {
const pauseDuration = Date.now() - this._lastPauseTime;
if (this._lastPauseTime > 0 && pauseDuration >= 3000) {
Logger.log('视频暂停超过3秒,自动恢复播放', 'info');
video.play().catch(error => {
if (this._isCurrent(generation) && this._isSourcePlayError(error)) this._queueVideoSourceRetry(video, this._getVideoMediaState(video), error);
});
this._lastPauseTime = 0;
}
}
}, 1000);
Logger.log('防中断机制已安装', 'info');
},
// 内部:安装视频pause事件钩子
_installVideoPauseHook(targetVideo = null) {
const hookPause = (video) => {
if (!video || video.dataset.cxPauseBound === '1') return;
video.dataset.cxPauseBound = '1';
const generation = this._playGeneration;
const onPause = () => {
if (!this._isCurrent(generation) || video.ended) return;
if (this._userPaused) return;
this._lastPauseTime = Date.now();
// 短暂延迟后恢复,避免与正常seek冲突
this._schedule(() => {
if (this._playing && generation === this._playGeneration && video.paused && !video.ended && !this._userPaused && !this._isVideoQuizBlocking() && this._isVideoSourceReady(video)) {
video.play().catch(error => {
if (this._isCurrent(generation) && this._isSourcePlayError(error)) this._queueVideoSourceRetry(video, this._getVideoMediaState(video), error);
});
}
}, 500);
};
video.addEventListener('pause', onPause);
this._antiPauseHandlers.push({ target: video, event: 'pause', handler: onPause, capture: false });
};
// 对当前视频安装
const video = targetVideo || this._videoEl || this._findVideoElement();
if (video) hookPause(video);
},
// 6.2 - removeAntiPause(): 移除所有钩子
removeAntiPause() {
this._antiPauseHandlers.forEach(({ target, event, handler, capture }) => {
try {
target.removeEventListener(event, handler, capture);
if (event === 'ended' && target.dataset) delete target.dataset.cxEndedBound;
if (event === 'pause' && target.dataset) delete target.dataset.cxPauseBound;
} catch (_) {}
});
this._antiPauseHandlers = [];
if (this._pauseCheckInterval) {
clearInterval(this._pauseCheckInterval);
this._pauseCheckInterval = null;
}
this._lastPauseTime = 0;
},
// 6.3 - _checkAndHandleChapterQuiz(): 视频播完后检查当前页面是否有章节测验iframe
async _checkAndHandleChapterQuiz(generation = this._playGeneration) {
if (!this._isCurrent(generation)) return;
// 学习通的章节页面结构:一个章节下有多个iframe任务点(视频、测验等)
// 视频播完后,测验iframe可能已经在当前页面上了
Logger.log('检查当前页面是否有章节测验...', 'info');
// 等待一下让页面稳定
await new Promise(r => setTimeout(r, 1000));
if (!this._isCurrent(generation)) return;
const quizDoc = this._findChapterQuizDoc();
if (quizDoc) {
Logger.log('在当前页面检测到章节测验,开始答题', 'info');
await this._autoAnswerChapterQuiz(quizDoc, generation);
return; // _autoAnswerChapterQuiz 完成后会自己调 advanceToNextChapter
}
// 当前页面没有测验,尝试查找页面上的测验tab/任务点链接并点击
// 学习通页面上方有任务点tab,如 "1 视频" "2 章节测验"
const tabSelectors = [
'.prev_ul li', '.ans-attach-ct .ans-job-icon', '.prev_tab li',
'.chapter_tab li', '.ans-cc-tab li', '[class*="tab"] li'
];
let quizTab = null;
// 在主页面查找
for (const sel of tabSelectors) {
const tabs = document.querySelectorAll(sel);
for (const tab of tabs) {
const text = tab.textContent?.trim() || '';
if (/测验|作业|quiz|test/i.test(text)) {
quizTab = tab;
break;
}
}
if (quizTab) break;
}
// 在iframe中查找
if (!quizTab) {
const iframes = document.querySelectorAll('iframe');
for (const iframe of iframes) {
try {
const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
if (!iframeDoc) continue;
for (const sel of tabSelectors) {
const tabs = iframeDoc.querySelectorAll(sel);
for (const tab of tabs) {
const text = tab.textContent?.trim() || '';
if (/测验|作业|quiz|test/i.test(text)) {
quizTab = tab;
break;
}
}
if (quizTab) break;
}
} catch (_) {}
if (quizTab) break;
}
}
if (quizTab) {
const tabText = quizTab.textContent?.trim().substring(0, 20) || '测验';
Logger.log(`找到测验tab: ${tabText},点击进入`, 'info');
const clickTarget = quizTab.querySelector('a, span, div') || quizTab;
clickTarget.click();
if (!this._isCurrent(generation)) return;
// 多次尝试检测测验,每次等待递增(iframe加载可能较慢)
for (let attempt = 1; attempt <= 5; attempt++) {
await new Promise(r => setTimeout(r, 2000 + attempt * 1000));
if (!this._isCurrent(generation)) return;
const quizDoc2 = this._findChapterQuizDoc();
if (quizDoc2) {
Logger.log('测验页面已加载,开始答题', 'info');
await this._autoAnswerChapterQuiz(quizDoc2, generation);
return;
}
}
Logger.log('多次尝试后仍未检测到题目,推进下一章', 'info');
} else {
Logger.log('当前章节无测验,推进下一章', 'info');
}
this.advanceToNextChapter();
},
// 6.3 - advanceToNextChapter(): 优先推进页面“下一节”,再回退章节树
advanceToNextChapter(skipPageNext = false) {
if (!this._playing) return false;
const generation = this._playGeneration;
const cfg = ConfigStore.getVideoConfig();
if (!cfg.autoAdvance) {
Logger.log('自动推进已关闭', 'info');
return false;
}
if (this._advanceInFlight) return true;
if (this._pendingPlayTimeout) {
clearTimeout(this._pendingPlayTimeout);
this._pendingPlayTimeout = null;
}
// SPA 切换时旧视频 DOM 可能仍存在,保留来源关联的完成标记可防止重复播放。
this._videoEl = null;
if (!skipPageNext) {
const pageNext = this._findPageNextButton();
const beforeSnapshot = this._lessonSnapshot();
const alreadyTried = pageNext && pageNext === this._lastNextControl &&
beforeSnapshot === this._lastNextSnapshot;
if (pageNext && !alreadyTried) {
const label = this._controlText(pageNext) || '下一节';
Logger.log(`点击课程页“${label}”`, 'info');
this._lastNextControl = pageNext;
this._lastNextSnapshot = beforeSnapshot;
this._advanceInFlight = true;
try {
this._resetVideoSourceWait(true);
if (!_isMediaWorkerFrame) FrameMediaBridge.resetChapter();
pageNext.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
pageNext.click();
if (!this._isCurrent(generation)) return false;
} catch (error) {
if (!this._isCurrent(generation)) return false;
this._advanceInFlight = false;
Logger.log(`点击“${label}”失败: ${error.message || error}`, 'error');
return this.advanceToNextChapter(true);
}
// 学习通 SPA 可能复用 URL 和 iframe,只替换正文。连续短轮询标题、任务标识、
// 内容根及节点身份,避免一次快照漏报后又点章节树而连续跳过两节。
const verifyPageChange = remainingChecks => {
if (!this._isCurrent(generation)) return;
this._pendingPlayTimeout = null;
const afterSnapshot = this._lessonSnapshot();
const controlDetached = pageNext.isConnected === false;
const controlUnavailable = controlDetached || !this._isUsableNavigationElement(pageNext);
if (afterSnapshot !== beforeSnapshot || controlUnavailable) {
this._advanceInFlight = false;
this._loadRetryCount = 0;
this._documentStateKey = '';
this._documentNoProgressCount = 0;
this._tryPlayVideo();
return;
}
if (remainingChecks > 0) {
this._pendingPlayTimeout = this._schedule(() => verifyPageChange(remainingChecks - 1), 500);
return;
}
this._advanceInFlight = false;
Logger.log(`“${label}”点击后页面持续未变化,改用章节树推进`, 'info');
const fallbackAdvanced = this.advanceToNextChapter(true);
if (!fallbackAdvanced && this._playing) {
this.stop();
UIPanel.setStatus('未找到下一节', 'info');
}
};
this._pendingPlayTimeout = this._schedule(() => verifyPageChange(12), 500);
this._updateVideoUI();
return true;
}
}
let courseTree = null;
const docs = CXUtils.listAccessibleDocs(document, 4);
for (const doc of docs) {
try { courseTree = doc.getElementById?.('coursetree'); } catch (_) { courseTree = null; }
if (courseTree) break;
}
if (!courseTree) {
Logger.log('未找到课程页“下一节”或章节树 (#coursetree)', 'error');
return false;
}
const nodeSelectors = [
'li[onclick]', 'span.posCatalog_name[onclick]', 'div.posCatalog_name[onclick]',
'a[href*="chapterId"]', '[role="treeitem"][data-id]', '[data-knowledge-id]'
].join(',');
const allNodes = Array.from(new Set(courseTree.querySelectorAll(nodeSelectors)));
if (allNodes.length === 0) {
const fallbackNodes = Array.from(courseTree.querySelectorAll('[onclick]'));
if (fallbackNodes.length === 0) {
Logger.log('章节树中未找到可点击节点', 'error');
return false;
}
allNodes.push(...fallbackNodes);
}
let currentIdx = -1;
for (let i = 0; i < allNodes.length; i++) {
const node = allNodes[i];
if (node.classList.contains('posCatalog_active') || node.classList.contains('currents') ||
node.closest('.posCatalog_active') || node.closest('.currents') ||
node.querySelector('.posCatalog_active') ||
node.parentElement?.classList.contains('posCatalog_active')) {
currentIdx = i;
}
}
if (currentIdx === -1) {
const urlMatch = location.href.match(/[?&]chapterId=(\d+)/);
if (urlMatch) {
const chapterId = urlMatch[1];
const idPattern = new RegExp(`(^|\\D)${chapterId}(?=\\D|$)`);
for (let i = 0; i < allNodes.length; i++) {
const source = [
allNodes[i].getAttribute?.('onclick') || '',
allNodes[i].getAttribute?.('href') || '',
allNodes[i].getAttribute?.('data-id') || '',
allNodes[i].getAttribute?.('data-knowledge-id') || ''
].join('|');
if (idPattern.test(source)) {
currentIdx = i;
break;
}
}
}
}
if (currentIdx === -1) {
Logger.log('未能定位当前章节,停止树形导航以避免回到第一节', 'error');
return false;
}
let nextChapter = null;
for (let i = currentIdx + 1; i < allNodes.length; i++) {
const node = allNodes[i];
const li = node.closest('li') || node;
const isCompleted = li.classList.contains('finished') ||
!!li.querySelector('.icon-finish, .roundpoint.done, .catalog_finished, .roundpointStudent.done, .icon_Ede_Stuednt');
if (isCompleted) {
const skipName = node.textContent?.trim().substring(0, 20) || '';
Logger.log(`跳过已完成: ${skipName}`, 'info');
continue;
}
nextChapter = node;
break;
}
if (!nextChapter) {
Logger.log('所有章节已完成', 'success');
this.stop();
UIPanel.setStatus('所有章节已完成', 'success');
this._updateVideoUI();
return true;
}
const chapterName = nextChapter.textContent?.trim().substring(0, 30) || '下一章节';
Logger.log(`推进到: ${chapterName}`, 'info');
this._currentChapter = chapterName;
this._resetVideoSourceWait(true);
if (!_isMediaWorkerFrame) FrameMediaBridge.resetChapter();
nextChapter.click();
if (!this._isCurrent(generation)) return false;
this._pendingPlayTimeout = this._schedule(() => {
this._pendingPlayTimeout = null;
if (this._playing) {
this._loadRetryCount = 0;
this._tryPlayVideo();
}
}, 3000);
this._updateVideoUI();
return true;
},
_isVideoPopupVisible(root) {
if (!root || root.isConnected === false || !Solver._isVisibleElement(root)) return false;
try {
const win = root.ownerDocument?.defaultView || window;
for (let node = root; node && node.nodeType === 1; node = node.parentElement) {
const style = win.getComputedStyle(node);
if (node.hidden || node.getAttribute('aria-hidden') === 'true' || style.display === 'none' ||
style.visibility === 'hidden' || Number(style.opacity) === 0) return false;
}
} catch (_) {}
return true;
},
_isVideoQuizBlocking() {
return this._quizAnswering || !!this._findVideoPopupQuizDoc();
},
_findVideoPopupQuizDoc() {
const docs = CXUtils.listAccessibleDocs(document, 4);
const popupSelectors = [
'.ans-videoquiz',
'[id^="videoquiz"]',
'.videoquiz',
'.video-quiz',
'.popboxes',
'.layui-layer',
'.xubox_layer',
'.mvp-question',
'.topicWrap',
'.ans-dialog'
];
const questionSelectors = '.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId, .TiMu, .mark_table';
for (const doc of docs) {
for (const sel of popupSelectors) {
let nodes = [];
try { nodes = Array.from(doc.querySelectorAll(sel)); } catch (_) {}
for (const node of nodes) {
if (!this._isVideoPopupVisible(node)) continue;
// 普通提示框也有“确定/继续”,必须同时存在作答区域才可接管。
const hasAnswerControls = node.querySelector('input[type="radio"], input[type="checkbox"], textarea, input[type="text"], .ans-videoquiz-opt label, .answerBg, .num_option, .num_option_dx, [role="radio"], [role="checkbox"]');
const hasQuestion = node.querySelector(questionSelectors) ||
node.querySelector('.ans-videoquiz-title, .ans-videoquiz-question') ||
/单选|多选|判断|填空|题目/.test(node.innerText || node.textContent || '');
if (hasAnswerControls && hasQuestion) return { doc, root: node };
}
}
}
return null;
},
async _waitForVideoPopupClose(root, canContinue, timeout = 6000) {
const deadline = Date.now() + timeout;
while (canContinue()) {
if (!this._isVideoPopupVisible(root)) return true;
if (Date.now() >= deadline) return false;
await new Promise(resolve => setTimeout(resolve, 100));
}
return false;
},
_resumeAfterVideoPopup(canContinue) {
if (!canContinue() || this._findVideoPopupQuizDoc()) return;
const video = this._videoEl || this._findVideoElement();
if (video && video.paused && !video.ended && !this._userPaused && this._isVideoSourceReady(video)) {
video.play().catch(error => {
if (canContinue() && this._isSourcePlayError(error)) this._queueVideoSourceRetry(video, this._getVideoMediaState(video), error);
});
}
},
async _canUseQuizMode(quizMode, label) {
const answerCfg = ConfigStore.getAnswerConfig();
if (quizMode === 'free' && !ConfigStore.isVerifyValid()) {
Logger.log(`${label}:免费验证码未验证或已过期,无法自动答题`, 'info');
return false;
}
if (quizMode === 'ai' && !answerCfg.aiApiKey) {
Logger.log(`${label}:未配置AI API Key,无法自动答题`, 'info');
return false;
}
return true;
},
async _answerVideoPopupQuizIfNeeded() {
if (!this._playing) return false;
// 接管期间轮询不得进入关闭分支,也不得抢占手动作业/考试的答题模式。
if (this._quizAnswering || AnswerModule._answering) return true;
const cfg = ConfigStore.getVideoConfig();
if (cfg.autoAnswerQuiz === false) return false;
const found = this._findVideoPopupQuizDoc();
if (!found) return false;
this._quizAnswering = true;
const generation = this._playGeneration;
const canContinue = () => this._playing && generation === this._playGeneration && !AnswerModule._stopRequested && !AnswerModule._answering;
const quizMode = cfg.quizMode || 'free';
const prevMode = AnswerModule._mode;
const modeState = { generation, previous: prevMode, mode: quizMode };
this._quizModeState = modeState;
AnswerModule._mode = quizMode;
try {
if (!(await this._canUseQuizMode(quizMode, '视频弹题'))) {
if (canContinue()) this.stop();
return true;
}
if (!canContinue()) return true;
const scope = found.root || found.doc;
const containers = Array.from(scope.querySelectorAll(
'.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId, .TiMu, .mark_table'
)).filter(node => this._isVideoPopupVisible(node));
const fallbackContainer = containers.length ? null : scope;
const targets = containers.length ? containers.filter(node => !containers.some(other => other !== node && other.contains(node))) : [fallbackContainer].filter(Boolean);
if (targets.length === 0) return false;
Logger.log(`检测到视频中途弹题,共 ${targets.length} 题,开始自动作答`, 'info');
let allAnswered = true;
for (let i = 0; i < targets.length; i++) {
if (!canContinue()) return true;
const container = targets[i];
const canAnswer = () => canContinue() && this._isVideoPopupVisible(scope) && this._isVideoPopupVisible(container);
if (!canAnswer()) return true;
if (AnswerModule._isQuestionCompleted(container)) continue;
const label = `视频弹题第 ${i + 1} 题`;
const qData = await Solver.recognize(container, { canContinue: canAnswer });
if (!canAnswer()) return true;
if (!qData.question) {
allAnswered = false;
Logger.log(`${label} 识别失败,跳过`, 'error');
continue;
}
const bankResult = await AnswerModule._queryAnswer(qData.question, qData.options, qData.type, qData.images || []);
if (!canAnswer()) return true;
const ok = await AnswerModule._applyAnswer(qData, container, label, bankResult, canAnswer);
if (!canAnswer()) return true;
if (ok && AnswerModule._isQuestionCompleted(container)) {
Logger.log(`${label} 已作答`, 'success');
} else {
allAnswered = false;
}
if (i < targets.length - 1) {
const delay = await AnswerModule._getQuestionDelay();
if (!canContinue()) return true;
if (quizMode === 'ai' && delay > 10000) Logger.log(`AI模式冷却中,${Math.round(delay/1000)}秒后继续(解锁后可加速)...`, 'info');
const deadline = Date.now() + delay;
while (canContinue() && Date.now() < deadline) {
if (quizMode === 'ai' && delay > 10000 && __scriptVerificationV1.sessionValid('ai-unlock', ConfigStore.getDeviceId(), ConfigStore.getAIUnlockSessionToken(), ConfigStore.getAIUnlockUntil())) break;
await new Promise(resolve => setTimeout(resolve, Math.min(100, deadline - Date.now())));
}
}
}
if (!canContinue()) return true;
if (!allAnswered || !AnswerModule._canSubmitQuestions(targets, '视频弹题')) {
Logger.log('视频弹题未完整作答,已暂停并保留答案,请检查后继续', 'error');
this.stop();
return true; // 已接管弹题,阻止调用方继续自动关闭未答完的弹窗。
}
// 视频题只提交一次,并且只能点当前弹题内的提交控件。
// 不能复用整卷提交:它会回退到主文档,误点作业提交或把同一题点两次。
const platformSubmit = scope.querySelector('#videoquiz-submit');
const submitBtn = platformSubmit && Solver._isVisibleElement(platformSubmit) ? platformSubmit :
Solver._findClickableByText(found.doc, ['提交答案', '提交', '确定'], scope);
if (!submitBtn || !this._isVideoPopupVisible(scope)) {
Logger.log('视频弹题未找到可用提交按钮,已暂停并保留答案,请手动检查', 'error');
this.stop();
return true;
}
if (!canContinue()) return true;
submitBtn.click();
Logger.log('视频弹题已点击提交,等待页面确认', 'info');
let closed = await this._waitForVideoPopupClose(scope, canContinue, 2000);
if (!canContinue()) return true;
if (!closed) {
// 仅允许明确的“继续播放/学习”,不能把“关闭/确定”当成提交成功。
const continueBtn = Solver._findClickableByText(found.doc, ['继续播放', '继续学习'], scope);
if (continueBtn && canContinue()) continueBtn.click();
closed = await this._waitForVideoPopupClose(scope, canContinue, 4000);
}
if (!canContinue()) return true;
if (!closed) {
Logger.log('视频弹题提交后仍未关闭,可能未通过或尚未保存,已暂停并保留答案,请检查页面提示', 'error');
this.stop();
return true;
}
this._lastQuizCloseTime = Date.now();
Logger.log('视频弹题已完成,恢复播放', 'success');
this._resumeAfterVideoPopup(canContinue);
return true;
} catch (e) {
if (canContinue()) {
Logger.log('视频弹题处理异常,已暂停并保留答案: ' + (e.message || e), 'error');
this.stop();
}
return true;
} finally {
this._restoreQuizMode(modeState);
if (generation === this._playGeneration) this._quizAnswering = false;
}
},
// 只处理确有关闭控件的可跳过弹窗,并核实关闭后才恢复播放。
async _tryDismissQuizPopup() {
const generation = this._playGeneration;
const canContinue = () => this._playing && generation === this._playGeneration;
const selectors = '.ans-videoquiz-close, #videoquiz-close, [id^="videoquiz"] .close_btn, .ans-videoquiz .x-btn';
for (const doc of CXUtils.listAccessibleDocs(document, 4)) {
for (const button of doc.querySelectorAll(selectors)) {
const root = button.closest('.ans-videoquiz, [id^="videoquiz"], .popboxes');
if (!root || !this._isVideoPopupVisible(root) || !Solver._isVisibleElement(button)) continue;
if (!canContinue()) return false;
this._quizAnswering = true;
try {
button.click();
const closed = await this._waitForVideoPopupClose(root, canContinue, 2000);
if (!canContinue()) return true;
if (!closed) {
Logger.log('该视频弹题不能直接关闭,请完成作答后继续,已暂停自动播放', 'info');
this.stop();
return true;
}
this._lastQuizCloseTime = Date.now();
Logger.log('已关闭可跳过的视频弹题', 'info');
this._resumeAfterVideoPopup(canContinue);
return true;
} finally {
if (generation === this._playGeneration) this._quizAnswering = false;
}
}
}
return false;
},
// 6.4 - detectAndCloseQuiz(): 检测并关闭视频中弹出的测验弹窗(不影响章节测验页面)
async detectAndCloseQuiz() {
if (!this._playing) return false;
const generation = this._playGeneration;
if (this._quizAnswering || AnswerModule._answering) return true;
const cfg = ConfigStore.getVideoConfig();
const canSkip = cfg.autoSkipQuiz !== false;
const canAnswer = cfg.autoAnswerQuiz !== false;
if (!canSkip && !canAnswer) return false;
// 冷却时间:避免频繁关闭
if (Date.now() - this._lastQuizCloseTime < 3000) return false;
if (canAnswer && await this._answerVideoPopupQuizIfNeeded()) return true;
if (!this._isCurrent(generation)) return true;
if (!canSkip) return false;
return this._tryDismissQuizPopup();
},
// 6.6 - getCurrentChapter(): 返回当前章节名称
getCurrentChapter() {
return this._currentChapter || '未知章节';
},
// 6.6 - getProgress(): 返回 0-100 进度百分比
getProgress() {
return this._progress;
},
// isPlaying(): 返回是否正在播放
isPlaying() {
return this._playing;
},
// 内部:更新章节名称
_updateChapterName() {
// 从章节树获取当前活跃章节名称
const courseTree = document.getElementById('coursetree');
if (courseTree) {
const active = courseTree.querySelector('.posCatalog_active, .currents, .active');
if (active) {
this._currentChapter = active.textContent?.trim().substring(0, 30) || '当前章节';
return;
}
}
// 备选:从页面标题获取
const title = document.title || '';
if (title) {
this._currentChapter = title.substring(0, 30);
}
},
// 内部:更新播放进度
_updateProgress() {
const video = this._videoEl || this._findVideoElement();
if (video && video.duration > 0) {
this._progress = Math.round((video.currentTime / video.duration) * 100);
} else if (!_isMediaWorkerFrame) {
const remoteProgress = FrameMediaBridge.getActiveProgress();
this._progress = remoteProgress == null ? 0 : remoteProgress;
} else {
this._progress = 0;
}
if (_isMediaWorkerFrame) FrameMediaBridge.reportWorkerState();
this._updateVideoUI();
},
// 6.5 & 6.6 - 更新视频标签页UI
_updateVideoUI() {
const doc = UIPanel._doc;
if (!doc) return;
const chapterEl = doc.getElementById('cx-video-chapter');
const progressEl = doc.getElementById('cx-video-progress');
const progressBar = doc.getElementById('cx-video-progress-bar');
const startBtn = doc.getElementById('cx-btn-video-start');
const stopBtn = doc.getElementById('cx-btn-video-stop');
if (chapterEl) chapterEl.textContent = this._currentChapter || '未开始';
if (progressEl) progressEl.textContent = `${this._progress}%`;
if (progressBar) progressBar.style.width = `${this._progress}%`;
if (startBtn) startBtn.disabled = this._playing;
if (stopBtn) stopBtn.disabled = !this._playing;
},
// 绑定视频模块事件
bindEvents() {
const doc = UIPanel._doc;
if (!doc) return;
// 开始播放
doc.getElementById('cx-btn-video-start')?.addEventListener('click', async () => {
const btn = doc.getElementById('cx-btn-video-start');
if (btn) btn.disabled = true;
const allowed = await UIPanel.confirmStudyPurpose();
if (btn) btn.disabled = false;
if (!allowed) {
Logger.log('已取消启动:本功能只能用于课程复习和学习回看', 'info');
return;
}
this.start();
});
// 停止播放
doc.getElementById('cx-btn-video-stop')?.addEventListener('click', () => {
this._userPaused = true;
this.stop();
});
}
};
// ==========================================
// FontDecryptor - font-cxsecret 字体解密模块
// ==========================================
const FontDecryptor = {
_table: null, // MD5 → Unicode 映射表
_cache: new Map(), // fontUrl → charMap,最多保留 8 套成功映射
_mapFonts: new WeakMap(), // 字符映射所属字体及实际字形覆盖范围
_missingWarnings: new WeakMap(),
_fontPending: new Map(),
_maxFontBytes: 8 * 1024 * 1024,
_loading: null, // 当前加载 Promise
_canContinue(canContinue) {
try { return typeof canContinue !== 'function' || !!canContinue(); }
catch (_) { return false; }
},
// 本站字典:按正式资源版本隔离缓存,失败后允许下次重试。
async _ensureTable() {
if (this._table) return;
if (!this._loading) this._loading = __scriptFontV1.loadTable('chaoxing-table', 'fontTable');
const pending = this._loading;
try { this._table = await pending; }
catch (error) { Logger.log('字体映射表加载失败: ' + error.message, 'error'); }
finally { if (this._loading === pending) this._loading = null; }
},
// 从页面样式表中查找 font-cxsecret 的 woff 字体 URL
_findFontUrl(doc) {
// @font-face 不跨文档继承;只使用当前题所在文档的字体,不能猜其它 iframe。
const docsToSearch = [doc || document];
for (const searchDoc of docsToSearch) {
try {
const baseUrl = searchDoc.baseURI || searchDoc.location?.href || location.href;
for (const sheet of searchDoc.styleSheets) {
try {
const rules = [...(sheet.cssRules || [])];
while (rules.length) {
const rule = rules.shift();
if (rule.type === 5 || /^\s*@font-face\b/i.test(rule.cssText || '')) {
const text = rule.cssText || '';
if (/font-cxsecret|cxsecret/i.test(text)) {
const m = text.match(/url\s*\(\s*['"]?([^'")\s]+?)['"]?\s*\)/i);
if (m) {
const url = new URL(m[1], sheet.href || baseUrl).href;
Logger.log('找到字体URL: ' + url.substring(0, 80), 'info');
return url;
}
}
} else if (rule.cssRules) {
rules.push(...rule.cssRules);
}
}
} catch (e) { /* 跨域样式表忽略 */ }
}
} catch (_) {}
}
return null;
},
// 下载字体文件并解析(支持 data: URI 和 http URL)
async _fetchFont(url) {
if (typeof url !== 'string' || !url) throw new Error('字体地址无效');
// data: URI 直接解码
if (url.startsWith('data:')) {
const base64Match = url.match(/base64,([\w\W]+?)$/);
if (base64Match) {
if (base64Match[1].length > Math.ceil(this._maxFontBytes / 3) * 4 + 1024) throw new Error('字体文件超过 8 MB');
const data = atob(base64Match[1]);
if (!data.length || data.length > this._maxFontBytes) throw new Error('字体文件为空或超过 8 MB');
const buffer = new Uint8Array(data.length);
for (let i = 0; i < data.length; i++) {
buffer[i] = data.charCodeAt(i);
}
return buffer.buffer;
}
throw new Error('无法解析 data URI');
}
const parsed = new URL(url);
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) throw new Error('字体地址仅支持 HTTP/HTTPS');
const group = CXRequests.taskGroup();
// 不合并不同任务组,避免停止答题时一并中断视频任务所需的字体。
const key = group + '|' + parsed.href;
if (this._fontPending.has(key)) return this._fontPending.get(key);
const pending = new Promise((resolve, reject) => {
let settled = false, request = null, shouldAbort = false;
const finish = (error, value) => {
if (settled) return;
settled = true;
error ? reject(error) : resolve(value);
};
const abortTooLarge = () => {
finish(new Error('字体文件超过 8 MB'));
shouldAbort = true;
try { request?.abort(); } catch (_) {}
};
try {
request = CXRequests.request({
method: 'GET', url: parsed.href, responseType: 'arraybuffer', timeout: 15000,
onprogress: event => {
if (Number(event.loaded) > this._maxFontBytes || Number(event.total) > this._maxFontBytes) abortTooLarge();
},
onload: resp => {
if (settled) return;
if (Number(resp.status) !== 200) return finish(new Error('字体下载失败: HTTP ' + resp.status));
const buffer = resp.response;
if (Object.prototype.toString.call(buffer) !== '[object ArrayBuffer]' || !buffer.byteLength) return finish(new Error('字体下载内容无效'));
if (buffer.byteLength > this._maxFontBytes) return abortTooLarge();
finish(null, buffer);
},
onerror: () => finish(new Error('字体下载网络错误')),
ontimeout: () => finish(new Error('字体下载超时')),
onabort: () => finish(new Error('字体下载已取消'))
}, group);
if (shouldAbort) request?.abort();
} catch (error) { finish(error); }
});
this._fontPending.set(key, pending);
try { return await pending; }
finally { if (this._fontPending.get(key) === pending) this._fontPending.delete(key); }
},
// 将 glyph 路径数据序列化为字符串用于 MD5(与 Table.json 生成方式一致)
_glyphPathHash(font, glyphIndex) {
if (typeof Typr === 'undefined' || !Typr.U) return null;
const path = Typr.U.glyphToPath(font, glyphIndex);
if (!path || !path.cmds || path.cmds.length === 0) return null;
// 使用 JSON.stringify + MD5 后8位(与参考脚本和 Table.json 一致)
return CryptoJS.MD5(JSON.stringify(path)).toString().slice(24);
},
// 构建字符映射: fakeCharCode → realChar
async buildCharMap(doc, canContinue = () => true) {
if (!this._canContinue(canContinue)) return null;
await this._ensureTable();
if (!this._canContinue(canContinue) || !this._table || Object.keys(this._table).length === 0) return null;
const fontUrl = this._findFontUrl(doc);
if (!fontUrl) {
Logger.log('未找到 font-cxsecret 字体 URL', 'warn');
return null;
}
// 缓存字体解析结果;新题出现的码点仍按该字体实际 cmap 按需解析。
if (this._cache.has(fontUrl)) {
const cached = this._cache.get(fontUrl);
this._cache.delete(fontUrl);
this._cache.set(fontUrl, cached);
return cached;
}
// 只合并二进制下载,各识别保留自己的取消状态。
const pending = (async () => {
try {
Logger.log('正在下载并解析 font-cxsecret 字体...', 'info');
const buffer = await this._fetchFont(fontUrl);
if (!this._canContinue(canContinue)) return null;
if (typeof Typr === 'undefined') {
Logger.log('Typr.js 未加载,无法解析字体', 'error');
return null;
}
const fonts = Typr.parse(buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer);
const font = fonts[0];
if (!font) {
Logger.log('字体解析失败', 'error');
return null;
}
const charMap = Object.create(null);
// Typr 会把 TTF 中空轮廓的 cmap 字形归零;覆盖检查须保留原 cmap 结果。
const cmapFont = Object.assign({}, font, { 'CFF ': {} });
this._mapFonts.set(charMap, { font, cmapFont, states: new Map(), glyphs: new Map() });
// 只检查页面实际使用的字符,兼容扩展汉字、私用区和补充平面。
for (const element of this._secretElements(doc)) {
for (const char of element.textContent || '') this._resolveChar(char, charMap);
}
if (!this._canContinue(canContinue)) return null;
Logger.log('字体解析完成,已匹配 ' + Object.keys(charMap).length + ' 个页面字符', 'info');
this._cache.set(fontUrl, charMap);
while (this._cache.size > 8) this._cache.delete(this._cache.keys().next().value);
return charMap;
} catch (e) {
if (this._canContinue(canContinue)) Logger.log('字体解密失败: ' + (e.message || e), 'error');
return null;
}
})();
return await pending;
},
_needsFontMapping(char) {
return /[\p{Unified_Ideograph}\uF900-\uFAFF\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u.test(char);
},
_resolveChar(char, charMap) {
const code = char.codePointAt(0);
if (Object.prototype.hasOwnProperty.call(charMap, code)) return charMap[code];
const metadata = this._mapFonts.get(charMap);
// 旧调用方传入普通映射时,继续严格保护未识别汉字。
if (!metadata) return this._needsFontMapping(char) ? null : char;
if (metadata.states.has(code)) return metadata.states.get(code);
let result = null;
try {
const glyph = Typr.U.codeToGlyph(metadata.cmapFont, code);
if (!glyph) {
// cmap 未包含的普通文字由浏览器备用字体显示,不是缺失的混淆映射。
// 私用区没有通用文字语义,仍交给 OCR。
result = /[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u.test(char) ? null : char;
} else {
if (!metadata.glyphs.has(glyph)) metadata.glyphs.set(glyph, this._glyphPathHash(metadata.font, glyph));
const hash = metadata.glyphs.get(glyph);
const realCode = hash && this._table[hash];
if (Number.isInteger(realCode) && realCode >= 0 && realCode <= 0x10ffff && !(realCode >= 0xd800 && realCode <= 0xdfff)) {
result = charMap[code] = String.fromCodePoint(realCode);
} else if (!this._needsFontMapping(char)) result = char;
}
} catch (_) { /* 字形解析失败保持未识别状态,不提交乱码。 */ }
metadata.states.set(code, result);
return result;
},
// 解密文本:将 DOM 元素中的混淆文字还原
decryptText(text, charMap) {
if (!charMap || !text) return text;
let result = '';
for (const ch of text) {
const code = ch.codePointAt(0);
result += charMap[code] || ch;
}
return result;
},
// 只在该元素实际使用的混淆字形都匹配时原子替换文本。
// 不改 innerHTML,避免破坏标签、连续替换或把未识别乱码当作正常题目。
_decodeSecretElement(element, charMap, canContinue = () => true) {
if (!this._canContinue(canContinue)) return false;
const doc = element.ownerDocument || document;
const walker = doc.createTreeWalker(element, 4);
const changes = [];
const missing = new Set();
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const parent = node.parentElement;
if (parent?.closest('script, style, textarea, noscript')) continue;
// 子元素明确改用了其它字体时,不对其正常文字作混淆还原。
const family = doc.defaultView?.getComputedStyle(parent)?.fontFamily || '';
if (family && !/cxsecret/i.test(family)) continue;
const text = node.nodeValue || '';
let decoded = '';
for (const char of text) {
const real = this._resolveChar(char, charMap);
if (real === null) missing.add(char.codePointAt(0));
else decoded += real;
}
changes.push([node, decoded]);
}
if (missing.size) {
const signature = [...missing].sort((a, b) => a - b).map(code => 'U+' + code.toString(16).toUpperCase()).join(',');
const previous = this._missingWarnings.get(element);
if (previous?.map !== charMap || previous.signature !== signature) {
Logger.log('字体仍有 ' + missing.size + ' 个未匹配字形(' + signature.slice(0, 90) + '),保留原字体并回退 OCR', 'warn');
this._missingWarnings.set(element, { map: charMap, signature });
}
return false;
}
if (!this._canContinue(canContinue)) return false;
for (const [node, text] of changes) node.nodeValue = text;
for (const child of element.querySelectorAll('.font-cxsecret')) child.classList.remove('font-cxsecret');
element.classList.remove('font-cxsecret');
return true;
},
_secretElements(root) {
const elements = [...root.querySelectorAll('.font-cxsecret')];
if (root.matches?.('.font-cxsecret')) elements.unshift(root);
return elements.filter(element => !elements.some(parent => parent !== element && parent.contains(element)));
},
async decryptElement(element, doc, canContinue = () => true) {
if (!element || !this._canContinue(canContinue)) return '';
const charMap = await this.buildCharMap(doc, canContinue);
if (!this._canContinue(canContinue) || !charMap) return '';
const secretElements = this._secretElements(element);
for (const secret of secretElements) if (!this._decodeSecretElement(secret, charMap, canContinue)) return '';
return element.textContent || '';
},
async decryptDocument(doc, canContinue = () => true) {
if (!doc || !this._canContinue(canContinue)) return;
const charMap = await this.buildCharMap(doc, canContinue);
if (!this._canContinue(canContinue) || !charMap) return;
for (const element of this._secretElements(doc)) this._decodeSecretElement(element, charMap, canContinue);
}
};
// ==========================================
// Solver - 答案求解器模块(题目识别与答案匹配)
// ==========================================
const Solver = {
// 题目类型常量
TYPE_SINGLE: 0, // 单选
TYPE_MULTI: 1, // 多选
TYPE_FILL: 2, // 填空
TYPE_JUDGE: 3, // 判断
TYPE_OTHER: 4, // 其他
// ---- 8.1 readFromDOM ----
readFromDOM(element) {
const result = { question: '', options: [], type: this.TYPE_OTHER, images: [] };
if (!element) return result;
result.type = this._detectType(element);
result.question = this._extractQuestion(element);
result.options = this._extractOptions(element);
result.images = this._extractQuestionImages(element);
// 图片题和图片选项不一定有 textContent,不能因此被上层按空题跳过。
// 混淆字体仍先走解密,避免用图片占位提前掩盖尚未识别的题干。
if (!result.question && result.images.length && !element.querySelector('.font-cxsecret')) {
result.question = '[题目配图] 请根据题图及选项作答。';
}
return result;
},
_isQuestionImage(image) {
if (!image || image.tagName !== 'IMG') return false;
// 只采集当前题内的内容图片,排除头像、按钮、工具栏和已显示的解析。
if (image.closest('button, [role="button"], script, style, .avatar, .user-avatar, .userAvatar, .headImg, .head-img, .logo, .icon, .layui-icon, .toolbar, .toolbar-container, .mark_answer, .Py_answer, .answer-analysis, .analysis')) return false;
if (image.closest('[hidden], [aria-hidden="true"]')) return false;
for (let node = image; node && node.nodeType === 1; node = node.parentElement) {
if (/(?:display\s*:\s*none|visibility\s*:\s*hidden)/i.test(node.getAttribute('style') || '')) return false;
}
const width = Number(image.getAttribute('width'));
const height = Number(image.getAttribute('height'));
if (width > 0 && height > 0 && width <= 3 && height <= 3) return false;
return true;
},
_questionImageURL(image) {
if (!image) return '';
const lazyAttributes = ['data-src', 'data-original', 'data-lazy-src', 'data-actualsrc', 'data-url', 'original'];
const candidates = lazyAttributes.map(name => image.getAttribute(name));
candidates.push(image.currentSrc, image.getAttribute('src'));
const srcset = image.getAttribute('data-srcset') || image.getAttribute('srcset');
if (srcset && !/^\s*data:/i.test(srcset)) candidates.push(srcset.split(',')[0].trim().split(/\s+/)[0]);
for (const candidate of candidates) {
const raw = String(candidate || '').trim();
if (!raw || /^(?:javascript:|about:|#)/i.test(raw)) continue;
// 透明占位图不是题目。保留空地址的 descriptor,由 AI 核心提示等待图片就绪。
if (/^data:image\/gif;base64,R0lGODlhAQABA/i.test(raw)) continue;
try {
const resolved = new URL(raw, image.ownerDocument?.baseURI || location.href);
if (/^(?:https?:|blob:)$/.test(resolved.protocol) || /^data:image\//i.test(raw)) return resolved.href;
} catch (_) {}
}
return '';
},
_questionTextWithImages(node) {
if (!node) return '';
if (!node.querySelector('img')) return node.innerText || node.textContent || '';
const content = node.cloneNode(true);
content.querySelectorAll('img').forEach(image => {
const alt = String(image.getAttribute('alt') || image.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 160);
image.replaceWith(this._isQuestionImage(image) ? ` [配图${alt ? ':' + alt : ''}] ` : '');
});
return content.textContent || '';
},
_extractQuestionImages(element) {
// 不允许扫描整个文档或播放器页面,只处理已经定位到的本题/弹题容器。
if (!element || element.nodeType === 9 || !element.querySelectorAll) return [];
const pairs = this._extractOptionPairs(element);
const images = [];
const seen = new Set();
for (const image of element.querySelectorAll('img')) {
if (!this._isQuestionImage(image)) continue;
const optionIndex = pairs.findIndex(pair => pair.element?.contains(image));
const role = optionIndex >= 0 ? 'option' : 'question';
const url = this._questionImageURL(image);
// 同一图片出现在不同选项时必须保留关联,不能仅按 URL 全局去重。
const key = `${role}:${optionIndex}:${url || 'unresolved-' + images.length}`;
if (seen.has(key)) continue;
seen.add(key);
const descriptor = { url, alt: String(image.getAttribute('alt') || image.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 160), role, sourceIndex: images.length };
if (optionIndex >= 0) descriptor.optionIndex = optionIndex;
images.push(descriptor);
}
return images;
},
_isVideoQuizElement(element) {
return !!element?.closest?.('.ans-videoquiz, .videoquiz, .video-quiz, .mvp-question, .topicWrap, [id^="videoquiz"]');
},
_extractVideoQuizQuestion(element) {
if (!this._isVideoQuizElement(element)) return '';
// 播放器题干是普通 div/span,不一定具有作业页的 mark_name/h3。
// 在弹题范围内去掉选项和操作按钮后读取文字,不能把整幅视频截图送入 OCR。
if (element.querySelector('.font-cxsecret')) return '';
const content = element.cloneNode(true);
content.querySelectorAll(
'.ans-videoquiz-opt, label, input, textarea, button, [role="button"], ' +
'#videoquiz-submit, [id^="videoquiz-close"], .ans-videoquiz-close, .close_btn, ' +
'.submit_btn, .btn, script, style, video, audio'
).forEach(node => node.remove());
return this._cleanQuestionText(this._questionTextWithImages(content));
},
// xuexitong 特化:沿 DOM 查找「最近」的 .mark_name(题目标题容器)
// 标题 textContent 形如「41. (多选题, 2.0 分) 从人文的角度来看...」
// 查找顺序:容器内 → 前兄弟 → 父级前兄弟 → 整 DOM 前置最近
_findNearestMarkName(el) {
if (!el) return null;
// 0) el 自身就是 .mark_name(当容器选择器恰好返回 h3.mark_name 时)
if (el.classList && el.classList.contains('mark_name')) return el;
// 1) 容器内部
try {
const inner = el.querySelector('.mark_name');
if (inner) return inner;
} catch (_) {}
// 2) 前兄弟(沿父链回溯 6 层)
let cur = el;
for (let depth = 0; depth < 6 && cur; depth++) {
let sib = cur.previousElementSibling;
while (sib) {
if (sib.classList && sib.classList.contains('mark_name')) return sib;
try {
const all = sib.querySelectorAll && sib.querySelectorAll('.mark_name');
if (all && all.length > 0) return all[all.length - 1]; // 兄弟内最后一个(最接近 el)
} catch (_) {}
sib = sib.previousElementSibling;
}
cur = cur.parentElement;
}
// 3) 整文档前置兜底:取 DOM 顺序上所有前置 .mark_name 的最后一个
try {
const doc = el.ownerDocument || document;
const all = doc.querySelectorAll('.mark_name');
let nearest = null;
const POS_PRECEDING = 2; // Node.DOCUMENT_POSITION_PRECEDING
for (const mn of all) {
if (el.compareDocumentPosition(mn) & POS_PRECEDING) nearest = mn;
else break; // NodeList 已按 DOM 顺序,一旦遇到非前置即可停止
}
if (nearest) return nearest;
} catch (_) {}
return null;
},
// 从 mark_name 元素中抽取可能的题型标识字符串(含自身 textContent + 所有子 aria-label)
_extractMarkNameTypeText(mn) {
if (!mn) return '';
let t = mn.textContent || '';
try {
mn.querySelectorAll('[aria-label]').forEach(s => {
const a = s.getAttribute('aria-label');
if (a) t += ' ' + a;
});
} catch (_) {}
return t;
},
// xuexitong 特化:查找最近的 .type_tit(section 标题,如 h2.type_tit「二、 多选题」)
// 整卷预览模式下 type_tit 在容器内部;列表模式下在父级的前兄弟中
_findNearestTypeTit(el) {
if (!el) return null;
// 1) 容器内部
try {
const inner = el.querySelector('.type_tit, h2.type_tit');
if (inner) return inner;
} catch (_) {}
// 2) 前兄弟(含父级)
let cur = el;
for (let depth = 0; depth < 6 && cur; depth++) {
let sib = cur.previousElementSibling;
while (sib) {
if (sib.classList && sib.classList.contains('type_tit')) return sib;
try {
const found = sib.querySelector && sib.querySelector('.type_tit');
if (found) return found;
} catch (_) {}
sib = sib.previousElementSibling;
}
cur = cur.parentElement;
}
return null;
},
_detectType(el) {
const cls = el.className || '';
// 播放器内的题型以题窗自身为准,不能沿父页面借用作业标题的题型。
if (this._isVideoQuizElement(el)) {
const popupText = (el.textContent || '').trim();
if (/^(?:【|\[)?\s*(?:判断|是非)/.test(popupText)) return this.TYPE_JUDGE;
if (/^(?:【|\[)?\s*(?:多选|多项选择|不定项)/.test(popupText)) return this.TYPE_MULTI;
if (/^(?:【|\[)?\s*(?:单选|单项选择)/.test(popupText)) return this.TYPE_SINGLE;
if (/^(?:【|\[)?\s*填空/.test(popupText)) return this.TYPE_FILL;
}
// [P1] 输入框类型:最可靠信号(每道题自己的 input 决定题型),checkbox 纯存在 → MULTI
const checkboxes = el.querySelectorAll('input[type="checkbox"]');
const radios = el.querySelectorAll('input[type="radio"]');
if (checkboxes.length > 0 && radios.length === 0) return this.TYPE_MULTI;
// [P2 ⭐ 最高优先] 查找 .mark_name(题目标题)+ .type_tit(section 标题)
// xuexitong 实测: 所有题型的容器 class 都带 singleQuesId,不可靠!
// 但 h3.mark_name 的 text/aria-label 有「(多选题, 2.0 分)」
// h2.type_tit 有「二、 多选题 (共 15题,30.0 分)」
// 这两个才是可靠来源 → 提到最前
const nearestMark = this._findNearestMarkName(el);
if (nearestMark) {
const mt = this._extractMarkNameTypeText(nearestMark);
if (/多选|多项选择|不定项/.test(mt)) return this.TYPE_MULTI;
if (/判断|是非/.test(mt)) return this.TYPE_JUDGE;
if (/填空/.test(mt)) return this.TYPE_FILL;
if (/单选|单项选择/.test(mt)) return this.TYPE_SINGLE;
}
// [P2b] 查找 .type_tit section 标题(整卷预览=容器内,列表模式=父级子元素)
const typeTit = this._findNearestTypeTit(el);
if (typeTit) {
const tt = typeTit.textContent || '';
if (/多选|多项选择|不定项/.test(tt)) return this.TYPE_MULTI;
if (/判断|是非/.test(tt)) return this.TYPE_JUDGE;
if (/填空/.test(tt)) return this.TYPE_FILL;
if (/单选|单项选择/.test(tt)) return this.TYPE_SINGLE;
}
// [P3] 容器 class 标注(⚠ 去掉 singleQuesId —— xuexitong 所有题型都有此 class)
if (/multipleQuesId/i.test(cls)) return this.TYPE_MULTI;
if (/judgementQuesId|judge|panduan/i.test(cls)) return this.TYPE_JUDGE;
if (/completionQuesId|fill|tiankong/i.test(cls)) return this.TYPE_FILL;
// 注意:不再检测 singleQuesId / single
// [P4] 提取「题目自身」的题型标签(仅限题目标题元素)
const titleSelectors = ['.mark_name', '.Zy_TItle', '.questionType', '.question_title', '.topic-txt', '.stem', '.question-title', '.quesTitle', '.type_tit'];
let titleText = '';
for (const sel of titleSelectors) {
const n = el.querySelector(sel);
if (n) titleText += ' ' + (n.textContent || '');
}
if (titleText) {
if (/多选|多项选择|不定项/.test(titleText)) return this.TYPE_MULTI;
if (/判断|是非/.test(titleText)) return this.TYPE_JUDGE;
if (/填空/.test(titleText)) return this.TYPE_FILL;
if (/单选|单项选择/.test(titleText)) return this.TYPE_SINGLE;
}
// [P5] 前面最近的 section 标题(支持 h2/h3;兼容旧版 .newTestType 和 .type_tit)
const checkSectionHeader = (start) => {
let p = start;
let depth = 0;
while (p && depth < 50) {
const tag = p.tagName;
const isSectionHead = (tag === 'H2' || tag === 'H3' || tag === 'H4')
|| (p.classList && (p.classList.contains('newTestType') || p.classList.contains('type_tit')));
if (isSectionHead) {
const hText = p.textContent || '';
if (/多选|多项选择|不定项/.test(hText)) return this.TYPE_MULTI;
if (/判断|是非/.test(hText)) return this.TYPE_JUDGE;
if (/填空/.test(hText)) return this.TYPE_FILL;
if (/单选|单项选择/.test(hText)) return this.TYPE_SINGLE;
break;
}
p = p.previousElementSibling;
depth++;
}
return null;
};
const headerType = checkSectionHeader(el.previousElementSibling) || (el.parentElement && checkSectionHeader(el.parentElement.previousElementSibling));
if (headerType !== null) return headerType;
// [P5] 整体 textContent 计数比较(取前 300 字避免干扰;多选优先)
const fullText = (el.textContent || '').slice(0, 300);
const multiN = (fullText.match(/多选|多项选择|不定项/g) || []).length;
const singleN = (fullText.match(/单选|单项选择/g) || []).length;
if (multiN > 0 && multiN >= singleN) return this.TYPE_MULTI;
if (singleN > 0) return this.TYPE_SINGLE;
if (/判断|是非/.test(fullText)) return this.TYPE_JUDGE;
if (/填空/.test(fullText)) return this.TYPE_FILL;
// [P6] 最终 fallback:按 input 推断
if (radios.length > 0) {
const opts = this._extractOptions(el);
if (radios.length === 2 && opts.length === 2) {
const joined = opts.join('');
if (/[对错√×✓✗TF]/.test(joined) || /正确|错误|true|false/i.test(joined)) {
return this.TYPE_JUDGE;
}
}
// 如果既有 radio 又有 checkbox(罕见自定义),按 checkbox 优先
if (checkboxes.length > 0) return this.TYPE_MULTI;
return this.TYPE_SINGLE;
}
if (checkboxes.length > 0) return this.TYPE_MULTI;
const textInputs = el.querySelectorAll('input[type="text"], textarea');
if (textInputs.length > 0) return this.TYPE_FILL;
// 诊断:所有策略都没识别出来 —— 记录一次性日志帮助排查
try {
const preview = (el.textContent || '').replace(/\s+/g, ' ').slice(0, 60);
if (typeof Logger !== 'undefined' && Logger && Logger.log) {
Logger.log(`⚠ 题型识别失败,容器预览: ${preview}...(将按 OTHER 处理)`, 'info');
}
} catch (_) {}
return this.TYPE_OTHER;
},
_extractQuestion(el) {
if (this._isVideoQuizElement(el)) return this._extractVideoQuizQuestion(el);
// 优先从 .mark_name 或 .Zy_TItle 提取
const selectors = [
'h3 .clearfix', 'h3 div', '.Cy_TItle .clearfix', '.Zy_TItle .clearfix',
'.topic-txt', '.mark_name', '.Zy_TItle', '.questionContent',
'.question_title', '.stem', 'h3'
];
for (const sel of selectors) {
const node = el.querySelector(sel);
if (node) {
// 检测 font-cxsecret 字体混淆
if (node.classList?.contains('font-cxsecret') || node.querySelector('.font-cxsecret')) {
// 字体混淆:尝试从 aria-label 获取真实文字
const ariaLabel = node.getAttribute('aria-label');
if (ariaLabel) return this._cleanQuestionText(ariaLabel);
// 备选:用 innerText 可能经过浏览器渲染后是正确的(部分情况)
// 标记需要 OCR
return '';
}
const text = this._questionTextWithImages(node).trim();
if (text) return this._cleanQuestionText(text);
}
}
// 备选:取容器内第一段有意义的文本
const firstP = el.querySelector('p, h3, h4, .title');
if (firstP) {
// 同样检测字体混淆
if (firstP.classList?.contains('font-cxsecret') || firstP.closest?.('.font-cxsecret')) {
const ariaLabel = firstP.getAttribute('aria-label');
if (ariaLabel) return this._cleanQuestionText(ariaLabel);
return '';
}
const text = this._questionTextWithImages(firstP).trim();
if (text) return this._cleanQuestionText(text);
}
return '';
},
_cleanQuestionText(text) {
let s = String(text || '');
// 解码 HTML 实体(双重编码 " → " → ",循环最多 3 次)
for (let i = 0; i < 3; i++) {
if (!/&(quot|apos|lt|gt|amp|nbsp|#\d+|#x[0-9a-f]+);/i.test(s)) break;
const prev = s;
s = s.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ /g, ' ')
.replace(/&/g, '&');
if (s === prev) break;
}
// 移除题号前缀(如 "1." "【单选题】" 等)
return s.replace(/\s+/g, ' ')
.replace(/^[\s\d]+[.、.)]\s*/, '')
.replace(/^[((]\s*\d+\s*[))]\s*/, '')
.replace(/^【?\s*(单选题|多选题|判断题|填空题|单项选择题|多项选择题|不定项选择题)\s*】?\s*/, '')
.replace(/^(单选题|多选题|判断题|填空题|单项选择题|多项选择题)[】\]))]\s*/, '')
// 去掉题目中/末尾的分值角标,如 "(5分)"/"(10.0分)"
.replace(/[((]\s*\d+(\.\d+)?\s*分\s*[))]/g, '')
.trim();
},
// 提取选项对(text + element + input)—— text 与 element 严格对齐,避免 input 索引错位
// 学习通常见问题:DOM 中可能存在隐藏 radio / 多余 radio,导致 inputs[1] 不一定对应视觉上的 B
// 通过此方法返回的 pairs 保证 pairs[idx].text === pageOptions[idx],并提供对应的 element/input 用于点击
_extractOptionPairs(el) {
if (!el) return [];
const hasFontSecret = el.querySelector('.font-cxsecret') !== null;
const pickText = (node, input) => {
if (!node && !input) return '';
// 字体混淆时优先 aria-label
if (hasFontSecret) {
const aria = (node && node.getAttribute('aria-label')) || (input && input.getAttribute('aria-label'));
if (aria) return this._cleanOptionText(aria.trim());
}
const raw = (node ? this._questionTextWithImages(node) : '').trim();
return this._cleanOptionText(raw);
};
const seen = new Set();
const out = [];
const pushPair = (text, element, input) => {
if (!text) return;
// 文本 .answer_p/.after 与蓝色选中标记往往是兄弟节点。
// 将操作和状态检查统一到本题内的同一选项行,不能向上读到整道题。
const row = element?.closest?.('.answerBg, li, .option_li, label, .option');
if (row && row !== el && el.contains(row)) element = row;
if (seen.has(element)) return;
seen.add(element);
out.push({ text, element, input });
};
// 视频中途弹题的 label 可能通过 for 指向同级的 input,优先按可见标签
// 建立对应关系,避免把整个 ans-videoquiz-opt 当成一个选项。
if (this._isVideoQuizElement(el)) {
for (const label of el.querySelectorAll('.ans-videoquiz-opt label')) {
let input = label.querySelector('input[type="radio"], input[type="checkbox"]');
if (!input && label.htmlFor) {
const related = (el.ownerDocument || document).getElementById(label.htmlFor);
if (related && el.contains(related) && related.matches('input[type="radio"], input[type="checkbox"]')) input = related;
}
pushPair(pickText(label, input), label, input);
}
if (out.length) return out;
}
// 策略 1:从 radio/checkbox 出发,找最近的可点击祖先容器
const inputs = el.querySelectorAll('input[type="radio"], input[type="checkbox"]');
if (inputs && inputs.length > 0) {
for (const input of inputs) {
const ancestor = input.closest('label, li, .answerBg, .option, .clearfix, .option_li, .answer_p, .textDIV, .eidtDiv, .topic-option-list li, .Zy_ulTop li');
const element = ancestor || input.parentElement || input;
const text = pickText(element, input);
pushPair(text, element, input);
}
if (out.length > 0) return out;
}
// 策略 2:纯文本选项容器(没有 input 的情况,例如 CSS 模拟单选)
const liItems = el.querySelectorAll(
'.stem_answer .answerBg .answer_p, .Cy_ulTop .clearfix, .Zy_ulTop li .after, ' +
'ul li .after, .topic-option-list li, .Zy_ulTop li, .answerBg li, .option_li, .answer_p, .textDIV, .eidtDiv'
);
for (const li of liItems) {
const text = pickText(li, null);
pushPair(text, li, null);
}
if (out.length > 0) return out;
// 策略 3:label 容器
const labels = el.querySelectorAll('label.fl, label.option, .answerBg label');
for (const label of labels) {
const input = label.querySelector('input[type="radio"], input[type="checkbox"]');
const text = pickText(label, input);
pushPair(text, label, input);
}
if (out.length > 0) return out;
// 策略 4:含输入的容器
const inputContainers = el.querySelectorAll('.Zy_ulBottom li, .answerList li, div.option');
for (const c of inputContainers) {
const input = c.querySelector('input[type="radio"], input[type="checkbox"]');
const text = pickText(c, input);
pushPair(text, c, input);
}
return out;
},
_extractOptions(el) {
// 复用 _extractOptionPairs 保证与 _selectOptions 的索引完全对齐
const pairs = this._extractOptionPairs(el);
if (pairs.length > 0) return pairs.map(p => p.text);
// 极端兜底:保留原始多策略实现,避免回归
const options = [];
const hasFontSecret = el.querySelector('.font-cxsecret') !== null;
// 优先从 .Zy_ulTop li 提取
const liItems = el.querySelectorAll(
'.stem_answer .answerBg .answer_p, .Cy_ulTop .clearfix, .Zy_ulTop li .after, ' +
'ul li .after, .topic-option-list li, .Zy_ulTop li, .answerBg li, .option_li, .answer_p, .textDIV, .eidtDiv'
);
if (liItems.length > 0) {
liItems.forEach(li => {
if (hasFontSecret) {
// 字体混淆:优先用 aria-label
const ariaLabel = li.getAttribute('aria-label');
if (ariaLabel) {
options.push(this._cleanOptionText(ariaLabel));
return;
}
}
const text = this._cleanOptionText(li.textContent.trim());
if (text) options.push(text);
});
if (options.length > 0) return [...new Set(options)];
}
// 备选:从 label 元素提取
const labels = el.querySelectorAll('label.fl, label.option, .answerBg label');
if (labels.length > 0) {
labels.forEach(label => {
if (hasFontSecret) {
const ariaLabel = label.getAttribute('aria-label');
if (ariaLabel) {
options.push(this._cleanOptionText(ariaLabel));
return;
}
}
const text = this._cleanOptionText(label.textContent.trim());
if (text) options.push(text);
});
if (options.length > 0) return [...new Set(options)];
}
// 再备选:从包含 radio/checkbox 的容器提取
const inputContainers = el.querySelectorAll('.Zy_ulBottom li, .answerList li, div.option');
inputContainers.forEach(container => {
if (hasFontSecret) {
const ariaLabel = container.getAttribute('aria-label');
if (ariaLabel) {
options.push(this._cleanOptionText(ariaLabel));
return;
}
}
const text = this._cleanOptionText(container.textContent.trim());
if (text) options.push(text);
});
return [...new Set(options)];
},
_cleanOptionText(text) {
// 移除选项前缀(如 "A." "A、" "A " 等)
return text.replace(/^[A-Za-z][.、::\s]\s*/, '').trim();
},
// ---- 8.2 recognizeByOCR ----
async recognizeByOCR(element, context = {}) {
const result = { question: '', options: [], type: this.TYPE_OTHER, images: [] };
if (!element) return result;
const domResult = this.readFromDOM(element);
result.options = domResult.options.slice();
result.images = domResult.images;
result.type = domResult.type;
// 与 DOM 提取复用同一题目图片范围,不能将第一张选项图误作题干。
const images = result.images;
if (images.length === 0) return result;
try {
const questionTexts = [];
const optionTexts = new Map();
for (const image of images) {
if (!image.url) continue;
const text = String(await this._recognizeOCR(image.url, context) || '').trim();
if (!text) continue;
if (image.role === 'option') {
const prior = optionTexts.get(image.optionIndex) || [];
prior.push(text);
optionTexts.set(image.optionIndex, prior);
} else {
questionTexts.push(text);
}
}
result.question = questionTexts.join(' ').trim();
for (const [index, texts] of optionTexts) {
// 保持 DOM 选项的顺序和图片标记,附加 OCR 文字有助于文字题库匹配。
result.options[index] = [result.options[index] || '[配图]', texts.join(' ')].join(' ').trim();
}
} catch (e) {
if (e.name === 'AbortError' || e.name === 'TimeoutError') throw e;
Logger.log('OCR 识别失败: ' + (e.message || e), 'error');
}
if (!result.question && images.length) result.question = domResult.question || '[题目配图] 请根据题图及选项作答。';
return result;
},
_waitForRecognition(promise, label, context = {}, limit = 20000) {
// OCR 语言包/Worker 在网络异常时可能永不返回。等待必须可超时、可停止。
return new Promise((resolve, reject) => {
let timer = null;
let poll = null;
let settled = false;
const finish = (fn, value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
clearInterval(poll);
fn(value);
};
const error = (name, message) => Object.assign(new Error(message), { name });
const active = () => !context.canContinue || context.canContinue();
const remaining = context.deadline == null ? limit : Math.min(limit, context.deadline - Date.now());
Promise.resolve(promise).then(value => {
if (!active()) finish(reject, error('AbortError', '题目识别已取消'));
else finish(resolve, value);
}, reason => finish(reject, reason));
if (!active()) {
finish(reject, error('AbortError', '题目识别已取消'));
return;
}
timer = setTimeout(() => finish(reject, error('TimeoutError', `${label}超时,请检查网络或手动作答`)), Math.max(0, remaining));
if (context.canContinue) poll = setInterval(() => {
if (!active()) finish(reject, error('AbortError', '题目识别已取消'));
}, 100);
});
},
async _recognizeOCR(source, context = {}) {
if (typeof Tesseract === 'undefined') return '';
let worker = null;
let finished = false;
let fatalError;
const fatal = new Promise((_, reject) => { fatalError = reject; });
const terminate = instance => {
if (!instance?.terminate) return;
try { Promise.resolve(instance.terminate()).catch(() => {}); } catch (_) {}
};
const task = (async () => {
if (typeof Tesseract.createWorker === 'function') {
const instance = await Tesseract.createWorker({ errorHandler: error => fatalError(new Error(String(error))) });
if (finished) { terminate(instance); return null; }
worker = instance;
await worker.load();
if (finished) return null;
await worker.loadLanguage('chi_sim');
if (finished) return null;
await worker.initialize('chi_sim');
if (finished) return null;
return worker.recognize(source);
}
return typeof Tesseract.recognize === 'function' ? Tesseract.recognize(source, 'chi_sim') : null;
})();
try {
const result = await this._waitForRecognition(Promise.race([task, fatal]), 'OCR 识别', context);
return result?.data?.text || '';
} finally {
finished = true;
terminate(worker);
}
},
async _ocrImage(imgEl, context = {}) {
const source = this._questionImageURL(imgEl);
if (!source) return '';
try {
return await this._recognizeOCR(source, context);
} catch (e) {
if (e.name === 'AbortError' || e.name === 'TimeoutError') throw e;
Logger.log('Tesseract OCR 错误: ' + (e.message || e), 'error');
}
return '';
},
// recognize(): 综合识别(先 DOM,失败则字体解密,最后 OCR)
async recognize(element, context = {}) {
context = { ...context, deadline: context.deadline ?? Date.now() + 30000 };
if (context.canContinue && !context.canContinue()) throw Object.assign(new Error('题目识别已取消'), { name: 'AbortError' });
const domResult = this.readFromDOM(element);
const hasFontSecret = element.matches?.('.font-cxsecret') || element.querySelector('.font-cxsecret') !== null;
if (domResult.question && !hasFontSecret) return domResult;
// DOM 提取失败(可能是 font-cxsecret 字体混淆),优先尝试字体解密
if (hasFontSecret) {
Logger.log('检测到 font-cxsecret 字体混淆,尝试字体解密...', 'info');
let fontActive = true;
try {
const doc = element.ownerDocument || document;
// 外层超时后也关闭本次写入权限,迟到字体不能再修改页面。
const canDecode = () => fontActive && (!context.canContinue || context.canContinue());
const decoded = await this._waitForRecognition(FontDecryptor.decryptElement(element, doc, canDecode), '字体识别', context, 10000);
// 解密后重新用 DOM 方式读取
const decryptedResult = this.readFromDOM(element);
if (decoded && decryptedResult.question) {
Logger.log('字体解密成功: ' + decryptedResult.question.slice(0, 30) + '...', 'info');
return decryptedResult;
}
} catch (e) {
if (e.name === 'AbortError' || e.name === 'TimeoutError') throw e;
Logger.log('字体解密异常: ' + (e.message || e), 'error');
} finally { fontActive = false; }
}
// 字体解密失败,回退到 html2canvas + OCR
if (typeof html2canvas !== 'undefined' && typeof Tesseract !== 'undefined') {
Logger.log('尝试 OCR 识别...', 'info');
let canvas = null;
let captureFinished = false;
try {
const capture = Promise.resolve(html2canvas(element, {
useCORS: true, logging: false, scale: 2, backgroundColor: '#ffffff'
})).then(value => {
if (captureFinished) { value.width = 0; value.height = 0; }
return value;
});
canvas = await this._waitForRecognition(capture, '题目截图', context, 8000);
const text = await this._recognizeOCR(canvas, context);
const lines = text.split('\n').map(l => l.trim()).filter(l => l);
let question = '';
const options = [];
const optionLetters = [];
const optionPattern = /^[A-F][.、::\s]\s*(.+)/;
for (const line of lines) {
const match = line.match(optionPattern);
if (match) {
options.push(match[1].trim());
optionLetters.push(line[0]);
} else if (!question) {
question = this._cleanQuestionText(line);
}
}
if (question) {
// 有图片选项时以 DOM 索引为准,OCR 行数不能改变选项与图片的关联。
const hasImageOptions = domResult.images.some(image => image.role === 'option');
const pairs = this._extractOptionPairs(element);
const unresolvedOptions = pairs.some(pair => {
if (pair.element?.getAttribute('aria-label') || pair.input?.getAttribute('aria-label')) return false;
const node = pair.element;
return !!(node?.closest('.font-cxsecret') || node?.querySelector('.font-cxsecret'));
}) || (!pairs.length && hasFontSecret && domResult.options.length > 0);
if (unresolvedOptions && (hasImageOptions || options.length !== domResult.options.length ||
optionLetters.some((letter, index) => letter !== String.fromCharCode(65 + index)))) {
Logger.log('字体选项尚未完整识别,已跳过本题', 'warn');
return { question: '', options: [], type: domResult.type, images: domResult.images };
}
return { question, options: hasImageOptions || options.length === 0 ? domResult.options : options, type: domResult.type ?? this._detectType(element), images: domResult.images };
}
} catch (e) {
if (e.name === 'AbortError' || e.name === 'TimeoutError') throw e;
Logger.log('OCR 识别失败: ' + (e.message || e), 'error');
} finally {
captureFinished = true;
if (canvas) { canvas.width = 0; canvas.height = 0; }
}
}
// 最后尝试图片 OCR
Logger.log('DOM 提取失败,尝试图片 OCR 识别...', 'info');
return await this.recognizeByOCR(element, context);
},
// ---- 8.3 matchAnswer ----
matchAnswer(answers, pageOptions) {
if (!answers || answers.length === 0 || !pageOptions || pageOptions.length === 0) return [];
const matched = [];
for (const answer of answers) {
const ans = answer.trim();
if (!ans) continue;
// 策略1:判断题特殊处理
const judgeIdx = this._matchJudge(ans);
if (judgeIdx >= 0 && judgeIdx < pageOptions.length) {
matched.push(judgeIdx);
continue;
}
// 策略2:纯字母答案映射(A/AC/BCD → 索引)
const letterIndices = this._matchLetters(ans);
if (letterIndices.length > 0) {
const valid = letterIndices.filter(i => i < pageOptions.length);
matched.push(...valid);
continue;
}
// 策略3:精确匹配
const exactIdx = this._matchExact(ans, pageOptions);
if (exactIdx >= 0) {
matched.push(exactIdx);
continue;
}
// 策略4:包含匹配
const containIdx = this._matchContain(ans, pageOptions);
if (containIdx >= 0) {
matched.push(containIdx);
continue;
}
// 策略5:相似度匹配(>60%)
const simIdx = this._matchSimilarity(ans, pageOptions);
if (simIdx >= 0) {
matched.push(simIdx);
continue;
}
}
// 去重
return [...new Set(matched)];
},
_matchJudge(ans) {
const truePatterns = /^(对|正确|√|✓|T|true|是|right|yes)$/i;
const falsePatterns = /^(错|错误|×|✗|F|false|否|wrong|no)$/i;
if (truePatterns.test(ans)) return 0;
if (falsePatterns.test(ans)) return 1;
return -1;
},
_matchLetters(ans) {
// 仅当答案是纯字母(A-Z)时才匹配
if (!/^[A-Za-z]+$/.test(ans)) return [];
// 排除可能是单词的情况(超过4个字母且不全是大写)
if (ans.length > 4 && ans !== ans.toUpperCase()) return [];
return ans.toUpperCase().split('').map(ch => ch.charCodeAt(0) - 65);
},
_matchExact(ans, pageOptions) {
const normalized = ans.toLowerCase().trim();
for (let i = 0; i < pageOptions.length; i++) {
if (pageOptions[i].toLowerCase().trim() === normalized) return i;
}
return -1;
},
_matchContain(ans, pageOptions) {
const normalized = ans.toLowerCase().trim();
// 答案是选项的子串
for (let i = 0; i < pageOptions.length; i++) {
const opt = pageOptions[i].toLowerCase().trim();
if (opt.includes(normalized) || normalized.includes(opt)) return i;
}
return -1;
},
_matchSimilarity(ans, pageOptions) {
let bestIdx = -1;
let bestScore = 0.6; // 阈值 60%
for (let i = 0; i < pageOptions.length; i++) {
const score = this._similarity(ans, pageOptions[i]);
if (score > bestScore) {
bestScore = score;
bestIdx = i;
}
}
return bestIdx;
},
// 字符串相似度(基于编辑距离)
_similarity(a, b) {
const s1 = a.toLowerCase().trim();
const s2 = b.toLowerCase().trim();
if (s1 === s2) return 1;
if (!s1 || !s2) return 0;
const maxLen = Math.max(s1.length, s2.length);
if (maxLen === 0) return 1;
const dist = this._editDistance(s1, s2);
return 1 - dist / maxLen;
},
_editDistance(a, b) {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) dp[i][0] = i;
for (let j = 0; j <= n; j++) dp[0][j] = j;
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
}
}
}
return dp[m][n];
},
// ---- 8.3.1 万能脚本算法移植:智能匹配辅助函数 ----
// 文本归一化(同万能脚本 formatString)
// 修复:
// 1) 原 guard `includes('img')` 会误伤含 "img" 子串的普通文字;改为精确的 `
')
.replace(/ /g, ' ')
.replace(/&/g, '&');
// 全角转半角
src = src.replace(/[\uff01-\uff5e]/g, ch => String.fromCharCode(ch.charCodeAt(0) - 65248));
return src.replace(/\s+/g, ' ')
.replace(/[\u201c\u201d]/g, '"')
.replace(/[\u2018\u2019]/g, "'")
.replace(/\u3002/g, '.')
.replace(/[,.?:!;]$/, '')
.trim();
},
// 判断答案文本表示"对/正确"
_isTrue(str) {
return Boolean(String(str).match(/(^|,)(正确|是|对|√|T|ri|true|A)(,|$)/));
},
// 判断答案文本表示"错/错误"
_isFalse(str) {
return Boolean(String(str).match(/(^|,)(错误|否|错|×|F|不是|wr|false|B)(,|$)/));
},
// 判断是否为纯字母答案(如 A、ABC)
_isPlainAnswer(answer) {
if (!answer || answer.length > 8 || !/[A-Z]/.test(answer)) return false;
let min = 0;
for (let i = 0; i < answer.length; i++) {
if (answer.charCodeAt(i) < min) return false;
min = answer.charCodeAt(i);
}
return true;
},
// 投票:在多个候选组中取出现次数最多的组合
_getMost(arr) {
if (!arr || arr.length === 0) return undefined;
const reversed = [...arr].reverse();
const hash = {};
let m = 0; let trueEl;
for (const el of reversed) {
const key = JSON.stringify(el);
hash[key] = (hash[key] || 0) + 1;
if (hash[key] >= m) { m = hash[key]; trueEl = el; }
}
return trueEl;
},
// 取最长的组合(多选题兜底)
_getLong(arr) {
if (!arr || arr.length === 0) return undefined;
let len = 0; let ele;
for (const a of arr) {
if (a.length > len) { len = a.length; ele = a; }
}
return ele || (arr.length > 0 ? arr[0] : []);
},
// 判断题:根据页面选项内容动态判定"对/错"对应的索引
_findJudgeIndexByOptions(isTrue, pageOptions) {
if (!Array.isArray(pageOptions) || pageOptions.length === 0) return -1;
// 优先精确判断每个选项
for (let i = 0; i < pageOptions.length; i++) {
const opt = String(pageOptions[i] || '').trim();
if (isTrue && this._isTrue(opt)) return i;
if (!isTrue && this._isFalse(opt)) return i;
}
// 兜底:约定 [对, 错] 顺序
return isTrue ? 0 : 1;
},
// ---- 8.3.2 智能匹配(移植万能脚本算法)----
// groups: 二维答案组数组(success:false 时由后端返回多组相似答案,success:true 时只有一组)
// pageOptions: 当前页面的选项文本数组
// type: TYPE_SINGLE / TYPE_MULTI / TYPE_JUDGE / TYPE_FILL / TYPE_OTHER
matchAnswerSmart(groups, pageOptions, type) {
if (!Array.isArray(groups) || groups.length === 0) return [];
if (type === this.TYPE_FILL) return []; // 填空题不通过此函数
const targetOptionsList = [];
for (const answers of groups) {
if (!Array.isArray(answers) || answers.length === 0) continue;
if (type === this.TYPE_JUDGE) {
if (targetOptionsList.length > 3) break;
const targetOptions = new Set();
const joined = answers.join(',');
if (this._isTrue(joined)) {
const idx = this._findJudgeIndexByOptions(true, pageOptions);
if (idx >= 0) targetOptions.add(idx);
} else if (this._isFalse(joined)) {
const idx = this._findJudgeIndexByOptions(false, pageOptions);
if (idx >= 0) targetOptions.add(idx);
}
if (targetOptions.size > 0) targetOptionsList.push(targetOptions);
} else if (type === this.TYPE_SINGLE || type === this.TYPE_MULTI || type === this.TYPE_OTHER) {
const beautifulOptions = (pageOptions || []).map(o => this._formatString(o).toLowerCase().replace(/\s/g, ''));
const targetOptions = new Set();
for (const ans of answers) {
const ansStr = String(ans || '').trim();
if (!ansStr) continue;
// 纯字母答案(A/AB/ABC)
if (ansStr.length <= 4 && this._isPlainAnswer(ansStr.toUpperCase())) {
for (const ch of ansStr.toUpperCase()) {
const idx = ch.charCodeAt(0) - 65;
if (idx >= 0 && idx < (pageOptions || []).length) targetOptions.add(idx);
}
continue;
}
// 完整文本匹配
const val = this._formatString(ansStr).toLowerCase().replace(/\s/g, '');
const optIndex = beautifulOptions.indexOf(val);
if (optIndex >= 0) targetOptions.add(optIndex);
}
// 单选无命中或多选不足2个 → 启用相似度匹配(>65%)
if ((type === this.TYPE_SINGLE && targetOptions.size === 0) || (type === this.TYPE_MULTI && targetOptions.size < 2) || (type === this.TYPE_OTHER && targetOptions.size === 0)) {
if (targetOptionsList.length === 0) {
for (const ans of answers) {
const val = this._formatString(String(ans || '')).toLowerCase();
if (val.length >= 3 && !val.includes('
this._similarity(val, opt) * 100);
const maxScore = Math.max(...ratings, 0);
if (maxScore > 65) targetOptions.add(ratings.indexOf(maxScore));
}
}
}
}
if (targetOptions.size > 0) targetOptionsList.push(targetOptions);
}
}
// 投票:对于单选/判断,选出现次数最多的单一答案;多选选出现最多的组合
const sortArr = targetOptionsList.map(s => Array.from(s).sort((a, b) => a - b));
let items;
if (type === this.TYPE_SINGLE || type === this.TYPE_JUDGE || type === this.TYPE_OTHER) {
items = this._getMost(sortArr.filter(i => i.length === 1));
if (!items || items.length === 0) {
items = this._getMost(sortArr.filter(i => i.length > 0));
}
} else if (type === this.TYPE_MULTI) {
items = this._getMost(sortArr.filter(i => i.length > 1));
if (!items || items.length === 0) {
items = this._getLong(sortArr.filter(i => i.length > 0));
}
}
return items || [];
},
// ---- 8.4 autoSelectAndSubmit ----
async autoSelectAndSubmit(answers, container) {
if (!container) {
Logger.log('无法解析答案:容器元素为空', 'error');
return;
}
// 提取页面选项文本
const pageOptions = this._extractOptions(container);
if (pageOptions.length === 0 && this._detectType(container) !== this.TYPE_FILL) {
Logger.log('无法解析答案:未找到页面选项', 'error');
return;
}
const type = this._detectType(container);
// 填空题特殊处理
if (type === this.TYPE_FILL) {
this._fillBlanks(answers, container);
return;
}
// 匹配答案
const matchedIndices = this.matchAnswer(answers, pageOptions);
if (matchedIndices.length === 0) {
Logger.log('无法解析答案:匹配失败,跳过该题', 'error');
return;
}
// 选中对应选项
this._selectOptions(matchedIndices, container, type);
// 点击提交按钮
await this._clickSubmit(container);
},
// 只在一个选项行内读取状态;不能把题号导航、展开按钮的 active 当作答案。
_isPairSelected(pair) {
if (!pair) return false;
const { element, input } = pair;
if (input && input.checked) return true;
if (element) {
const classes = String(element.className || '').split(/\s+/);
if (['is-checked', 'checked', 'active', 'selected', 'cur', 'check_answer', 'check_answer_dx'].some(name => classes.includes(name))) return true;
if (element.getAttribute && element.getAttribute('aria-checked') === 'true') return true;
try {
if (element.querySelector && element.querySelector('.check_answer, .check_answer_dx, .is-checked, [aria-checked="true"], input:checked')) return true;
} catch (_) {}
}
return false;
},
// 保存本次实际要填写的选项,防止只点中一个选项就把多选题判为完整。
_selectionTargets: new WeakMap(),
_areOptionsSelected(container) {
const target = this._selectionTargets.get(container);
if (!target) return false;
const pairs = this._extractOptionPairs(container);
if (!pairs.length || pairs.length !== target.texts.length ||
pairs.some((pair, index) => pair.text !== target.texts[index])) return false;
return pairs.every((pair, index) => this._isPairSelected(pair) === target.indices.has(index));
},
_selectOptions(indices, container, type) {
// 通过 _extractOptionPairs 获取严格对齐的 (text, element, input) 三元组,
// 避免 inputs[1] 因隐藏/多余 radio 而错位(典型表现:日志显示选 B 但页面选中 A)
const pairs = this._extractOptionPairs(container);
const labels = [];
const skipped = [];
const targets = new Set(indices);
if (!pairs.length || !targets.size || [...targets].some(index => !Number.isInteger(index) || index < 0 || index >= pairs.length) ||
((type === this.TYPE_SINGLE || type === this.TYPE_JUDGE) && targets.size !== 1)) return false;
this._selectionTargets.set(container, { indices: targets, texts: pairs.map(pair => pair.text) });
// 单次点击切换选项的勾选状态(设置为 desired),已是 desired 则跳过避免反选
const setPairChecked = (pair, desired) => {
if (!pair) return false;
const current = this._isPairSelected(pair);
if (current === desired) return false; // 已是目标状态,避免再次点击触发 toggle 取消
const { element, input } = pair;
const clickTarget = input || element;
if (!clickTarget || clickTarget.disabled || clickTarget.getAttribute?.('aria-disabled') === 'true') return false;
try {
// 让页面自己的点击事件更新答案;直接强改 checked 会掩盖点击失败。
clickTarget.click();
return true;
} catch (_) { return false; }
};
// 多选题:先取消现已勾选但本题答案不需要的选项(防止脏选项保留)
if (type === Solver.TYPE_MULTI && pairs.length > 0) {
const indexSet = new Set(indices);
for (let i = 0; i < pairs.length; i++) {
if (!indexSet.has(i) && this._isPairSelected(pairs[i])) {
setPairChecked(pairs[i], false);
labels.push('-' + String.fromCharCode(65 + i));
}
}
}
// 选中目标选项;已选中则跳过点击避免取消
indices.forEach(idx => {
if (idx >= 0 && idx < pairs.length) {
const wasSelected = this._isPairSelected(pairs[idx]);
if (wasSelected) {
skipped.push(String.fromCharCode(65 + idx));
labels.push(String.fromCharCode(65 + idx) + '(已选)');
return;
}
setPairChecked(pairs[idx], true);
labels.push(String.fromCharCode(65 + idx));
return;
}
});
const summary = labels.length > 0 ? labels.join(',') : '(无变化)';
const skipNote = skipped.length > 0 ? `(${skipped.join(',')} 已是正确答案,跳过点击避免取消)` : '';
Logger.log(`已操作选项: ${summary}${skipNote}`, 'info');
return true;
},
_fillBlanks(answers, container) {
// 只处理当前题目中真正可编辑的答案框;禁用/只读/隐藏的输入框不应
// 被计入题目空数,否则会把页面上的模板字段误判为未完成。
const inputs = this._getFillInputs(container);
if (!Array.isArray(answers) || answers.length === 0 || inputs.length === 0) {
Logger.log(inputs.length === 0 ? '填空题未找到可编辑输入框' : '填空题未返回有效答案', 'error');
return false;
}
let filled = 0;
for (let i = 0; i < inputs.length; i++) {
const input = inputs[i];
const current = String(input.value == null ? '' : input.value).trim();
// 用户已经填写的内容先保留,避免自动答题覆盖用户可能已经填对的答案。
if (current) continue;
if (i >= answers.length || answers[i] == null) continue;
const answer = String(answers[i]).trim();
if (!answer) continue;
try {
input.value = answer;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
if (String(input.value == null ? '' : input.value).trim() === answer) filled++;
} catch (_) {}
}
const incomplete = inputs.filter(input => !String(input.value == null ? '' : input.value).trim()).length;
Logger.log(`已填写 ${filled} 个空${incomplete ? `,仍有 ${incomplete} 个空未完成` : ''}`, incomplete ? 'error' : 'info');
// 返回真实完成状态:允许先写入部分答案,但不能把部分答案当作已完成。
return incomplete === 0;
},
_getFillInputs(container) {
if (!container || typeof container.querySelectorAll !== 'function') return [];
let candidates = [];
try { candidates = Array.from(container.querySelectorAll('input, textarea')); } catch (_) {}
return candidates.filter((el) => {
if (!el) return false;
const tag = String(el.tagName || '').toLowerCase();
if (tag === 'textarea') {
// textarea 没有 type 属性,继续走通用可编辑性检查。
} else if (tag === 'input') {
const type = String(el.type || el.getAttribute?.('type') || 'text').toLowerCase();
if (type !== 'text') return false;
} else {
return false;
}
if (el.disabled || el.readOnly || el.getAttribute?.('aria-disabled') === 'true' || el.getAttribute?.('readonly') != null) return false;
const cls = String(el.className || '');
if (/\b(disabled|is-disabled|forbid|readonly)\b/i.test(cls)) return false;
try {
if (typeof this._isVisibleElement === 'function' && !this._isVisibleElement(el)) return false;
} catch (_) {}
return true;
});
},
_isVisibleElement(el) {
if (!el || el.disabled || el.getAttribute('aria-disabled') === 'true') return false;
const cls = String(el.className || '');
if (/\b(disabled|is-disabled|forbid|readonly)\b/i.test(cls)) return false;
try {
const win = el.ownerDocument?.defaultView || window;
const style = win.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false;
} catch (_) {}
const rect = el.getBoundingClientRect?.();
if (rect && rect.width === 0 && rect.height === 0) return false;
return true;
},
_findClickableByText(doc, textPatterns, root = null) {
doc = doc || document;
const scope = root || doc;
const selectors = [
'button', 'a', '[role="button"]', 'input[type="button"]', 'input[type="submit"]',
'.btn', '.Btn', '.jb_btn', '.Btn_blue_01', '.Btn_blue_1', '.save_btn', '.submit_btn',
'.el-button', '.ant-btn', '.layui-layer-btn a', '.popbtn', '.sure', '.confirm'
];
let candidates = [];
try { candidates = Array.from(scope.querySelectorAll(selectors.join(','))); } catch (_) {}
const patterns = textPatterns.map(t => String(t).replace(/\s+/g, ''));
for (const el of candidates) {
if (!this._isVisibleElement(el)) continue;
const value = el.value || '';
const text = ((el.innerText || el.textContent || value || '') + '').replace(/\s+/g, '');
const aria = (el.getAttribute?.('aria-label') || '').replace(/\s+/g, '');
if (!text && !aria) continue;
if (patterns.some(p => text === p || text.includes(p) || aria === p || aria.includes(p))) return el;
}
return null;
},
async _confirmSubmitDialogs(doc, canSubmit = () => true) {
const current = CXRequests.capture();
const allowed = () => current() && canSubmit();
if (!allowed()) return false;
doc = doc || document;
await new Promise(r => setTimeout(r, 500));
if (!allowed()) return false;
const docs = CXUtils.listAccessibleDocs(document, 4);
if (!docs.includes(doc)) docs.unshift(doc);
const patterns = ['确定', '确认', '继续提交', '提交', '保存', '我知道了', '知道了'];
// 只在弹窗根节点内找确认按钮,不能把页面主内容中的“提交作业”
// 当成确认按钮再次点击。最终提交后的确认弹窗仍会被覆盖到。
const dialogSelectors = [
'.layui-layer', '.layui-layer-dialog', '.xubox_layer',
'.ui-dialog', '.modal', '.modal-dialog', '.el-dialog', '.ant-modal',
'[role="dialog"]', '.popbox', '.popDiv', '.popup', '.popup-container',
'.ans-dialog', '.confirm-dialog', '.alert-dialog', '#confirmBox', '#dialog'
];
const roots = [];
const seenRoots = new Set();
for (const d of docs) {
for (const selector of dialogSelectors) {
let nodes = [];
try { nodes = Array.from(d.querySelectorAll(selector)); } catch (_) {}
for (const root of nodes) {
if (root && !seenRoots.has(root)) {
seenRoots.add(root);
roots.push({ doc: d, root });
}
}
}
}
for (const item of roots) {
if (!allowed()) return false;
const btn = this._findClickableByText(item.doc, patterns, item.root);
if (btn) {
try {
btn.click();
Logger.log('已确认提交弹窗', 'info');
await new Promise(r => setTimeout(r, 600));
return true;
} catch (_) {}
}
}
return false;
},
async _clickSubmit(container, canSubmit = () => true) {
const current = CXRequests.capture();
const allowed = () => current() && canSubmit() && container?.isConnected !== false;
if (!allowed() || !container || typeof container.querySelector !== 'function') return false;
const doc = container.ownerDocument || document;
// 逐题保存只能查当前题目容器。页面级“提交作业/交卷”由
// _clickFinalSubmit 在全部题目处理完后统一执行,不能在这里回退到 doc,
// 否则标准作业页会在第一题后误点整份作业的全局提交按钮。
const submitSelectors = [
'.jb_btn.jb_btn_92',
'.jb_btn',
'#submitBtn',
'#saveBtn',
'#submit_button',
'a.jb_btn',
'button[type="submit"]',
'input[type="submit"]',
'.Btn_blue_01',
'.Btn_blue_1',
'.saveWork',
'.save_btn',
'.submit_btn',
'.submitBtn',
'.btnSubmit',
'.saveYl',
'.commitBtn'
];
let submitBtn = null;
for (const sel of submitSelectors) {
try {
submitBtn = container?.querySelector(sel);
} catch (_) {
submitBtn = null;
}
if (submitBtn && this._isVisibleElement(submitBtn)) break;
submitBtn = null;
}
if (!submitBtn) {
submitBtn = this._findClickableByText(
doc,
['提交', '保存', '提交答案', '保存答案', '确定', '完成'],
container
);
}
if (submitBtn) {
await new Promise(r => setTimeout(r, 300));
if (!allowed() || submitBtn.isConnected === false) return false;
try { submitBtn.click(); } catch (_) {}
Logger.log('已点击提交/保存按钮', 'info');
await this._confirmSubmitDialogs(doc, allowed);
return allowed();
}
return false;
},
async _clickFinalSubmit(doc, label = '任务', canSubmit = () => true) {
const current = CXRequests.capture();
const allowed = () => current() && canSubmit();
if (!allowed()) return false;
doc = doc || document;
const btn = this._findClickableByText(doc, [
'提交作业', '提交测验', '提交考试', '提交试卷', '提交答案', '提交',
'保存并提交', '保存提交', '完成', '交卷'
]) || this._findClickableByText(document, [
'提交作业', '提交测验', '提交考试', '提交试卷', '提交答案', '提交',
'保存并提交', '保存提交', '完成', '交卷'
]);
if (!btn) {
Logger.log(`${label}未找到最终提交按钮`, 'info');
return false;
}
await new Promise(r => setTimeout(r, 500));
if (!allowed() || btn.isConnected === false) return false;
try { btn.click(); } catch (_) { return false; }
Logger.log(`${label}已点击最终提交按钮`, 'success');
await this._confirmSubmitDialogs(doc, allowed);
return allowed();
}
};
// ==========================================
// AnswerModule - 答题模块(三种答题模式)
// ==========================================
const AnswerModule = {
_mode: 'free', // 当前模式: 'free' | 'paid' | 'ai'
_answering: false,
_stopRequested: false,
_answerGeneration: 0,
_answerRunId: null,
_currentQuestion: 0,
_totalQuestions: 0,
_aiUnlockExpiryTimer: null,
_aiUnlockDisplayUntil: 0,
_pendingDelays: new Set(),
// AI模式题间延迟(毫秒):解锁后1.5秒,未解锁35秒;其他模式1-2秒
async _getQuestionDelay() {
if (this._mode === 'ai') {
if (await AccessGuard.requireAIUnlockAccess()) {
return 1500 + Math.random() * 500; // 解锁后 1.5-2秒
}
return 35000 + Math.random() * 2000; // 未解锁 35-37秒
}
return 1000 + Math.random() * 1000; // 1-2秒
},
// ---- 模式管理 ----
setMode(mode) {
this._mode = mode;
const cfg = ConfigStore.getAnswerConfig();
cfg.mode = mode;
ConfigStore.setAnswerConfig(cfg);
this._updateModeUI();
Logger.log(`答题模式已切换为: ${mode === 'free' ? '免费题库' : mode === 'paid' ? '付费题库' : 'AI 答题'}`, 'info');
},
getMode() {
return this._mode;
},
// ---- 9.1 免费验证码模式 ----
_verificationRequests: new Map(),
_activationRequestSeq: 0,
_beginVerificationRequest(scope) {
const token = scope === 'free-answer' ? ConfigStore.getVerifySessionToken() : ConfigStore.getAIUnlockSessionToken();
const request = {
scope,
seq: (this._verificationRequests.get(scope)?.seq || 0) + 1,
identity: AccessGuard._getSessionIdentity(scope, token),
doc: UIPanel._doc
};
this._verificationRequests.set(scope, request);
return request;
},
_isVerificationRequestCurrent(request) {
return this._verificationRequests.get(request.scope) === request && UIPanel._doc === request.doc && AccessGuard._isCurrentIdentity(request.identity);
},
_verificationStaleError() {
const error = new Error('验证状态已变化,本次响应已忽略,请重新验证');
error.stale = true;
return error;
},
_readVerificationResponse(resp, request) {
if (!this._isVerificationRequestCurrent(request)) throw this._verificationStaleError();
const status = Number(resp.status);
if (status < 200 || status >= 300 || !Number.isFinite(status)) throw new Error('验证服务响应异常,请稍后重试');
let result;
try { result = JSON.parse(resp.responseText); } catch (_) { throw new Error('验证响应不是有效 JSON'); }
const data = result?.data;
if (result?.code !== 1 || data?.valid !== true) throw new Error(String(result?.msg || result?.message || '验证码无效或已过期'));
const token = data.session_token;
const until = typeof data.valid_until === 'number' || typeof data.valid_until === 'string' && /^\d+$/.test(data.valid_until)
? Number(data.valid_until) : NaN;
if (data.scope !== request.scope || data.verification_required !== true || typeof token !== 'string' || !token.trim() || token.length > 4096 || /[\u0000-\u0020\u007f]/.test(token) || !Number.isSafeInteger(until) || until >= 1e12 || until <= Math.floor(Date.now() / 1000) || data.device_id !== undefined && data.device_id !== request.identity.deviceId) {
throw new Error('验证响应中的用途、会话或有效期异常,请重新验证');
}
return { success: true, validUntil: until, validUntilStr: new Date(until * 1000).toLocaleString('zh-CN'), sessionToken: token };
},
async verifyCode(code) {
code = String(code || '').trim();
if (!/^\d{4}$/.test(code)) {
this._updateFreeStatus(false, '请输入4位数字验证码');
return { success: false, message: '请输入4位数字验证码' };
}
const request = this._beginVerificationRequest('free-answer');
const verifyBtn = request.doc?.getElementById('cx-btn-verify');
if (verifyBtn) { verifyBtn.disabled = true; verifyBtn.textContent = '验证中...'; }
try {
const resp = await new Promise((resolve, reject) => CXRequests.request({
method: 'POST',
url: 'http://103.236.88.53:23123/index.php?s=/api/code/verify',
timeout: 25000,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: 'code=' + encodeURIComponent(code) + '&scope=free-answer&device_id=' + encodeURIComponent(request.identity.deviceId),
onload: resolve,
onerror: () => reject(new Error('验证请求失败,处理结果需确认,请稍后重新检查')),
ontimeout: () => reject(new Error('验证请求超时,验证码可能已被使用,请先重新检查会话')),
onabort: () => reject(new Error('验证请求已取消,处理结果需确认'))
}, 'ui'));
const result = this._readVerificationResponse(resp, request);
ConfigStore.setVerifyValidUntil(result.validUntil, code, result.sessionToken);
Logger.log(`验证成功,有效期至 ${result.validUntilStr}`, 'success');
this._updateFreeStatus(true, result.validUntilStr);
this._syncVerificationUI();
return result;
} catch (error) {
if (!this._isVerificationRequestCurrent(request)) error = this._verificationStaleError();
const message = error?.message || '验证未完成';
if (!error.stale) { Logger.log(message, 'error'); this._updateFreeStatus(false, message); }
return { success: false, message, stale: Boolean(error.stale) };
} finally {
if (this._verificationRequests.get(request.scope) === request && UIPanel._doc === request.doc && verifyBtn) {
verifyBtn.textContent = '验证';
verifyBtn.disabled = this.isVerifyValid();
}
}
},
isVerifyValid() {
return ConfigStore.isVerifyValid();
},
_updateFreeStatus(success, message) {
const doc = UIPanel._doc;
if (!doc) return;
const statusEl = doc.getElementById('cx-free-status');
const codeInput = doc.getElementById('cx-free-code');
const verifyBtn = doc.getElementById('cx-btn-verify');
if (!statusEl) return;
if (success && this.isVerifyValid()) {
statusEl.textContent = `✅ 验证成功,有效期至 ${message}`;
statusEl.style.color = '#67c23a';
if (codeInput) codeInput.disabled = true;
if (verifyBtn) verifyBtn.disabled = true;
} else if (success === false) {
statusEl.textContent = `❌ ${message}`;
statusEl.style.color = '#f56c6c';
if (codeInput) codeInput.disabled = false;
if (verifyBtn) verifyBtn.disabled = false;
} else {
statusEl.textContent = '';
if (codeInput) codeInput.disabled = false;
if (verifyBtn) verifyBtn.disabled = false;
}
},
// 检查免费模式有效期,过期后重新启用输入
_checkFreeExpiry() {
if (this._mode !== 'free') return;
const cfg = ConfigStore.getAnswerConfig();
const validUntil = cfg.verifyValidUntil || 0;
if (validUntil > 0 && !ConfigStore.isVerifyValid()) {
// 已过期
ConfigStore.clearVerifySession();
this._updateFreeStatus(null);
const doc = UIPanel._doc;
if (doc) {
const statusEl = doc.getElementById('cx-free-status');
if (statusEl) {
statusEl.textContent = '⚠️ 验证码已过期,请重新验证';
statusEl.style.color = '#e6a23c';
}
}
Logger.log('免费模式验证码已过期', 'info');
}
},
// ---- 9.2 付费积分模式 ----
async activateCode(code) {
code = String(code || '').trim();
if (!code) {
this._showPaidStatus(false, '请输入题库积分激活码');
return { success: false, message: '请输入题库积分激活码' };
}
const seq = ++this._activationRequestSeq;
const device = ConfigStore.getDeviceId();
const doc = UIPanel._doc;
const activateBtn = doc?.getElementById('cx-btn-activate');
const current = () => seq === this._activationRequestSeq && device === ConfigStore.getDeviceId() && doc === UIPanel._doc;
if (activateBtn) { activateBtn.disabled = true; activateBtn.textContent = '激活中...'; }
try {
const resp = await new Promise((resolve, reject) => CXRequests.request({
method: 'POST',
url: 'http://103.236.88.53:23123/index.php?s=/api/question_bank/activate',
timeout: 25000,
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({ code, device_id: device }),
onload: resolve,
onerror: () => reject(new Error('激活请求失败,结果需确认,请先核对积分或激活记录')),
ontimeout: () => reject(new Error('激活请求超时,可能已成功,请先核对积分或激活记录')),
onabort: () => reject(new Error('激活请求已取消,处理结果需确认,请先核对积分或激活记录'))
}, 'ui'));
if (!current()) throw this._verificationStaleError();
const status = Number(resp.status);
if (!Number.isFinite(status) || status < 200 || status >= 300) throw new Error('激活服务响应异常,结果需确认,请先核对积分或激活记录');
let result;
try { result = JSON.parse(resp.responseText); } catch (_) { throw new Error('激活响应解析失败,结果需确认,请先核对积分或激活记录'); }
const data = result?.data;
if (result?.code !== 1 || data?.valid !== true) throw new Error(String(result?.msg || result?.message || '激活码无效或已使用'));
const credits = data.credits;
const remaining = data.remaining_credits;
if (!Number.isSafeInteger(credits) || credits < 0 || !Number.isSafeInteger(remaining) || remaining < 0 || data.device_id !== undefined && data.device_id !== device) {
throw new Error('激活响应中的积分或设备信息异常,请先核对激活记录');
}
const message = typeof data.message === 'string' && data.message ? data.message : `已激活 ${credits} 积分`;
Logger.log(`激活成功: ${message}`, 'success');
this._updateCreditsDisplay(remaining);
this._showPaidStatus(true, message);
return { success: true, credits, remaining };
} catch (error) {
const message = current() ? error?.message || '激活未完成' : '设备或激活状态已变化,本次响应已忽略,请核对激活记录';
if (current()) { Logger.log(message, 'error'); this._showPaidStatus(false, message); }
return { success: false, message, stale: !current() };
} finally {
if (seq === this._activationRequestSeq && doc === UIPanel._doc && activateBtn) { activateBtn.disabled = false; activateBtn.textContent = '激活'; }
}
},
getCredits() {
const canContinue = CXRequests.capture();
const deviceId = ConfigStore.getDeviceId();
return new Promise((resolve) => {
CXRequests.taskRequest({
method: 'GET',
url: `http://103.236.88.53:23123/index.php?s=/api/question_bank/credits&device_id=${encodeURIComponent(deviceId)}`,
onload: (resp) => {
if (!canContinue() || deviceId !== ConfigStore.getDeviceId()) { resolve(null); return; }
try {
const data = CXRequests.readJSON(resp);
const remaining = this._readCreditAmount(data.remaining_credits);
if (remaining === null) throw new Error('积分余额格式无效');
this._updateCreditsDisplay(remaining);
resolve(remaining);
} catch (_) { resolve(null); }
},
onerror: () => resolve(null),
ontimeout: () => resolve(null),
onabort: () => resolve(null)
});
});
},
_readCreditAmount(value) {
if (!(typeof value === 'number' || typeof value === 'string' && /^\d+$/.test(value))) return null;
const amount = Number(value);
return Number.isSafeInteger(amount) && amount >= 0 ? amount : null;
},
_updateCreditsDisplay(credits) {
if (this._readCreditAmount(credits) === null) return;
const doc = UIPanel._doc;
if (!doc) return;
const el = doc.getElementById('cx-paid-credits');
if (el) el.textContent = credits;
},
_showPaidStatus(success, message) {
const doc = UIPanel._doc;
if (!doc) return;
const statusEl = doc.getElementById('cx-paid-status');
if (!statusEl) return;
statusEl.textContent = success ? `✅ ${message}` : `❌ ${message}`;
statusEl.style.color = success ? '#67c23a' : '#f56c6c';
},
// ---- 9.3 AI 答题模式 ----
setAIApiKey(key) {
ConfigStore.setAISettings({ ...ConfigStore.getAISettings(), apiKey: String(key || '').trim() });
Logger.log('当前来源的 AI API Key 已保存', 'success');
},
async askAI(question, options, type, images = []) {
const failure = { answers: [], remaining: -1 };
const canContinue = CXRequests.capture();
let config;
let hasImages = false;
try {
if (this._hasUnsavedAISettings?.()) {
Logger.log('AI 设置尚未保存,请保存当前来源、模型和 Key 后再开始答题', 'error');
return failure;
}
// 本题始终复用同一快照,等待下载、检测或重试时不会串用其他来源的 Key。
config = AISettingsService.snapshot(getAIProviderConfig());
if (!Array.isArray(images)) throw new Error('题图信息格式无效,请重新扫描题目');
hasImages = images.length > 0;
let imageParts = [];
if (hasImages) {
Logger.log(`🖼️ 检测到 ${images.length} 张题目/选项图片,正在读取图片`, 'info');
// 先检查原图有效性,避免缺图或登录页触发收费检测。
imageParts = await AISettingsService._prepareImages(images, canContinue);
if (!canContinue()) return failure;
Logger.log('🧪 正在确认当前模型的图片能力…', 'info');
const capability = await AISettingsService.checkVision(config);
if (!canContinue()) return failure;
if (capability.status !== 'supported') {
Logger.log(capability.message || '尚未确认当前模型支持图片,已停止本题作答,请更换模型或检测图片能力', 'error');
return failure;
}
}
const prompt = this._buildAIPrompt(question, options, type);
const buildContent = text => hasImages ? [
{ type: 'text', text: text + '\n\n【附图】每张图片前已标记题干或对应选项,请结合图片判断;看不清关键条件时不得编造答案。' },
...imageParts
] : text;
const retryPrompt = type === Solver.TYPE_FILL
? prompt + '\n\n上一次没有给出有效填空答案。请重新作答,只输出非空填空内容;多个空用 || 分隔,不要解释、标点空壳或空字符串。'
: prompt;
Logger.log(`🤖 正在使用 ${config.name} · ${config.model} 答题${hasImages ? '(含图片)' : ''}…`, 'info');
for (let attempt = 0; attempt < (type === Solver.TYPE_FILL ? 2 : 1); attempt++) {
if (!canContinue()) return failure;
if (this._hasUnsavedAISettings?.()) {
Logger.log('AI 设置已修改但尚未保存,已停止发送本题请求', 'error');
return failure;
}
const body = createAIRequestBody(config, buildContent(attempt ? retryPrompt : prompt), 0.1, type === Solver.TYPE_FILL ? 2048 : 4096);
const raw = await AISettingsService._request(config, body);
if (!canContinue()) return failure;
const content = this._cleanAIContent(AISettingsService._readContent(raw));
const answers = this._parseAIAnswer(content, type);
if (answers.length) {
Logger.log(`AI 返回答案: ${answers.join(', ')}`, 'success');
return { answers, remaining: -1 };
}
if (attempt === 0 && type === Solver.TYPE_FILL) Logger.log('AI 首次返回空答案,正在用填空题强化提示重试…', 'info');
}
Logger.log('AI 返回内容为空或无法提取有效答案', 'error');
} catch (error) {
if (hasImages && config && error?.visionUnsupported === true) {
AISettingsService._setVisionStatus(config, { status: 'unsupported', message: '当前模型或接口明确不支持图片输入,请选择支持图片的模型后重新检测。' });
}
Logger.log(error?.message || 'AI 请求未完成,请检查来源、模型和网络设置', 'error');
}
return failure;
},
_buildAIPrompt(question, options, type) {
const typeNames = { 0: '单选题', 1: '多选题', 2: '填空题', 3: '判断题', 4: '题目' };
const typeName = typeNames[type] || '题目';
let prompt = `请回答以下${typeName},`;
switch (type) {
case Solver.TYPE_SINGLE:
prompt += '请只回答选项字母(如 A),不要包含其他内容。\n';
break;
case Solver.TYPE_MULTI:
prompt += '请回答所有正确选项的字母,多个选项之间用 || 分隔(如 A||C||D),不要包含其他内容。\n';
break;
case Solver.TYPE_JUDGE:
prompt += '请只回答"对"或"错",不要包含其他内容。\n';
break;
case Solver.TYPE_FILL:
prompt += '请只回答填空内容,多个空之间用 || 分隔,不要包含其他内容。题目里的 ()、()、横线、空格都表示需要补全的位置;严禁返回空答案,无法完全确定也必须给出最可能答案。\n';
break;
default:
prompt += '请直接回答答案,不要包含解释。\n';
}
prompt += `\n题目:${question}\n`;
if (options && options.length > 0) {
prompt += '选项:\n';
options.forEach((opt, i) => {
prompt += `${String.fromCharCode(65 + i)}. ${opt}\n`;
});
}
return prompt;
},
_cleanAIContent(content) {
return String(content || '')
.trim()
.replace(/^```(?:json|text)?\s*/i, '')
.replace(/```$/i, '')
.replace(/^\s*(?:答案|答|最终答案|填空内容)\s*[::]\s*/i, '')
.trim();
},
_parseAIAnswer(content, type) {
let text = this._cleanAIContent(content);
if (!text) return [];
// 填空题:兼容 "||" / JSON / 引号 / "应填:xxx" 等格式,并过滤空壳答案
if (type === Solver.TYPE_FILL) {
const normalizeFill = (s) => String(s || '')
.replace(/^\s*(?:答案|答|填空内容|应填|填写|填入|空\d*|第\d+空)\s*[::]\s*/i, '')
.replace(/^["'“”‘’]+|["'“”‘’]+$/g, '')
.trim();
try {
const json = JSON.parse(text);
if (Array.isArray(json)) {
const arr = json.map(normalizeFill).filter(Boolean);
if (arr.length) return arr;
}
if (json && typeof json === 'object') {
const values = Object.values(json).map(normalizeFill).filter(Boolean);
if (values.length) return values;
}
} catch (_) {}
const stripped = normalizeFill(text);
if (!stripped || /^(?:无|空|不知道|不确定|无法确定|略|N\/A|NA|null|undefined)$/i.test(stripped)) return [];
if (stripped.includes('||')) {
return stripped.split('||').map(normalizeFill).filter(Boolean);
}
const lines = stripped.split(/\n+/).map(normalizeFill).filter(Boolean);
if (lines.length > 1) return lines;
const quoted = [...stripped.matchAll(/[“"']([^“”"']{1,80})[”"']/g)]
.map(m => normalizeFill(m[1]))
.filter(Boolean);
if (quoted.length) return quoted;
const colon = stripped.match(/(?:应填|填入|填写|答案(?:是|为)?)[::]\s*([^。;;\n]+)/i);
if (colon && normalizeFill(colon[1])) return [normalizeFill(colon[1])];
return [stripped];
}
// 多选题:兼容多种格式 —— "A||C||D" / "A,C,D" / "A、C、D" / "ACD" / "答案是 A 和 C"
if (type === Solver.TYPE_MULTI) {
// 先尝试 || 分隔
if (text.includes('||')) {
const parts = text.split('||').map(s => s.trim()).filter(Boolean);
if (parts.length > 0) return parts;
}
// 正则提取所有 A-Z 字母(去重,按字母顺序)
// 先做一次预处理:去掉常见 noise 词语("答案"/"选项"等)
const cleaned = text.replace(/答案|选项|正确|的?字母是?|应?该?选/g, ' ');
const letters = cleaned.match(/[A-Ha-h]/g);
if (letters && letters.length > 0) {
const uniq = [...new Set(letters.map(c => c.toUpperCase()))];
uniq.sort();
return uniq;
}
return [];
}
// 单选题:提取第一个字母
if (type === Solver.TYPE_SINGLE) {
const match = text.match(/[A-Ha-h]/);
if (match) return [match[0].toUpperCase()];
}
// 判断题
if (type === Solver.TYPE_JUDGE) {
if (/对|正确|√|true|是|right|yes/i.test(text)) return ['对'];
if (/错|错误|×|false|否|wrong|no/i.test(text)) return ['错'];
}
// 默认返回整个文本
return [text];
},
_parseBankAnswers(rawAnswers, success, options = []) {
if (!Array.isArray(rawAnswers) || rawAnswers.length === 0) return [];
const cleanList = list => list
.map(a => String(a))
.map(a => a.trim())
.filter(a => a);
if (typeof rawAnswers[0] === 'number') {
const uniqueIndices = [...new Set(rawAnswers)];
return uniqueIndices
.filter(idx => Number.isInteger(idx) && idx >= 0)
.map(idx => options[idx] || String.fromCharCode(65 + idx))
.filter(a => a);
}
if (success) {
return cleanList(rawAnswers);
}
const groups = Array.isArray(rawAnswers[0]) ? rawAnswers : [rawAnswers];
for (const group of groups) {
const cleaned = cleanList(Array.isArray(group) ? group : [group]);
if (cleaned.length > 0) return cleaned;
}
return [];
},
// 解析为 2D 答案组数组(用于智能匹配的投票),保留所有候选组
_parseBankAnswerGroups(rawAnswers, success, options = []) {
if (!Array.isArray(rawAnswers) || rawAnswers.length === 0) return [];
const cleanList = list => list.map(a => String(a)).map(a => a.trim()).filter(a => a);
// 数字索引 → 单组文本
if (typeof rawAnswers[0] === 'number') {
const uniqueIndices = [...new Set(rawAnswers)];
const texts = uniqueIndices
.filter(idx => Number.isInteger(idx) && idx >= 0)
.map(idx => options[idx] || String.fromCharCode(65 + idx))
.filter(a => a);
return texts.length ? [texts] : [];
}
// success: true,1D 文本 → 单组
if (success) {
const cleaned = cleanList(rawAnswers);
return cleaned.length ? [cleaned] : [];
}
// success: false,2D 文本 → 多个候选组
const raw2D = Array.isArray(rawAnswers[0]) ? rawAnswers : [rawAnswers];
return raw2D
.map(g => cleanList(Array.isArray(g) ? g : [g]))
.filter(g => g.length > 0);
},
// ---- 答题查询接口(供后续任务使用) ----
async askFreeBank(question, options, type) {
const canContinue = CXRequests.capture();
const empty = () => ({ answers: [], remaining: -1 });
let accessOk = false;
try { accessOk = await AccessGuard.requireFreeAnswerAccess(); } catch (_) {}
if (!accessOk || !canContinue()) return empty();
return new Promise((resolve) => {
const requestToken = ConfigStore.getVerifySessionToken();
const requestIdentity = AccessGuard._getSessionIdentity('free-answer', requestToken);
const _normQ = Solver._formatString(question);
if (_normQ !== question) {
Logger.log(`[免费题库] 已归一化题干: ${_normQ.slice(0, 30)}... (原: ${question.slice(0, 20)}...)`, 'info');
} else {
Logger.log(`[免费题库] 查询: ${question.slice(0, 30)}...`, 'info');
}
CXRequests.taskRequest({
method: 'POST',
url: 'http://103.236.88.53:23123/index.php?s=/api/code/free_answer',
headers: { 'Content-Type': 'application/json' },
// 与万能脚本 formatSearchAnswer 字段对齐 + formatString 归一化(去全角/HTML实体/尾标点)以提升缓存命中
data: JSON.stringify({
session_token: requestToken,
device_id: ConfigStore.getDeviceId(),
plat: null,
qid: null,
question: Solver._formatString(question),
options: (options || []).map(o => Solver._formatString(o)),
options_id: [],
type,
// 后台来源字段最多 100 个 UTF-8 字节,课程长链接不能直接传入。
location: '学习通'
}),
onload: (resp) => {
if (!canContinue() || !AccessGuard._isCurrentIdentity(requestIdentity)) { resolve(empty()); return; }
try {
const data = CXRequests.readJSON(resp);
if (data.result && typeof data.result === 'object') {
const rawAnswers = data.result.answers || [];
const success = data.result.success;
const finalAnswers = this._parseBankAnswers(rawAnswers, success, options);
const finalGroups = this._parseBankAnswerGroups(rawAnswers, success, options);
Logger.log(`[免费题库] 返回 ${finalAnswers.length} 个有效答案 (${finalGroups.length} 组候选)`, 'info');
resolve({ answers: finalAnswers, groups: finalGroups, remaining: -1 });
} else {
Logger.log('[免费题库] 返回缺少有效结果,未继续操作', 'error');
resolve(empty());
}
} catch (e) {
const rejected = e.status === 401 || e.status === 403 ||
e.status === 200 && e.businessCode === 0 && /验证码|授权|session|会话/i.test(e.message || '');
if (rejected && AccessGuard._isCurrentIdentity(requestIdentity)) {
ConfigStore.clearVerifySession();
this._updateFreeStatus(false, '验证码会话已被拒绝,请重新验证');
}
Logger.log('[免费题库] ' + (e.message || '响应解析失败'), 'error');
resolve(empty());
}
},
onerror: () => resolve(empty()),
ontimeout: () => { Logger.log('[免费题库] 请求超时,未自动重试', 'error'); resolve(empty()); },
onabort: () => resolve(empty())
});
});
},
async askPaidBank(question, options, type) {
const canContinue = CXRequests.capture();
const deviceId = ConfigStore.getDeviceId();
let credits = null;
try { credits = await this.getCredits(); } catch (_) {}
if (!canContinue() || deviceId !== ConfigStore.getDeviceId()) return { answers: [], remaining: -1 };
if (credits === null) {
Logger.log('积分余额暂时无法确认,请稍后刷新余额;本次未发起付费查询', 'error');
return { answers: [], remaining: -1 };
}
if (credits === 0) {
Logger.log('积分不足,请充值后再试', 'error');
return { answers: [], remaining: 0 };
}
return new Promise((resolve) => {
const _normQ = Solver._formatString(question);
if (_normQ !== question) {
Logger.log(`[付费题库] 已归一化题干(余${credits}积分): ${_normQ.slice(0, 30)}... (原: ${question.slice(0, 20)}...)`, 'info');
} else {
Logger.log(`[付费题库] 查询(余${credits}积分): ${question.slice(0, 30)}...`, 'info');
}
CXRequests.taskRequest({
method: 'POST',
url: 'http://103.236.88.53:23123/index.php?s=/api/question_bank/answer',
headers: { 'Content-Type': 'application/json' },
// 与万能脚本 formatSearchAnswer 字段对齐 + formatString 归一化(去全角/HTML实体/尾标点)以提升缓存命中
data: JSON.stringify({
device_id: ConfigStore.getDeviceId(),
plat: null,
qid: null,
question: Solver._formatString(question),
options: (options || []).map(o => Solver._formatString(o)),
options_id: [],
type,
location: '学习通'
}),
timeout: 15000,
onload: (resp) => {
if (!canContinue() || deviceId !== ConfigStore.getDeviceId()) { resolve({ answers: [], remaining: credits }); return; }
try {
const data = CXRequests.readJSON(resp);
if (data.result && typeof data.result === 'object') {
const remaining = this._readCreditAmount(data.remaining_credits) ?? credits;
const rawAnswers = data.result.answers || [];
const success = data.result.success;
const finalAnswers = this._parseBankAnswers(rawAnswers, success, options);
const finalGroups = this._parseBankAnswerGroups(rawAnswers, success, options);
Logger.log(`[付费题库] 返回 ${finalAnswers.length} 个有效答案 (${finalGroups.length} 组候选), 余${remaining}积分`, 'info');
this._updateCreditsDisplay(remaining);
resolve({ answers: finalAnswers, groups: finalGroups, remaining });
} else {
Logger.log('[付费题库] 返回缺少有效结果,未继续操作', 'error');
resolve({ answers: [], remaining: credits });
}
} catch (e) {
// 仅明确的预算拒绝才允许走原免费回退;网络异常不重发收费请求。
if (canContinue() && e.businessCode === 0 && e.status >= 200 && e.status < 300 &&
/系统积分|管理员充值/.test(e.message || '')) {
this._fallbackFreeQuery(question, options, type, credits, resolve)
.catch(() => resolve({ answers: [], remaining: credits }));
return;
}
Logger.log('[付费题库] ' + (e.message || '响应解析失败'), 'error');
resolve({ answers: [], remaining: credits });
}
},
onerror: () => {
Logger.log('[付费题库] 网络请求失败', 'error');
resolve({ answers: [], remaining: credits });
},
ontimeout: () => {
Logger.log('[付费题库] 请求超时,处理结果需确认,未自动重试', 'error');
resolve({ answers: [], remaining: credits });
},
onabort: () => resolve({ answers: [], remaining: credits })
});
});
},
async _fallbackFreeQuery(question, options, type, credits, resolve) {
const canContinue = CXRequests.capture();
const accessOk = await AccessGuard.requireFreeAnswerAccess();
if (!accessOk || !canContinue()) {
Logger.log('[免费题库回退] 免费验证码未验证或授权无效,已停止回退查询', 'error');
resolve({ answers: [], remaining: credits });
return;
}
const requestToken = ConfigStore.getVerifySessionToken();
const requestIdentity = AccessGuard._getSessionIdentity('free-answer', requestToken);
CXRequests.taskRequest({
method: 'POST',
url: 'http://103.236.88.53:23123/index.php?s=/api/code/free_answer',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({
session_token: requestToken,
device_id: ConfigStore.getDeviceId(),
plat: null,
qid: null,
question: Solver._formatString(question),
options: (options || []).map(o => Solver._formatString(o)),
options_id: [],
type,
location: '学习通'
}),
timeout: 15000,
onload: (freeResp) => {
if (!canContinue() || !AccessGuard._isCurrentIdentity(requestIdentity)) {
resolve({ answers: [], remaining: credits }); return;
}
try {
const freeData = CXRequests.readJSON(freeResp);
if (freeData.result && typeof freeData.result === 'object') {
const answers = freeData.result.answers || [];
const finalAnswers = this._parseBankAnswers(answers, freeData.result.success, options);
const finalGroups = this._parseBankAnswerGroups(answers, freeData.result.success, options);
if (finalAnswers.length > 0) {
Logger.log(`[免费题库回退] 查询成功,返回 ${finalAnswers.length} 个有效答案`, 'info');
resolve({ answers: finalAnswers, groups: finalGroups, remaining: credits });
return;
}
}
Logger.log('[免费题库回退] 未找到匹配答案', 'info');
resolve({ answers: [], remaining: credits });
} catch (e) {
const rejected = e.status === 401 || e.status === 403 ||
e.status === 200 && e.businessCode === 0 && /验证码|授权|session|会话/i.test(e.message || '');
if (rejected && AccessGuard._isCurrentIdentity(requestIdentity)) {
ConfigStore.clearVerifySession();
this._updateFreeStatus(false, '验证码会话已被拒绝,请重新验证');
}
Logger.log('[免费题库回退] 解析失败', 'error');
resolve({ answers: [], remaining: credits });
}
},
onerror: () => {
Logger.log('[免费题库回退] 网络请求失败', 'error');
resolve({ answers: [], remaining: credits });
},
ontimeout: () => {
Logger.log('[免费题库回退] 请求超时', 'error');
resolve({ answers: [], remaining: credits });
},
onabort: () => resolve({ answers: [], remaining: credits })
});
},
// ---- 跨 iframe 查找题目所在文档(作业/考试页通常嵌套在 iframe 里)----
_findQuizDoc() {
const sel = '.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId, .TiMu, .mark_table, .exam-sidebar, .leftItems, .questionList, .TiMu-list';
if (document.querySelector(sel)) return document;
const search = (doc, depth) => {
if (depth > 4) return null;
try {
const iframes = doc.querySelectorAll('iframe');
for (const iframe of iframes) {
try {
const idoc = iframe.contentDocument || iframe.contentWindow?.document;
if (!idoc) continue;
if (idoc.querySelector(sel)) return idoc;
const found = search(idoc, depth + 1);
if (found) return found;
} catch (_) { /* 跨域 iframe 忽略 */ }
}
} catch (_) {}
return null;
};
return search(document, 1) || document; // 兜底返回 document,避免后续 null 引用
},
// ---- 10.1 / 10.2 答题查询路由 ----
async _queryAnswer(question, options, type, images = []) {
switch (this._mode) {
case 'free': return this.askFreeBank(question, options, type);
case 'paid': return this.askPaidBank(question, options, type);
case 'ai': return this.askAI(question, options, type, images);
default: return { answers: [], remaining: -1 };
}
},
_canSubmitQuestions(containers, label) {
const complete = containers.length > 0 && Array.from(containers).every(container => this._isQuestionCompleted(container));
if (!complete) Logger.log(`${label}仍有未完成题目,已保留当前答案,请检查后手动提交`, 'error');
return complete;
},
_finishAnswerRun(runId = this._answerRunId) {
if (runId !== this._answerRunId) return;
CXRequests.cancelGroup('answer');
this._answering = false;
this._stopRequested = false;
this._answerRunId = null;
RunStateManager.finishModule('answer', runId);
UIPanel.setRunning(VideoModule._playing);
this._setAnswerButtonsRunning(false);
},
// ---- 10.1 作业自动答题 ----
async startHomework() {
if (RunStateManager._leaving) return;
if (this._answering) {
Logger.log('答题任务正在进行中', 'info');
return;
}
const doc = this._findQuizDoc();
const containers = Array.from(doc.querySelectorAll(
'.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId'
));
if (containers.length === 0) {
Logger.log('未检测到题目,请确认当前页面为作业页面(已搜索同源 iframe 子页面)', 'error');
return;
}
this._answering = true;
this._stopRequested = false;
this._answerGeneration++;
const runId = this._answerRunId = RunStateManager.startModule('answer');
this._totalQuestions = containers.length;
this._currentQuestion = 0;
UIPanel.setRunning(true);
UIPanel.setProgress(0, this._totalQuestions);
this._setAnswerButtonsRunning(true);
Logger.log(`检测到 ${this._totalQuestions} 道题目,开始答题...`, 'info');
let allAnswered = true;
try {
for (let i = 0; i < containers.length; i++) {
if (this._stopRequested) break;
this._currentQuestion = i + 1;
UIPanel.setProgress(this._currentQuestion, this._totalQuestions);
const container = containers[i];
if (this._isQuestionCompleted(container)) {
Logger.log(`第 ${i + 1} 题已完成,跳过`, 'info');
continue;
}
const ok = await this._processOneQuestion(container, i + 1);
if (this._stopRequested) break;
if (ok) await Solver._clickSubmit(container, () => !this._stopRequested && RunStateManager.isCurrentRun('answer', runId));
else allAnswered = false;
if (i < containers.length - 1 && !this._stopRequested) {
const delay = await this._getQuestionDelay();
if (this._stopRequested) break;
if (this._mode === 'ai' && delay > 10000) Logger.log(`AI模式冷却中,${Math.round(delay/1000)}秒后继续(解锁后可加速)...`, 'info');
await this._delay(delay);
}
}
if (this._stopRequested) {
Logger.log('答题已停止,已保留当前答案', 'info');
} else if (allAnswered && this._canSubmitQuestions(containers, '作业')) {
const submitted = await Solver._clickFinalSubmit(doc, '作业', () => !this._stopRequested && RunStateManager.isCurrentRun('answer', runId));
if (submitted) Logger.log('全部题目已作答,已尝试提交作业', 'success');
} else {
Logger.log('作业有未完成或处理失败的题目,未自动提交,请检查后继续', 'error');
}
} catch (e) {
Logger.log(`作业答题异常,未自动提交:${e.message || e}`, 'error');
} finally {
this._finishAnswerRun(runId);
}
},
// ---- 10.2 考试自动答题 ----
async startExam() {
if (RunStateManager._leaving) return;
if (this._answering) {
Logger.log('答题任务正在进行中', 'info');
return;
}
this._answering = true;
this._stopRequested = false;
this._answerGeneration++;
const runId = this._answerRunId = RunStateManager.startModule('answer');
UIPanel.setRunning(true);
this._setAnswerButtonsRunning(true);
try {
const switched = await this._trySwitchToFullPaperView();
if (this._stopRequested) return;
if (switched) {
await this._delay(800);
if (this._stopRequested) return;
Logger.log('✅ 已切换到整卷浏览模式', 'success');
}
const isPaginated = this._isExamPaginated();
Logger.log(`检测到考试布局: ${isPaginated ? '分页模式' : '整卷/列表模式'}`, 'info');
const complete = isPaginated
? await this._processExamPaginated()
: await this._processExamList();
if (this._stopRequested) {
Logger.log('答题已停止,已保留当前答案', 'info');
} else if (complete === true) {
const submitted = await Solver._clickFinalSubmit(this._findQuizDoc(), '考试/章测', () => !this._stopRequested && RunStateManager.isCurrentRun('answer', runId));
if (submitted) Logger.log('全部题目已作答,已尝试提交', 'success');
} else {
Logger.log('存在未完成题目或无法确认整卷已答完,未自动提交,请检查后继续', 'error');
}
} catch (e) {
Logger.log(`考试答题异常,未自动提交:${e.message || e}`, 'error');
} finally {
this._finishAnswerRun(runId);
}
},
// 在 doc 全文范围按文本查找可点击按钮(跨多种学习通模板)
_findButtonByText(doc, textPatterns) {
if (!doc) return null;
const sels = ['button', 'a', '[role="button"]', '.btn', '.Btn', '.jb_btn', '.Btn_blue_01', '.Btn_blue_02', '.el-button', '.ant-btn'];
let candidates = [];
try { candidates = Array.from(doc.querySelectorAll(sels.join(','))); } catch (_) {}
const patterns = textPatterns.map(t => String(t).replace(/\s+/g, ''));
for (const el of candidates) {
const text = ((el.innerText || el.textContent || '') + '').replace(/\s+/g, '');
const aria = (el.getAttribute('aria-label') || '').replace(/\s+/g, '');
if (!text && !aria) continue;
const matched = patterns.some(p => text === p || text.includes(p) || aria === p || aria.includes(p));
if (!matched) continue;
if (el.disabled) continue;
if (el.getAttribute('aria-disabled') === 'true') continue;
const cls = String(el.className || '');
if (/\b(disabled|is-disabled)\b/.test(cls)) continue;
// 视觉可见性兜底
try {
const style = el.ownerDocument && el.ownerDocument.defaultView
? el.ownerDocument.defaultView.getComputedStyle(el) : null;
if (style && (style.display === 'none' || style.visibility === 'hidden')) continue;
} catch (_) {}
return el;
}
return null;
},
// 尝试切换到「整卷浏览/整卷预览」模式 —— 整卷模式下所有题目一次性渲染,答题速度最快
async _trySwitchToFullPaperView() {
const doc = this._findQuizDoc();
const btn = this._findButtonByText(doc, ['整卷预览', '整卷浏览', '查看整卷', '整卷模式']);
if (!btn) return false;
Logger.log('🔍 检测到「整卷浏览」按钮,切换到整卷模式以加速答题...', 'info');
try { btn.click(); } catch (_) { return false; }
await this._delay(2500);
return true;
},
// 点击"下一题"按钮推进,返回是否成功
_clickNextQuestionButton() {
const doc = this._findQuizDoc();
const btn = this._findButtonByText(doc, ['下一题', '下一道', '下一个']);
if (!btn) return false;
try { btn.click(); return true; } catch (_) { return false; }
},
// 检测是否为分页模式考试
_isExamPaginated() {
// 分页模式:有侧边栏题号导航(跨 iframe 查找;兼容 chaoxing/xuexitong 多版本)
const doc = this._findQuizDoc();
const sidebarSel = '.exam-sidebar, .leftItems, .questionList, .TiMu-list, ' +
'.examPaperNum-list, .examNum-list, .markBox, .test-num-list, ' +
'.exam-paper-num, .examPaper, .questionStatus, .nav-list, .num-list';
const sidebar = doc.querySelector(sidebarSel);
if (sidebar) {
const navItems = sidebar.querySelectorAll('a, li, .item, .TiMu-item, .examNum, .quesNum, .questionItem, .examNumItem, .markItem, .examPaperNum-item');
if (navItems.length > 0) return true;
}
// 兜底:判断是否存在「下一题」按钮——这强烈暗示当前是分页/单页模式
if (this._findButtonByText(doc, ['下一题', '下一道'])) return true;
return false;
},
// 用题目ID或完整题干确认分页确实切换,不能把点击次数当成已完成题数。
_getExamQuestionKey(container) {
if (!container) return '';
const id = container.getAttribute?.('data-questionid') || container.getAttribute?.('data-id') || container.id;
const title = container.querySelector?.('.Zy_TItle, .mark_name, .question-title, .title');
const text = String(title?.textContent || container.innerText || container.textContent || '').trim();
return id ? `id:${id}|${text}` : text;
},
async _processExamPaginated() {
const doc = this._findQuizDoc();
const sidebarSel = '.exam-sidebar, .leftItems, .questionList, .TiMu-list, ' +
'.examPaperNum-list, .examNum-list, .markBox, .test-num-list, ' +
'.exam-paper-num, .examPaper, .questionStatus, .nav-list, .num-list';
const sidebar = doc.querySelector(sidebarSel);
const navItems = sidebar ? Array.from(sidebar.querySelectorAll(
'a, li, .item, .TiMu-item, .examNum, .quesNum, .questionItem, .examNumItem, .markItem, .examPaperNum-item'
)).filter(it => {
const text = String(it.innerText || it.textContent || '').trim();
return text.length > 0 && text.length < 30;
}) : [];
const knownTotal = navItems.length;
const totalLimit = knownTotal || 100;
this._totalQuestions = totalLimit;
this._currentQuestion = 0;
UIPanel.setProgress(0, totalLimit);
Logger.log(`检测到 ${knownTotal || '未知数量'} 道题目${knownTotal ? '' : '(无法确认总题数,完成后请手动检查提交)'}`, 'info');
const visited = new Set();
let allAnswered = true;
for (let i = 0; i < totalLimit; i++) {
if (this._stopRequested) return false;
const container = this._findCurrentExamQuestion(this._findQuizDoc());
const key = this._getExamQuestionKey(container);
if (!key || visited.has(key)) {
Logger.log('未找到新题目或题目切换失败,保留当前答案,停止自动提交', 'error');
return false;
}
visited.add(key);
this._currentQuestion = i + 1;
UIPanel.setProgress(i + 1, totalLimit);
// 检查题目本身,侧栏“已作答”标记不能证明多空题已填完整。
if (!this._isQuestionCompleted(container)) {
const ok = await this._processOneQuestion(container, i + 1);
if (!ok) allAnswered = false;
}
if (this._stopRequested) return false;
if (!this._isQuestionCompleted(container)) allAnswered = false;
if (knownTotal && visited.size === knownTotal) return allAnswered;
if (i === totalLimit - 1) return false;
let advanced = this._clickNextQuestionButton();
if (!advanced && navItems[i + 1]) {
try { navItems[i + 1].click(); advanced = true; } catch (_) {}
}
if (!advanced) {
Logger.log('未确认所有题目均已处理,请检查后手动提交', 'info');
return false;
}
const delay = await this._getQuestionDelay();
if (this._stopRequested) return false;
if (this._mode === 'ai' && delay > 10000) Logger.log(`AI模式冷却中,${Math.round(delay/1000)}秒后继续(解锁后可加速)...`, 'info');
await this._delay(delay);
let changed = false;
for (let waited = 0; waited <= 3000; waited += 300) {
if (this._stopRequested) return false;
const nextKey = this._getExamQuestionKey(this._findCurrentExamQuestion(this._findQuizDoc()));
if (nextKey && nextKey !== key) { changed = true; break; }
if (waited < 3000) await this._delay(300);
}
if (!changed) {
Logger.log('下一题未加载成功,已停止自动作答和提交,请检查页面', 'error');
return false;
}
}
return false;
},
// 列表/整卷模式:所有题目在同一页面
async _processExamList() {
const doc = this._findQuizDoc();
const containers = doc.querySelectorAll(
'.exam-main .questionLi, .exam-main .singleQuesId, .exam-main .multipleQuesId, ' +
'.exam-main .judgementQuesId, .exam-main .completionQuesId, ' +
'.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId, ' +
'.examItem, .questionItem, .examQ, .examQuestion, .subject-item, ' +
'.exam-paper-question, .question-item, .quesItem, .quesBody'
);
if (containers.length === 0) {
Logger.log('未检测到题目', 'error');
return false;
}
this._totalQuestions = containers.length;
this._currentQuestion = 0;
UIPanel.setProgress(0, this._totalQuestions);
Logger.log(`检测到 ${this._totalQuestions} 道题目`, 'info');
let allAnswered = true;
for (let i = 0; i < containers.length; i++) {
if (this._stopRequested) {
Logger.log('答题已停止', 'info');
return false;
}
this._currentQuestion = i + 1;
UIPanel.setProgress(this._currentQuestion, this._totalQuestions);
Logger.log(`正在处理第 ${this._currentQuestion}/${this._totalQuestions} 题`, 'info');
const container = containers[i];
// 跳过已作答题目
if (this._isQuestionCompleted(container)) {
Logger.log(`第 ${this._currentQuestion} 题已作答,跳过`, 'info');
continue;
}
const ok = await this._processOneQuestion(container, this._currentQuestion);
if (!ok) allAnswered = false;
// 题间延迟(AI模式:解锁后1.5秒,未解锁35秒;其他1-2秒)
if (i < containers.length - 1 && !this._stopRequested) {
const delay = await AnswerModule._getQuestionDelay();
if (this._stopRequested) return false;
if (AnswerModule._mode === 'ai' && delay > 10000) Logger.log(`AI模式冷却中,${Math.round(delay/1000)}秒后继续(解锁后可加速)...`, 'info');
await this._delay(delay);
}
}
return !this._stopRequested && allAnswered && this._canSubmitQuestions(containers, '考试/章测');
},
// 题库未命中时的 AI 兜底(仅在非 ai 模式下被调用;ai 模式本身已经走 askAI)
async _aiFallback(qData, questionLabel) {
const strategy = ConfigStore.getUnmatchedFallback();
if (strategy === 'skip') {
Logger.log(`${questionLabel} 题库未命中,按设置跳过`, 'info');
return null;
}
// 默认 ai 兜底
const cfg = ConfigStore.getAnswerConfig();
if (!cfg.aiApiKey) {
Logger.log(`🤖 ${questionLabel} 想用 AI 兜底但未配置 API Key,跳过(请在 AI 答题模式中保存 API Key)`, 'info');
return null;
}
if (!Array.isArray(qData.options) || qData.options.length === 0) {
if (qData.type !== Solver.TYPE_FILL && qData.type !== Solver.TYPE_JUDGE && !(qData.images || []).length) {
Logger.log(`🤖 ${questionLabel} 想用 AI 兜底但选项为空,跳过`, 'info');
return null;
}
}
try {
const typeMap = { 0: '单选题', 1: '多选题', 2: '填空题', 3: '判断题', 4: '其他' };
Logger.log(`🤖 ${questionLabel} 题库未命中,调用 AI 兜底(题型: ${typeMap[qData.type] || '未知'})...`, 'info');
const aiResult = await this.askAI(qData.question, qData.options || [], qData.type, qData.images || []);
if (aiResult && Array.isArray(aiResult.answers) && aiResult.answers.length > 0) {
Logger.log(`🤖 ${questionLabel} AI 返回 ${aiResult.answers.length} 个答案:${aiResult.answers.join(' / ')}`, 'success');
return aiResult.answers;
}
Logger.log(`🤖 ${questionLabel} AI 未返回有效答案,跳过`, 'info');
return null;
} catch (err) {
Logger.log(`🤖 ${questionLabel} AI 兜底失败:${err.message || err}`, 'error');
return null;
}
},
// 选择并应用答案(智能匹配 + AI 兜底)
// 返回 true 表示成功作答,false 表示跳过
async _applyAnswer(qData, container, questionLabel, bankResult, canContinue = () => !this._stopRequested) {
if (!canContinue()) return false;
const pageOptions = (qData.options && qData.options.length > 0) ? qData.options : Solver._extractOptions(container);
const type = (qData.type !== undefined) ? qData.type : Solver._detectType(container);
// 填空题:直接填写
if (type === Solver.TYPE_FILL) {
const fillAnswers = (bankResult && bankResult.answers && bankResult.answers.length > 0) ? bankResult.answers : null;
let answers = fillAnswers;
if (!answers) {
answers = await this._aiFallback(qData, questionLabel);
}
if (!canContinue()) return false;
if (!answers || answers.length === 0) {
Logger.log(`${questionLabel} 填空题无答案,跳过`, 'error');
return false;
}
// _fillBlanks 会保留用户已有内容,并在写入后重新核实所有有效输入框。
// API 只返回部分答案时允许先填入已有部分,但不能谎报为已完成。
return Solver._fillBlanks(answers, container);
}
// 选择题:先用智能匹配
const groups = (bankResult && Array.isArray(bankResult.groups) && bankResult.groups.length > 0)
? bankResult.groups
: (bankResult && Array.isArray(bankResult.answers) && bankResult.answers.length > 0 ? [bankResult.answers] : []);
let matchedIndices = groups.length > 0 ? Solver.matchAnswerSmart(groups, pageOptions, type) : [];
// 智能匹配失败 → 兼容旧的 matchAnswer 再试一次
if (matchedIndices.length === 0 && bankResult && bankResult.answers && bankResult.answers.length > 0) {
matchedIndices = Solver.matchAnswer(bankResult.answers, pageOptions);
}
// 仍然失败 → AI 兜底(若策略为 skip 或未配置 Key 则跳过本题,绝不随机猜)
if (matchedIndices.length === 0) {
const strategy = ConfigStore.getUnmatchedFallback();
if (strategy === 'ai') {
const aiAnswers = await this._aiFallback(qData, questionLabel);
if (!canContinue()) return false;
if (aiAnswers && aiAnswers.length > 0) {
matchedIndices = Solver.matchAnswerSmart([aiAnswers], pageOptions, type);
if (matchedIndices.length === 0) {
matchedIndices = Solver.matchAnswer(aiAnswers, pageOptions);
}
}
}
}
if (matchedIndices.length === 0) {
Logger.log(`${questionLabel} 答案匹配失败,跳过`, 'error');
return false;
}
if (!canContinue() || Solver._selectOptions(matchedIndices, container, type) === false) return false;
// CSS 选中态可能由页面异步更新。只读回状态,不重复点击导致反选;
// 目标缺选或仍有多余选项都不能放行整卷提交。
for (let attempt = 0; attempt <= 12; attempt++) {
if (!canContinue()) return false;
if (Solver._areOptionsSelected(container)) return true;
if (attempt < 12) await this._delay(100);
}
return false;
},
// 处理单道题目(考试模式共用)
async _processOneQuestion(container, questionNum) {
const label = `第 ${questionNum} 题`;
const generation = this._answerGeneration;
const canContinue = () => this._answering && !this._stopRequested &&
generation === this._answerGeneration && container?.isConnected !== false &&
RunStateManager.isCurrentRun('answer', this._answerRunId);
try {
if (!canContinue()) return false;
const qData = await Solver.recognize(container, { canContinue });
if (!qData.question) {
Logger.log(`${label} 识别失败,跳过`, 'error');
return false;
}
if (!canContinue()) return false;
// 查询答案(题库 / AI 模式)
const bankResult = await this._queryAnswer(qData.question, qData.options, qData.type, qData.images || []);
if (!canContinue()) return false;
// 智能选择并应用答案(无命中自动 AI 兜底)
const ok = await this._applyAnswer(qData, container, label, bankResult, canContinue);
if (!canContinue()) return false;
const complete = ok && this._isQuestionCompleted(container);
if (complete) Logger.log(`${label} 已作答`, 'success');
else Logger.log(`${label} 未完整填写,保留当前答案`, 'error');
return !!complete;
} catch (e) {
Logger.log(`${label} 处理异常: ${e.message || e}`, 'error');
return false;
}
},
// 查找当前显示的考试题目容器(doc 参数允许指定 iframe 内的 document)
_findCurrentExamQuestion(doc) {
doc = doc || this._findQuizDoc();
// 分页模式下,当前显示的题目(旧版 chaoxing 类名)
const visible = doc.querySelector(
'.questionLi:not([style*="display: none"]):not([style*="display:none"]), ' +
'.singleQuesId:not([style*="display: none"]), ' +
'.multipleQuesId:not([style*="display: none"]), ' +
'.judgementQuesId:not([style*="display: none"]), ' +
'.completionQuesId:not([style*="display: none"])'
);
if (visible) return visible;
// 备选:查找 .exam-main 下的活跃题目
const active = doc.querySelector('.exam-main .active, .exam-main .current');
if (active) return active;
// 新版 xuexitong:尝试更多类名
const newSel = doc.querySelector('.examItem, .questionItem, .examQ, .examQuestion, .subject-item, .question-item, .quesItem, .quesBody, .exam-paper-question');
if (newSel) return newSel;
// 再备选:取第一个题目容器
return doc.querySelector('.questionLi, .singleQuesId, .multipleQuesId, .judgementQuesId, .completionQuesId');
},
// 检查题目是否已完成
_isQuestionCompleted(container) {
if (!container) return false;
// 填空题不能只看容器上的 is-checked:页面可能在第一空填写后就
// 添加该标记。必须确认所有有效可编辑答案框都非空。
let detectedType = null;
try { detectedType = Solver._detectType(container); } catch (_) {}
if (detectedType === Solver.TYPE_FILL) {
const inputs = typeof Solver._getFillInputs === 'function' ? Solver._getFillInputs(container) : [];
if (inputs.length === 0) return false;
return inputs.every(input => String(input.value == null ? '' : input.value).trim() !== '');
}
// 点击、重试和提交前检查使用同一套选项状态识别。
// 有本轮目标时必须全部吻合;用户原已填写的题目按平台已选状态识别。
if (Solver._selectionTargets.has(container)) return Solver._areOptionsSelected(container);
const pairs = Solver._extractOptionPairs(container);
return pairs.some(pair => Solver._isPairSelected(pair));
},
// 更新答题按钮状态
_setAnswerButtonsRunning(running) {
const doc = UIPanel._doc;
if (!doc) return;
const homeworkBtn = doc.getElementById('cx-btn-start-homework');
const examBtn = doc.getElementById('cx-btn-start-exam');
const stopBtn = doc.getElementById('cx-btn-stop-answer');
if (homeworkBtn) homeworkBtn.disabled = running;
if (examBtn) examBtn.disabled = running;
if (stopBtn) stopBtn.disabled = !running;
},
// 所有答题等待均可取消;停止只结束等待,不把旧任务提前标为可重启。
_delay(ms) {
if (this._stopRequested) return Promise.resolve(false);
const delay = Math.max(0, Number(ms) || 0);
const watchUnlock = this._mode === 'ai' && delay > 10000;
return new Promise(resolve => {
let settled = false;
let timer = null;
let poll = null;
const finish = (completed, unlocked = false) => {
if (settled) return;
settled = true;
if (timer !== null) clearTimeout(timer);
if (poll !== null) clearInterval(poll);
this._pendingDelays.delete(cancel);
if (unlocked) Logger.log('🚀 AI限速已解锁,提前结束当前冷却', 'success');
resolve(completed);
};
const cancel = () => finish(false);
this._pendingDelays.add(cancel);
timer = setTimeout(() => finish(true), delay);
if (watchUnlock && !settled) poll = setInterval(() => {
if (this._stopRequested) finish(false);
else if (__scriptVerificationV1.sessionValid('ai-unlock', ConfigStore.getDeviceId(), ConfigStore.getAIUnlockSessionToken(), ConfigStore.getAIUnlockUntil())) finish(true, true);
}, 500);
});
},
// ---- 9.4 UI 相关 ----
_updateModeUI() {
const doc = UIPanel._doc;
if (!doc) return;
const mode = this._mode;
// 更新 radio 选中状态
doc.querySelectorAll('input[name="cx-answer-mode-tab"]').forEach(radio => {
radio.checked = radio.value === mode;
});
// 显示/隐藏对应配置区域
doc.getElementById('cx-answer-free-area').style.display = mode === 'free' ? 'block' : 'none';
doc.getElementById('cx-answer-paid-area').style.display = mode === 'paid' ? 'block' : 'none';
doc.getElementById('cx-answer-ai-area').style.display = mode === 'ai' ? 'block' : 'none';
},
// 答题状态
isAnswering() { return this._answering; },
getCurrentQuestion() { return this._currentQuestion; },
getTotalQuestions() { return this._totalQuestions; },
stopAnswering() {
this._answerGeneration++;
this._stopRequested = true;
CXRequests.cancelGroup('answer');
for (const cancel of Array.from(this._pendingDelays)) cancel();
RunStateManager.finishModule('answer', this._answerRunId);
UIPanel.setRunning(VideoModule._playing);
if (!VideoModule._playing) UIPanel.setStatus('已停止', 'info');
},
// 绑定答题模块事件
bindEvents() {
const doc = UIPanel._doc;
if (!doc) return;
// 模式切换(答题标签页内的 radio)
doc.querySelectorAll('input[name="cx-answer-mode-tab"]').forEach(radio => {
radio.addEventListener('change', (e) => {
this.setMode(e.target.value);
});
});
// 免费模式:验证按钮
doc.getElementById('cx-btn-verify')?.addEventListener('click', () => {
const code = doc.getElementById('cx-free-code')?.value?.trim();
if (!code || code.length !== 4) {
this._updateFreeStatus(false, '请输入4位验证码');
return;
}
this.verifyCode(code);
});
// 免费模式:回车键验证
doc.getElementById('cx-free-code')?.addEventListener('keypress', (e) => {
if (e.key === 'Enter') doc.getElementById('cx-btn-verify')?.click();
});
// 付费模式:激活按钮
doc.getElementById('cx-btn-activate')?.addEventListener('click', () => {
const code = doc.getElementById('cx-paid-code')?.value?.trim();
if (!code) {
this._showPaidStatus(false, '请输入激活码');
return;
}
this.activateCode(code);
});
// 付费模式:刷新积分
doc.getElementById('cx-btn-refresh-credits')?.addEventListener('click', () => {
this.getCredits();
Logger.log('正在查询积分余额...', 'info');
});
this._bindAISettings();
// 题库未命中兜底策略切换
const fallbackSelect = doc.getElementById('cx-unmatched-fallback');
if (fallbackSelect) {
fallbackSelect.addEventListener('change', () => {
ConfigStore.setUnmatchedFallback(fallbackSelect.value);
Logger.log(`兜底策略已切换为: ${fallbackSelect.value === 'ai' ? 'AI 兜底' : '跳过'}`, 'info');
});
}
// AI 模式:解锁按钮
const unlockBtn = doc.getElementById('cx-ai-unlock-btn');
const unlockCodeInput = doc.getElementById('cx-ai-unlock-code');
if (unlockBtn && unlockCodeInput) {
unlockBtn.addEventListener('click', async () => {
const code = unlockCodeInput.value.trim();
if (!code || code.length !== 4) {
const s = doc.getElementById('cx-ai-unlock-status');
if (s) { s.textContent = '❌ 请输入4位解锁码'; s.style.color = '#f56c6c'; }
return;
}
unlockBtn.disabled = true;
unlockBtn.textContent = '验证中...';
const unlockRequestSeq = (this._verificationRequests.get('ai-unlock')?.seq || 0) + 1;
try {
const result = await this._verifyAIUnlockCode(code);
if (result.success) {
unlockCodeInput.value = '';
Logger.log(`🚀 AI限速已解锁!有效期至 ${result.validUntilStr}`, 'success');
}
this._syncVerificationUI();
} catch (err) {
const s = doc.getElementById('cx-ai-unlock-status');
if (s && !err?.stale) { s.textContent = '❌ ' + (err.message || err); s.style.color = '#f56c6c'; }
} finally {
if ((this._verificationRequests.get('ai-unlock')?.seq || 0) <= unlockRequestSeq) {
unlockBtn.disabled = ConfigStore.isAIUnlocked();
unlockBtn.textContent = '解锁';
}
}
});
// 回车支持
unlockCodeInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') unlockBtn.click();
});
}
// 同步设置面板中的答题模式 radio
doc.querySelectorAll('input[name="cx-answer-mode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
this.setMode(e.target.value);
// 同步答题标签页的 radio
const tabRadio = doc.querySelector(`input[name="cx-answer-mode-tab"][value="${e.target.value}"]`);
if (tabRadio) tabRadio.checked = true;
});
});
// 作业答题按钮
doc.getElementById('cx-btn-start-homework')?.addEventListener('click', () => {
this.startHomework();
});
// 考试答题按钮
doc.getElementById('cx-btn-start-exam')?.addEventListener('click', () => {
this.startExam();
});
// 停止答题按钮
doc.getElementById('cx-btn-stop-answer')?.addEventListener('click', () => {
this.stopAnswering();
Logger.log('正在停止答题,已取消冷却等待...', 'info');
});
},
// AI 解锁验证
async _verifyAIUnlockCode(code) {
code = String(code || '').trim();
if (!/^\d{4}$/.test(code)) throw new Error('请输入4位数字解锁码');
const request = this._beginVerificationRequest('ai-unlock');
try {
const resp = await new Promise((resolve, reject) => CXRequests.request({
method: 'POST',
url: 'http://103.236.88.53:23123/index.php?s=/api/code/verify',
timeout: 25000,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: 'code=' + encodeURIComponent(code) + '&scope=ai-unlock&device_id=' + encodeURIComponent(request.identity.deviceId),
onload: resolve,
onerror: () => reject(new Error('解锁请求失败,处理结果需确认,请稍后重新检查')),
ontimeout: () => reject(new Error('解锁请求超时,验证码可能已被使用,请先重新检查会话')),
onabort: () => reject(new Error('解锁请求已取消,处理结果需确认'))
}, 'ui'));
const result = this._readVerificationResponse(resp, request);
// 校验和写入在同一同步步骤完成,旧设备或旧请求不能覆盖新凭据。
ConfigStore.setAIUnlockUntil(result.validUntil, code, result.sessionToken);
return result;
} catch (error) {
if (!this._isVerificationRequestCurrent(request)) throw this._verificationStaleError();
throw error;
}
},
// AI 草稿仅在保存时生效;搜索只筛选目录,不改动当前模型或配置。
_hasUnsavedAISettings() {
return Boolean(this._aiSettingsUI?.isDirty());
},
_bindAISettings() {
const doc = UIPanel._doc;
if (!doc?.getElementById('cx-ai-model-list')) return;
if (this._aiSettingsUI?.doc === doc) return;
this._aiSettingsUI?.dispose?.();
const get = id => doc.getElementById('cx-ai-' + id);
const providerEl = get('provider'), keyEl = get('apikey'), urlEl = get('custom-url');
const modelEl = get('custom-model'), listEl = get('model-list'), searchEl = get('model-search');
const fetchEl = get('fetch-models'), clearEl = get('search-clear'), visionEl = get('check-vision');
const connectionEl = get('test-connection'), statusEl = get('status');
const drafts = new Map(), catalogs = new Map(), pendingLists = new Map(), pendingVision = new Set(), pendingTests = new Set();
let activeProvider = ConfigStore.getAIProvider(), revision = 0, disposed = false;
const read = () => ({ provider: providerEl.value, apiKey: keyEl.value.trim(), model: modelEl.value.trim(), url: urlEl.value.trim() });
const sameConfig = (a, b) => ['provider', 'apiKey', 'model'].every(field => a[field] === b[field]) && (a.provider !== 'custom' || a.url === b.url);
const isDirty = () => !sameConfig(read(), ConfigStore.getAISettings());
const catalogKey = config => {
let endpoint = config.url;
try { endpoint = AISettingsService.resolveEndpoint(config); } catch (_) {}
return JSON.stringify([config.provider, endpoint, config.apiKey]);
};
const configKey = config => JSON.stringify([catalogKey(config), config.model]);
const normalize = text => String(text).normalize('NFKC').toLocaleLowerCase().trim();
const setStatus = (text, state = '') => { statusEl.textContent = text; statusEl.dataset.state = state; };
const clearErrors = () => [providerEl, keyEl, urlEl, modelEl].forEach(el => el.removeAttribute('aria-invalid'));
const validate = (config, requireModel = true) => {
clearErrors();
const result = AISettingsService.validateConfig(config, { requireModel });
if (!result.ok) {
const field = { provider: providerEl, apiKey: keyEl, model: modelEl, url: urlEl }[result.field];
if (field === modelEl) get('model-manual').open = true;
field?.setAttribute('aria-invalid', 'true'); field?.focus();
setStatus(result.error, 'error');
}
return result.ok;
};
const renderVision = () => {
const config = read(), identity = configKey(config), el = get('vision-status');
const result = AISettingsService.getVisionStatus(config);
visionEl.disabled = pendingVision.has(identity);
visionEl.textContent = visionEl.disabled ? '检测中…' : '检测当前模型';
el.dataset.state = '';
if (visionEl.disabled) { el.textContent = '正在验证当前模型能否读取图片…'; return; }
if (result) {
el.textContent = result.message;
el.dataset.state = result.status === 'supported' ? 'success' : result.status === 'unsupported' ? 'error' : '';
return;
}
const model = catalogs.get(catalogKey(config))?.models.find(item => item.id === config.model);
el.textContent = model?.vision === 'supported'
? '接口标注支持图片,尚未通过实际检测。'
: model?.vision === 'unsupported' ? '接口标注不支持图片;可手动检测确认。' : '尚未检测当前模型的图片能力。';
};
const renderModels = () => {
const config = read(), identity = catalogKey(config), catalog = catalogs.get(identity);
const terms = normalize(searchEl.value).split(/\s+/).filter(Boolean);
const models = catalog?.models || [];
const filtered = models.filter(item => terms.every(term => normalize(item.name + ' ' + item.id).includes(term)));
const selected = models.find(item => item.id === config.model);
listEl.replaceChildren();
const add = (value, label) => { const option = doc.createElement('option'); option.value = value; option.textContent = label; listEl.appendChild(option); };
if (!config.model) add('', '请选择模型,或手动填写模型 ID');
if (config.model && !filtered.some(item => item.id === config.model)) {
const suffix = selected ? '(当前选择,不在筛选结果中)' : '(当前模型)';
add(config.model, (selected?.name || config.model) + ' ' + suffix);
}
for (const model of filtered) add(model.id, model.name === model.id ? model.id : model.name + ' · ' + model.id);
listEl.value = config.model;
get('model-name').textContent = selected?.name || config.model || '尚未选择模型';
get('model-id').textContent = config.model ? 'ID:' + config.model : '点击“获取模型”,或展开下方手动填写。';
clearEl.disabled = !searchEl.value;
fetchEl.disabled = pendingLists.has(identity);
fetchEl.textContent = fetchEl.disabled ? '获取中…' : '获取模型';
const message = get('model-status');
message.dataset.state = catalog?.error ? 'error' : '';
if (fetchEl.disabled) message.textContent = '正在获取当前 Key 对应的模型列表…';
else if (catalog?.error) message.textContent = catalog.error;
else if (catalog) message.textContent = (terms.length ? `匹配 ${filtered.length} / 共 ${models.length} 个模型。` : `共 ${models.length} 个模型。`) + (catalog.message || '');
else message.textContent = '填写 API Key 后获取列表;部分服务需手动填写模型或接入点 ID。';
renderVision();
};
const renderEdited = ({ resetSearch = false } = {}) => {
revision++;
clearErrors();
if (resetSearch) searchEl.value = '';
drafts.set(activeProvider, read());
setStatus(isDirty() ? '配置尚未保存,答题使用前请先保存。' : '当前配置已保存。');
connectionEl.disabled = pendingTests.has(configKey(read()));
connectionEl.textContent = connectionEl.disabled ? '测试中…' : '测试连接';
renderModels();
};
const show = config => {
activeProvider = config.provider;
providerEl.value = config.provider; keyEl.value = config.apiKey; modelEl.value = config.model; urlEl.value = config.url;
keyEl.type = 'password'; get('key-toggle').textContent = '显示'; get('key-toggle').setAttribute('aria-pressed', 'false');
searchEl.value = '';
get('model-manual').open = !config.model;
this._updateAIProviderInfo(config.provider);
renderEdited();
};
providerEl.addEventListener('change', () => {
// activeProvider 仍是离开前的来源;不要把旧字段写进新来源草稿。
drafts.set(activeProvider, { ...read(), provider: activeProvider });
show(drafts.get(providerEl.value) || ConfigStore.getAISettings(providerEl.value));
});
keyEl.addEventListener('input', () => renderEdited({ resetSearch: true }));
urlEl.addEventListener('input', () => renderEdited({ resetSearch: true }));
modelEl.addEventListener('input', () => renderEdited());
searchEl.addEventListener('input', renderModels);
clearEl.addEventListener('click', () => { searchEl.value = ''; renderModels(); searchEl.focus(); });
listEl.addEventListener('change', () => { modelEl.value = listEl.value; renderEdited(); });
get('key-toggle').addEventListener('click', () => {
const reveal = keyEl.type === 'password'; keyEl.type = reveal ? 'text' : 'password';
get('key-toggle').textContent = reveal ? '隐藏' : '显示'; get('key-toggle').setAttribute('aria-pressed', String(reveal));
});
fetchEl.addEventListener('click', async () => {
const config = read();
if (!validate(config, false)) return;
const identity = catalogKey(config);
if (pendingLists.has(identity)) return;
const task = AISettingsService.listModels(config);
pendingLists.set(identity, task); renderModels();
try {
const result = await task;
if (catalogs.size >= 24 && !catalogs.has(identity)) catalogs.delete(catalogs.keys().next().value);
catalogs.set(identity, result);
} catch (error) {
catalogs.set(identity, { models: catalogs.get(identity)?.models || [], error: error.message || '获取模型失败,请手动填写模型 ID。' });
if (!disposed && identity === catalogKey(read())) get('model-manual').open = true;
} finally {
pendingLists.delete(identity);
if (!disposed && identity === catalogKey(read())) renderModels();
}
});
doc.getElementById('cx-btn-save-aikey').addEventListener('click', () => {
const config = read();
if (!validate(config)) return;
const saved = ConfigStore.setAISettings(config);
modelEl.value = saved.model; keyEl.value = saved.apiKey; urlEl.value = saved.url;
drafts.set(saved.provider, saved); revision++;
setStatus('配置已保存,答题将使用当前来源与模型。', 'success');
renderModels();
});
visionEl.addEventListener('click', async () => {
const config = read();
if (!validate(config)) return;
const identity = configKey(config);
if (pendingVision.has(identity)) return;
pendingVision.add(identity); renderVision();
try { await AISettingsService.checkVision(config, { force: true }); }
catch (_) { if (!disposed && identity === configKey(read())) get('vision-status').textContent = '检测未完成,请检查配置后重试。'; }
finally {
pendingVision.delete(identity);
if (!disposed && identity === configKey(read())) renderVision();
}
});
connectionEl.addEventListener('click', async () => {
const config = read();
if (!validate(config)) return;
const identity = configKey(config), startedRevision = revision;
if (pendingTests.has(identity)) return;
pendingTests.add(identity); connectionEl.disabled = true; connectionEl.textContent = '测试中…';
setStatus('正在测试当前模型连接…');
try {
const message = await AISettingsService.testConnection(config);
if (!disposed && revision === startedRevision && identity === configKey(read())) setStatus(message + (isDirty() ? ' 配置尚未保存。' : ''), 'success');
} catch (error) {
if (!disposed && revision === startedRevision && identity === configKey(read())) setStatus(error.message || '连接测试失败,请检查配置。', 'error');
} finally {
pendingTests.delete(identity);
if (!disposed && identity === configKey(read())) { connectionEl.disabled = false; connectionEl.textContent = '测试连接'; }
}
});
const onVisionStatus = () => { if (!disposed) renderVision(); };
window.addEventListener('cx-ai-vision-status', onVisionStatus);
this._aiSettingsUI = { doc, isDirty, load: () => { drafts.clear(); show(ConfigStore.getAISettings()); },
dispose: () => { disposed = true; window.removeEventListener('cx-ai-vision-status', onVisionStatus); } };
this._aiSettingsUI.load();
},
// 更新 AI 来源说明,仅使用预设文字和链接。
_updateAIProviderInfo(providerOverride) {
const doc = UIPanel._doc;
if (!doc) return;
const providerKey = providerOverride || ConfigStore.getAIProvider();
const info = AI_PROVIDERS[providerKey];
const infoEl = doc.getElementById('cx-ai-provider-info');
if (!infoEl) return;
const customConfig = doc.getElementById('cx-ai-custom-config');
if (providerKey === 'custom') {
infoEl.textContent = '连接 OpenAI 兼容的 Chat Completions 服务,来源、模型和 Key 分别保存。';
if (customConfig) customConfig.style.display = 'flex';
return;
}
if (customConfig) customConfig.style.display = 'none';
if (!info) return;
infoEl.innerHTML = `
前往官方平台获取 API Key
${info.keyHint}。可选模型和费用以当前账户开通情况为准。
`;
},
// 更新 AI 解锁状态
_verificationUISubscription: null,
_verificationUIRevision: 0,
_syncVerificationUI() {
const doc = UIPanel._doc;
if (!doc) return Promise.resolve();
const revision = ++this._verificationUIRevision;
const current = () => revision === this._verificationUIRevision && doc === UIPanel._doc;
const jobs = [];
const setFree = (valid, message) => { if (current()) this._updateFreeStatus(valid, message); };
if (!__scriptVerificationV1.required('free-answer')) {
setFree(null);
const status = doc.getElementById('cx-free-status');
if (status) { status.textContent = '当前无需验证码'; status.style.color = '#67c23a'; }
} else if (ConfigStore.isVerifyValid() && ConfigStore.getVerifySessionToken()) {
const identity = AccessGuard._getSessionIdentity('free-answer', ConfigStore.getVerifySessionToken());
const until = identity.validUntil;
if (__scriptVerificationV1.sessionValid('free-answer', identity.deviceId, identity.token, until)) {
setFree(true, new Date(until * 1000).toLocaleString('zh-CN'));
} else {
setFree(false, '验证码会话正在复核,请稍候');
jobs.push(Promise.resolve().then(() => AccessGuard.requireFreeAnswerAccess()).then(valid => {
if (!current() || !__scriptVerificationV1.required('free-answer')) return;
if (valid && AccessGuard._isCurrentIdentity(identity)) setFree(true, new Date(until * 1000).toLocaleString('zh-CN'));
else if (AccessGuard._isCurrentIdentity(identity) || !ConfigStore.getVerifySessionToken()) setFree(false, '验证码会话未通过复核或暂时无法确认,请重新检查');
}).catch(() => { if (current()) setFree(false, '验证码会话暂时无法复核,请稍后重试'); }));
}
} else {
setFree(null);
}
this._updateAIUnlockStatus();
if (__scriptVerificationV1.required('ai-unlock') && ConfigStore.isAIUnlocked() && ConfigStore.getAIUnlockSessionToken()) {
jobs.push(Promise.resolve().then(() => AccessGuard.requireAIUnlockAccess()).then(() => {
if (current()) this._updateAIUnlockStatus();
}).catch(() => { if (current()) this._updateAIUnlockStatus(); }));
}
return Promise.allSettled(jobs);
},
_updateAIUnlockStatus() {
const doc = UIPanel._doc;
if (!doc) return;
const wasScheduled = this._aiUnlockExpiryTimer !== null;
if (wasScheduled) clearTimeout(this._aiUnlockExpiryTimer);
this._aiUnlockExpiryTimer = null;
const statusEl = doc.getElementById('cx-ai-unlock-status');
const codeInput = doc.getElementById('cx-ai-unlock-code');
const unlockBtn = doc.getElementById('cx-ai-unlock-btn');
if (!__scriptVerificationV1.required('ai-unlock')) {
if (statusEl) { statusEl.textContent = '当前无需验证码'; statusEl.style.color = '#67c23a'; }
if (codeInput) codeInput.disabled = false;
if (unlockBtn) unlockBtn.disabled = false;
return;
}
// 只有真实会话已复核且仍在有效期内,才显示解锁并设置到期计时。
const localValid = ConfigStore.isAIUnlocked();
const until = ConfigStore.getAIUnlockUntil() || this._aiUnlockDisplayUntil;
const token = ConfigStore.getAIUnlockSessionToken();
const checked = localValid && token && until * 1000 > Date.now() && __scriptVerificationV1.sessionValid('ai-unlock', ConfigStore.getDeviceId(), token, until);
if (checked) {
this._aiUnlockDisplayUntil = until;
const dateStr = new Date(until * 1000).toLocaleString('zh-CN');
if (statusEl) { statusEl.innerHTML = `✅ 已解锁,有效期至 ${dateStr}(答题间隔≈1.5秒)`; }
if (codeInput) codeInput.disabled = true;
if (unlockBtn) unlockBtn.disabled = true;
this._aiUnlockExpiryTimer = setTimeout(() => this._updateAIUnlockStatus(),
Math.min(2147483647, Math.max(1, until * 1000 - Date.now())));
} else {
const expired = until > 0 && until * 1000 <= Date.now();
if (expired) this._aiUnlockDisplayUntil = until;
const message = localValid && token
? '⏳ 会话待复核或暂时无法确认,当前使用普通模式'
: expired ? '⏳ 解锁已过期,当前答题间隔35–37秒,请重新输入解锁码' : '⏳ 未解锁,当前答题间隔35–37秒';
if (statusEl) { statusEl.textContent = message; statusEl.style.color = '#e6a23c'; }
if (codeInput) codeInput.disabled = false;
if (unlockBtn) unlockBtn.disabled = false;
if (expired && wasScheduled) Logger.log('AI限速解锁已过期,恢复35–37秒答题间隔,请重新输入解锁码', 'info');
}
},
// 加载配置并恢复 UI 状态
loadConfig() {
const cfg = ConfigStore.getAnswerConfig();
if (!this._verificationUISubscription) this._verificationUISubscription = __scriptVerificationV1.subscribe(() => this._syncVerificationUI());
this._mode = cfg.mode || 'free';
this._updateModeUI();
// 恢复免费模式状态
if (this.isVerifyValid()) {
const validUntil = ConfigStore.normalizeValidUntil(cfg.verifyValidUntil);
const validUntilStr = new Date(validUntil * 1000).toLocaleString('zh-CN');
this._updateFreeStatus(true, validUntilStr);
}
// 恢复按来源保存的 AI 配置,加载和切换面板不会发送模型请求。
const doc = UIPanel._doc;
if (doc) {
this._bindAISettings();
this._aiSettingsUI?.load();
const fallbackSelect = doc.getElementById('cx-unmatched-fallback');
if (fallbackSelect) {
fallbackSelect.value = ConfigStore.getUnmatchedFallback();
}
this._syncVerificationUI();
}
// 同步设置面板中的答题模式
if (doc) {
const settingsRadio = doc.querySelector(`input[name="cx-answer-mode"][value="${this._mode}"]`);
if (settingsRadio) settingsRadio.checked = true;
}
// 如果是付费模式,查询积分
if (this._mode === 'paid') {
this.getCredits();
}
// 定期检查免费模式有效期
setInterval(() => this._checkFreeExpiry(), 60000);
}
};
// ==========================================
// 脚本入口 — 初始化流程 (12.1, 12.2, 12.3)
// ==========================================
/**
* 运行状态管理器 (12.2)
* 负责保存/恢复运行状态,控制自动化任务的开始/停止
*/
const RunStateManager = {
_timerInterval: null,
_resumeTimer: null,
_resumeCandidate: null,
_runs: new Map(),
_tabId: '',
_ownerId: '',
_leaving: false,
_lifecycleBound: false,
_preserveRunId: '',
_newId() {
try { return crypto.randomUUID(); } catch (_) {
return Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
}
},
_getTabId() {
if (this._tabId) return this._tabId;
try {
let id = sessionStorage.getItem('cx_run_tab_id_v2');
if (!id || !/^[a-zA-Z0-9-]{8,100}$/.test(id)) {
id = this._newId();
sessionStorage.setItem('cx_run_tab_id_v2', id);
}
this._tabId = id;
} catch (_) { /* 无标签页存储时仍允许手动运行,不自动恢复。 */ }
return this._tabId;
},
_readIdentity() {
const validId = value => /^\d{1,24}$/.test(String(value || '').trim()) ? String(value).trim() : '';
const read = doc => {
let params;
try { params = new URL(doc.location?.href || doc.URL || location.href).searchParams; } catch (_) {}
const value = names => {
for (const name of names) {
const param = validId(params?.get(name));
if (param) return param;
try {
const el = doc.getElementById(name) || doc.querySelector('input[name="' + name + '"]');
const result = validId(el?.value);
if (result) return result;
} catch (_) {}
}
return '';
};
return {
courseId: value(['courseId', 'courseid']),
clazzId: value(['clazzid', 'clazzId', 'classId', 'classid']),
uid: value(['uid', 'userId', 'userid', 'puid']),
cpi: value(['cpi'])
};
};
let docs = [document];
try { docs = CXUtils.listAccessibleDocs(document, 2); } catch (_) {}
const top = read(document);
let cookieUid = '';
try { cookieUid = validId(document.cookie.match(/(?:^|;\s*)_uid=([^;]*)/)?.[1]); } catch (_) {}
const candidates = docs.map(read).filter(item =>
(!top.courseId || !item.courseId || item.courseId === top.courseId) &&
(!top.clazzId || !item.clazzId || item.clazzId === top.clazzId));
const scopes = new Map();
for (const item of candidates) {
const courseId = top.courseId || item.courseId;
const clazzId = top.clazzId || item.clazzId;
const uid = cookieUid || top.uid || item.uid;
const cpi = top.cpi || item.cpi;
if (!courseId || !clazzId || (!uid && !cpi)) continue;
const account = uid ? 'uid:' + uid : 'cpi:' + cpi;
const scopeKey = CXUtils.hostFamily() + '|' + account + '|' + courseId + '|' + clazzId;
scopes.set(scopeKey, { courseId, clazzId, scopeKey });
}
return scopes.size === 1 ? [...scopes.values()][0] : null;
},
_context() {
const identity = this._readIdentity();
const tabId = this._getTabId();
return identity && tabId ? { ...identity, tabId, storageScope: identity.scopeKey + '|tab:' + tabId } : null;
},
_isFresh(state) {
const elapsed = Date.now() - Number(state?.lastActiveTime);
return Number.isFinite(elapsed) && elapsed >= 0 && elapsed <= 5 * 60 * 1000;
},
isCurrentRun(moduleName, runId) {
const state = this._runs.get(moduleName);
if (this._leaving || !state || state.runId !== runId) return false;
return !state.scopeKey || this._readIdentity()?.scopeKey === state.scopeKey;
},
startModule(moduleName) {
if (this._leaving || !['video', 'answer'].includes(moduleName)) return null;
this.cancelAutoResume(moduleName !== 'video');
if (!this._ownerId) this._ownerId = this._newId();
const context = this._context();
const previous = this._runs.get(moduleName);
if (previous && previous.scopeKey === (context?.scopeKey || '')) return previous.runId;
if (previous) this.finishModule(moduleName, previous.runId);
const state = {
schemaVersion: 2, status: 'running', activeModule: moduleName,
runId: this._newId(), ownerId: this._ownerId, tabId: context?.tabId || '',
scopeKey: context?.scopeKey || '',
storageScope: context ? context.storageScope + '|' + moduleName : '',
handoff: false, lastActiveTime: Date.now(), startTime: Date.now()
};
this._runs.set(moduleName, state);
ConfigStore.setRunState(state);
UIPanel.setRunning(true);
UIPanel.setStatus('运行中', 'success');
return state.runId;
},
cancelAutoResume(clearState = true) {
if (this._resumeTimer !== null) clearTimeout(this._resumeTimer);
this._resumeTimer = null;
const candidate = this._resumeCandidate;
this._resumeCandidate = null;
if (clearState && candidate) ConfigStore.clearRunState(candidate.runId, candidate.storageScope);
},
finishModule(moduleName, runId) {
if (moduleName === 'video') this.cancelAutoResume();
const state = this._runs.get(moduleName);
if (!state || (runId && state.runId !== runId)) return;
if (state.runId !== this._preserveRunId) ConfigStore.clearRunState(state.runId, state.storageScope);
this._runs.delete(moduleName);
},
stopModule() {
this.cancelAutoResume();
if (VideoModule._playing) VideoModule.stop();
if (AnswerModule._answering) AnswerModule.stopAnswering();
UIPanel.setRunning(false);
UIPanel.setStatus('已停止', 'info');
},
tryAutoResume() {
this.cancelAutoResume(false);
const context = this._context();
if (this._leaving || !context) return;
const answerState = ConfigStore.getRunState(context.storageScope + '|answer');
if (answerState?.handoff) {
ConfigStore.clearRunState(answerState.runId, answerState.storageScope);
Logger.log('答题模块需要手动重新启动', 'info');
}
const state = ConfigStore.getRunState(context.storageScope + '|video');
if (!state || state.status !== 'running' || !state.handoff || state.scopeKey !== context.scopeKey ||
state.tabId !== context.tabId || state.activeModule !== 'video') return;
if (!this._isFresh(state) || !ConfigStore.isStudyPurposeConfirmed()) {
ConfigStore.clearRunState(state.runId, state.storageScope);
return;
}
this._resumeCandidate = state;
UIPanel.switchTab('video');
this._resumeTimer = setTimeout(() => {
this._resumeTimer = null;
const candidate = this._resumeCandidate;
this._resumeCandidate = null;
const currentContext = this._context();
const current = candidate && ConfigStore.getRunState(candidate.storageScope);
if (this._leaving || !candidate || currentContext?.scopeKey !== candidate.scopeKey ||
currentContext.tabId !== candidate.tabId || !current?.handoff || current.runId !== candidate.runId ||
current.status !== 'running' || !this._isFresh(current) ||
!ConfigStore.isStudyPurposeConfirmed()) return;
// 先消费交接,再启动,旧恢复回调不能重复接管。
current.handoff = false;
current.ownerId = this._ownerId;
if (!ConfigStore.setRunState(current)) return;
VideoModule.start();
}, 1500);
},
keepAlive() {
if (this._leaving) return;
const context = this._context();
for (const [moduleName, owned] of this._runs) {
const active = moduleName === 'video' ? VideoModule._playing : AnswerModule._answering && !AnswerModule._stopRequested;
if (!active) { this.finishModule(moduleName, owned.runId); continue; }
if (owned.scopeKey && context?.scopeKey !== owned.scopeKey) {
if (moduleName === 'video') VideoModule.stop();
else AnswerModule.stopAnswering();
continue;
}
const state = ConfigStore.getRunState(owned.storageScope);
if (!state || state.ownerId !== this._ownerId || state.runId !== owned.runId || state.handoff) continue;
state.lastActiveTime = Date.now();
ConfigStore.setRunState(state);
}
},
initLifecycle() {
if (!this._ownerId) this._ownerId = this._newId();
let context = this._context();
// 复制标签页可能继承 sessionStorage;活动所有者从未交接时,复制页另取标签页 ID。
if (context && ['video', 'answer'].some(name => {
const state = ConfigStore.getRunState(context.storageScope + '|' + name);
return state && !state.handoff && state.ownerId !== this._ownerId;
})) {
try {
this._tabId = this._newId();
sessionStorage.setItem('cx_run_tab_id_v2', this._tabId);
} catch (_) { this._tabId = ''; }
}
if (this._timerInterval === null) this._timerInterval = setInterval(() => this.keepAlive(), 30000);
if (this._lifecycleBound) return;
this._lifecycleBound = true;
window.addEventListener('pagehide', event => {
if (this._leaving) return;
this.cancelAutoResume(false);
this._leaving = true;
clearInterval(this._timerInterval);
this._timerInterval = null;
const videoRun = this._runs.get('video');
const currentContext = this._context();
const saved = videoRun && ConfigStore.getRunState(videoRun.storageScope);
if (videoRun && VideoModule._playing && currentContext?.scopeKey === videoRun.scopeKey && saved?.runId === videoRun.runId &&
saved.ownerId === this._ownerId) {
saved.handoff = true;
saved.lastActiveTime = Date.now();
if (ConfigStore.setRunState(saved)) this._preserveRunId = saved.runId;
}
AnswerModule.stopAnswering();
VideoModule.stop();
if (event.persisted) {
CXRequests.cancelGroup('answer');
CXRequests.cancelGroup('video');
} else CXRequests.cancelAll();
});
window.addEventListener('pageshow', event => {
if (!event.persisted) return;
this._leaving = false;
this._preserveRunId = '';
this.initLifecycle();
this.tryAutoResume();
});
}
};
/**
* 脚本初始化 (12.1)
* 页面匹配 → DOM 就绪 → 读取配置 → 注入 UI → 绑定模块 → 恢复运行状态
*/
async function initScript() {
const initStart = Date.now();
try {
// 1. 页面匹配检查(@match 已过滤,此处仅做兜底)
const url = window.location.href;
if (!/chaoxing\.com|xuexitong\.com/i.test(url) && !/chaoxing|学习通|超星/i.test(document.title || '')) {
return; // 非超星页面,不初始化
}
if (_isMediaWorkerFrame) {
FrameMediaBridge.initWorker();
return;
}
FrameMediaBridge.initController();
// 2. 等待 DOM 就绪
if (!document.body) {
await new Promise(resolve => {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', resolve, { once: true });
} else {
resolve();
}
});
}
// 3. 读取配置
const videoCfg = ConfigStore.getVideoConfig();
const answerCfg = ConfigStore.getAnswerConfig();
Logger.log(`学习通刷课助手 v${SCRIPT_VERSION} 已加载`, 'success');
// 4. 注入 UI 面板
UIPanel.init();
// 4.5 获取公告
try {
CXRequests.request({
method: 'GET',
url: 'http://103.236.88.53:23123/index.php?s=/admin/unified_manage/scriptannouncementapi&script_id=chaoxing',
timeout: 5000,
onload: function(resp) {
try {
if (Number(resp.status) < 200 || Number(resp.status) >= 300 || !Number.isFinite(Number(resp.status))) return;
var res = JSON.parse(resp.responseText);
if (res.code === 1 && res.data && res.data.enabled) {
var _doc = UIPanel._doc;
if (!_doc) return;
var colors = { info: '#3b82f6', warning: '#f59e0b', error: '#ef4444', success: '#22c55e' };
var bgColors = { info: '#eff6ff', warning: '#fffbeb', error: '#fef2f2', success: '#f0fdf4' };
var c = colors[res.data.type] || '#3b82f6';
var bg = bgColors[res.data.type] || '#eff6ff';
var styleTag = _doc.createElement('style');
styleTag.textContent = '@keyframes cxNoticeIn{from{opacity:0;transform:translateY(-8px);}to{opacity:1;transform:translateY(0);}} @keyframes cxPulse{0%,100%{transform:scale(1);}50%{transform:scale(1.15);}}';
_doc.head.appendChild(styleTag);
var el = _doc.createElement('div');
el.className = 'cx-announcement';
el.style.cssText = 'width:100%;margin:0 0 8px;padding:9px 11px;border-radius:10px;font-size:12px;line-height:1.5;border:1px solid '+c+';background:'+bg+';color:#333;position:relative;';
var head = _doc.createElement('div');
head.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px;';
var title = _doc.createElement('div');
title.style.cssText = 'font-weight:700;font-size:13px;color:'+c+';display:flex;align-items:center;gap:6px;';
var pulse = _doc.createElement('span');
pulse.style.cssText = 'animation:cxPulse 1.5s infinite;display:inline-block;';
pulse.textContent = '📢';
title.appendChild(pulse);
title.appendChild(_doc.createTextNode(res.data.title || '公告'));
var close = _doc.createElement('button');
close.type = 'button';
close.setAttribute('aria-label', '关闭公告');
close.style.cssText = 'display:flex;align-items:center;justify-content:center;flex:0 0 22px;width:22px;height:22px;cursor:pointer;font-family:inherit;font-size:18px;line-height:1;color:#64748b;padding:0;border:0;border-radius:4px;background:transparent;';
close.textContent = '×';
close.onclick = function(){ el.style.display = 'none'; };
head.appendChild(title);
head.appendChild(close);
el.appendChild(head);
var contentBox = _doc.createElement('div');
contentBox.style.cssText = 'font-size:12px;color:#444;white-space:pre-wrap;overflow-wrap:anywhere;';
contentBox.textContent = res.data.content || '';
el.appendChild(contentBox);
var noticeImages = Array.isArray(res.data.images) ? res.data.images.slice() : [];
if (!noticeImages.length && res.data.image_url) noticeImages = [res.data.image_url];
noticeImages = noticeImages.map(function(url) {
try { return new URL(String(url || ''), 'http://103.236.88.53:23123/').href; } catch (_) { return ''; }
}).filter(Boolean);
if (noticeImages.length) {
var imageBox = _doc.createElement('div');
imageBox.style.cssText = 'display:grid;gap:8px;margin-top:10px;';
noticeImages.forEach(function(url) {
var img = _doc.createElement('img');
__scriptAnnouncementV2.prepareImage(img, url);
img.alt = '公告图片';
img.style.cssText = 'width:100%;max-height:220px;object-fit:contain;border-radius:8px;border:1px solid #e2e8f0;background:#fff;';
imageBox.appendChild(img);
});
el.appendChild(imageBox);
}
__scriptAnnouncementV2.enhance(el, res.data);
var body = _doc.querySelector('.cx-body');
if (body && body.firstChild) {
body.insertBefore(el, body.firstChild);
}
}
} catch(e) {}
}
});
} catch(e) {}
// 5. 绑定所有模块事件并加载配置
VideoModule.bindEvents();
AnswerModule.bindEvents();
AnswerModule.loadConfig();
// 加载视频配置到设置面板
const doc = UIPanel._doc;
if (doc) {
const rateSelect = doc.getElementById('cx-cfg-playback-rate');
if (rateSelect) rateSelect.value = String(videoCfg.playbackRate || 2);
const autoAdvance = doc.getElementById('cx-cfg-auto-advance');
if (autoAdvance) autoAdvance.checked = videoCfg.autoAdvance !== false;
const autoSkipQuiz = doc.getElementById('cx-cfg-auto-skip-quiz');
if (autoSkipQuiz) autoSkipQuiz.checked = videoCfg.autoSkipQuiz !== false;
const autoAnswerQuiz = doc.getElementById('cx-cfg-auto-answer-quiz');
if (autoAnswerQuiz) autoAnswerQuiz.checked = videoCfg.autoAnswerQuiz !== false;
const quizModeSelect = doc.getElementById('cx-cfg-quiz-mode');
if (quizModeSelect) {
quizModeSelect.value = videoCfg.quizMode || 'free';
quizModeSelect.disabled = videoCfg.autoAnswerQuiz === false;
}
// 同步内联视频设置控件
const rateInline = doc.getElementById('cx-video-rate-inline');
if (rateInline) rateInline.value = String(videoCfg.playbackRate || 2);
const advanceInline = doc.getElementById('cx-video-advance-inline');
if (advanceInline) advanceInline.checked = videoCfg.autoAdvance !== false;
const skipQuizInline = doc.getElementById('cx-video-skip-quiz-inline');
if (skipQuizInline) skipQuizInline.checked = videoCfg.autoSkipQuiz !== false;
const autoAnswerInline = doc.getElementById('cx-video-auto-answer-quiz-inline');
if (autoAnswerInline) autoAnswerInline.checked = videoCfg.autoAnswerQuiz !== false;
const quizModeInline = doc.getElementById('cx-video-quiz-mode-inline');
if (quizModeInline) {
quizModeInline.value = videoCfg.quizMode || 'free';
quizModeInline.disabled = videoCfg.autoAnswerQuiz === false;
}
}
// 6. 增强视频模块的 start/stop 以集成运行状态管理 (12.2)
const _origVideoStart = VideoModule.start.bind(VideoModule);
const _origVideoStop = VideoModule.stop.bind(VideoModule);
VideoModule.start = function() {
if (RunStateManager._leaving) return;
RunStateManager.cancelAutoResume(false);
_origVideoStart();
if (VideoModule._playing) {
RunStateManager.startModule('video');
}
};
VideoModule.stop = function() {
_origVideoStop();
RunStateManager.finishModule('video');
};
// 答题在真正进入任务时记账,并在 finally 收尾;续期只由本页拥有的实际任务执行。
RunStateManager.initLifecycle();
// 8. 检查保存的运行状态,决定是否自动恢复
RunStateManager.tryAutoResume();
const elapsed = Date.now() - initStart;
Logger.log(`初始化完成,耗时 ${elapsed}ms`, 'success');
} catch (err) {
console.error('[学习通刷课助手] 初始化错误:', err);
Logger.log('初始化失败: ' + (err.message || String(err)), 'error');
}
}
// 启动初始化
initScript();
})();
})();
// BEGIN script panel update bridge v1. Code is installed by the script manager, never evaluated here.
;(() => {
'use strict';
const config = {"base_url":"http://103.236.88.53:23123","name":"学习通刷课助手","namespace":"http://tampermonkey.net/","version":"1.6.2","key":"6fb6e49bd4b45abc370ff336","panel":"","header":"#cx-header","frame":"#cx-helper-iframe","theme":"dark"};
const CACHE_TTL = 30 * 60 * 1000;
const FAILURE_TTL = 5 * 60 * 1000;
const LEASE_TTL = 20 * 1000;
const INSTALL_PAGE = 'https://docs.scriptcat.org/docs/script_installation/#url=';
const VERSION = /^\d+(?:\.\d+){0,3}(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?(?![\s\S])/;
let info = {};
try { if (typeof GM_info === 'object' && GM_info) info = GM_info; } catch (_) {}
// The embedded identity stays stable even if a manager reports a localized display name.
const identity = {name: config.name, namespace: config.namespace};
const currentVersion = VERSION.test(String(info.script?.version || ''))
? String(info.script.version) : config.version;
const handler = String(info.scriptHandler || '');
const isOtherManager = Boolean(handler && !/scriptcat|脚本猫/i.test(handler));
const base = new URL(config.base_url.replace(/\/$/, '') + '/');
const endpoint = new URL('index.php', base);
const cacheKey = '__script_panel_update_v1_' + config.key;
const dismissKey = cacheKey + '_dismissed';
const leaseKey = cacheKey + '_lease';
const owner = Date.now().toString(36) + Math.random().toString(36).slice(2);
const bannerAttribute = 'data-script-panel-update';
const styleAttribute = 'data-script-panel-update-style';
let latest = null, inFlight = null, nextTimer = null, mountTimer = null;
let stopped = false, observer = null;
const watchedFrames = new WeakSet();
function read(key, fallback) {
try { return typeof GM_getValue === 'function' ? GM_getValue(key, fallback) : fallback; }
catch (_) { return fallback; }
}
function write(key, value) {
try { if (typeof GM_setValue === 'function') GM_setValue(key, value); } catch (_) {}
}
// Match the server's PHP version_compare policy, including numeric segment count.
function compareVersions(left, right) {
if (!VERSION.test(left) || !VERSION.test(right)) return null;
function parts(value) {
return value.split('+', 1)[0].replace(/[-_+]/g, '.')
.replace(/([^\d.])(\d)/g, '$1.$2').replace(/(\d)([^\d.])/g, '$1.$2').replace(/\.+/g, '.').split('.');
}
function rank(value) {
for (const [prefix, order] of [['dev',0],['alpha',1],['a',1],['beta',2],['b',2],['RC',3],['rc',3],['#',4],['pl',5],['p',5]]) {
if (value.startsWith(prefix)) return order;
}
return -1;
}
function number(value) {
value = value.replace(/^0+/, '') || '0';
const max = '9223372036854775807';
return value.length > max.length || value.length === max.length && value > max ? max : value;
}
const a = parts(left), b = parts(right);
let i = 0;
for (; i < a.length && i < b.length && a[i] !== '' && b[i] !== ''; i++) {
const an = /^\d+$/.test(a[i]), bn = /^\d+$/.test(b[i]);
let result;
if (an && bn) {
const x = number(a[i]), y = number(b[i]);
result = x.length !== y.length ? Math.sign(x.length - y.length) : x === y ? 0 : x > y ? 1 : -1;
} else {
result = Math.sign(rank(an ? '#' : a[i]) - rank(bn ? '#' : b[i]));
}
if (result) return result;
}
if (i < a.length) return /^\d/.test(a[i]) ? 1 : Math.sign(rank(a[i]) - rank('#'));
if (i < b.length) return /^\d/.test(b[i]) ? -1 : Math.sign(rank('#') - rank(b[i]));
return 0;
}
function validateDownload(value, sha256) {
if (typeof value !== 'string' || value.length > 4096 || /[\u0000-\u0020\u007f\\]/.test(value)) return null;
try {
const url = new URL(value);
if (url.origin !== base.origin || url.pathname !== endpoint.pathname || url.username || url.password || url.hash) return null;
const names = [...url.searchParams.keys()];
if (names.length !== 4 || new Set(names).size !== 4 || names.some(key => !['r','slug','sha256','filename'].includes(key))) return null;
const slug = url.searchParams.get('slug');
if (url.searchParams.get('r') !== 'script-install' || !/^[a-z][a-z0-9_-]{1,79}$/.test(slug || '')) return null;
if (url.searchParams.get('sha256') !== sha256 || url.searchParams.get('filename') !== slug + '.user.js') return null;
return url.href;
} catch (_) { return null; }
}
function validateManifest(data) {
if (!data || typeof data !== 'object' || Array.isArray(data) || typeof data.available !== 'boolean') return null;
if (!data.available) return {available:false};
if (data.name !== identity.name || data.namespace !== identity.namespace ||
typeof data.version !== 'string' || data.version.length > 80 || !VERSION.test(data.version) ||
typeof data.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(data.sha256) ||
typeof data.notes !== 'string' || data.notes.length > 8000) return null;
const downloadUrl = validateDownload(data.download_url, data.sha256);
if (!downloadUrl) return null;
return {available:true,name:data.name,namespace:data.namespace,version:data.version,
sha256:data.sha256,notes:data.notes,download_url:downloadUrl,
synced_at:Number.isFinite(data.synced_at) ? data.synced_at : 0};
}
function installUrl(manifest) { return INSTALL_PAGE + manifest.download_url; }
function openUpdate(manifest, status) {
if (!manifest || !validateDownload(manifest.download_url, manifest.sha256)) return;
const target = isOtherManager ? manifest.download_url : installUrl(manifest);
try {
if (typeof GM_openInTab === 'function') GM_openInTab(target, {active:true,insert:true});
else {
window.open(target, '_blank', 'noopener,noreferrer');
}
if (status) status.textContent = isOtherManager
? '已打开下载,请在脚本管理器导入并确认更新。' : '已打开脚本猫安装页,请确认更新;完成后刷新课程页面。';
} catch (_) {
if (status) status.textContent = '未能打开,请使用下方的安装链接。';
}
}
function documents() {
const result = [document];
try { if (window.top !== window && window.top.document && !result.includes(window.top.document)) result.push(window.top.document); } catch (_) {}
return result;
}
function targets() {
const result = [];
for (const doc of documents()) {
if (config.frame) {
const frame = doc.querySelector(config.frame);
if (frame && !watchedFrames.has(frame)) {
watchedFrames.add(frame);
frame.addEventListener('load', queueMount);
}
try {
const child = frame?.contentDocument;
const header = child?.querySelector(config.header);
if (header?.parentElement) result.push({doc:child,root:header.parentElement,header});
} catch (_) {}
} else {
const root = doc.querySelector(config.panel);
if (!root) continue;
const header = config.header ? root.querySelector(config.header) : null;
result.push({doc,root,header});
}
}
return result;
}
function addStyle(doc) {
if (doc.querySelector('style[' + styleAttribute + ']')) return;
const style = doc.createElement('style');
style.setAttribute(styleAttribute, 'v1');
style.textContent = `
[${bannerAttribute}]{box-sizing:border-box!important;flex:0 0 auto!important;margin:8px 12px!important;padding:10px 12px!important;border:1px solid #3b597e!important;border-radius:6px!important;background:#172c44!important;color:#e5efff!important;text-align:left!important;font:12px/1.65 system-ui,sans-serif!important;overflow-wrap:anywhere!important;}
[${bannerAttribute}] *{box-sizing:border-box!important;}
[${bannerAttribute}] .spu-row{display:flex!important;align-items:center!important;gap:8px!important;flex-wrap:wrap!important;}
[${bannerAttribute}] strong{flex:1 1 135px!important;font:600 12px/1.6 system-ui,sans-serif!important;color:inherit!important;}
[${bannerAttribute}] button{position:static!important;transform:none!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;flex:0 0 auto!important;width:auto!important;min-width:0!important;min-height:30px!important;margin:0!important;padding:4px 9px!important;border:1px solid #5274a0!important;border-radius:4px!important;background:#24476e!important;color:#fff!important;cursor:pointer!important;font:500 12px/1.5 system-ui,sans-serif!important;}
[${bannerAttribute}] button.spu-later{background:transparent!important;color:#d1def0!important;}
[${bannerAttribute}] button:hover{background:#31567f!important;}
[${bannerAttribute}] details{margin-top:6px!important;}
[${bannerAttribute}] summary{cursor:pointer!important;font-size:11px!important;color:#c5d8f2!important;}
[${bannerAttribute}] p{white-space:pre-wrap!important;margin:6px 0!important;color:inherit!important;font:11px/1.7 system-ui,sans-serif!important;}
[${bannerAttribute}] a{font:11px/1.7 system-ui,sans-serif!important;color:#c9dfff!important;text-decoration:underline!important;}
[${bannerAttribute}] :focus-visible{outline:2px solid #b6d5ff!important;outline-offset:3px!important;}
[${bannerAttribute}][data-theme=light]{background:#f1f6ff!important;color:#263b56!important;border-color:#a6bddc!important;}
[${bannerAttribute}][data-theme=light] summary,[${bannerAttribute}][data-theme=light] a{color:#284f83!important;}
[${bannerAttribute}][data-theme=light] .spu-later{color:#284f83!important;}
[${bannerAttribute}] [role=status]:empty{display:none!important;}
@media(prefers-reduced-motion:reduce){[${bannerAttribute}],[${bannerAttribute}] *{transition:none!important;animation:none!important;}}
`;
(doc.head || doc.documentElement).appendChild(style);
}
function clearBanners() {
for (const doc of documents()) {
doc.querySelectorAll('[' + bannerAttribute + '="' + config.key + '"]').forEach(node => node.remove());
if (config.frame) {
try { doc.querySelector(config.frame)?.contentDocument?.querySelectorAll('[' + bannerAttribute + '="' + config.key + '"]').forEach(node => node.remove()); } catch (_) {}
}
}
}
function mount() {
if (stopped || !latest?.available || compareVersions(latest.version, currentVersion) !== 1 || read(dismissKey, '') === latest.sha256) {
clearBanners(); return;
}
for (const {doc,root,header} of targets()) {
const existing = root.querySelector('[' + bannerAttribute + '="' + config.key + '"]');
if (existing?.getAttribute('data-sha256') === latest.sha256 &&
existing.getAttribute('data-version') === latest.version &&
(existing.querySelector('.spu-notes')?.textContent || '') === latest.notes) continue;
existing?.remove(); addStyle(doc);
const manifest = latest;
const box = doc.createElement('section');
box.setAttribute(bannerAttribute, config.key);
box.setAttribute('data-sha256', manifest.sha256);
box.setAttribute('data-version', manifest.version);
box.setAttribute('aria-label', '脚本更新');
if (config.theme === 'light') box.setAttribute('data-theme', 'light');
const row = doc.createElement('div'); row.className = 'spu-row';
const title = doc.createElement('strong'); title.textContent = '发现新版本 ' + manifest.version;
const update = doc.createElement('button'); update.type = 'button'; update.textContent = isOtherManager ? '下载新版' : '立即更新';
const later = doc.createElement('button'); later.type = 'button'; later.className = 'spu-later'; later.textContent = '稍后';
const status = doc.createElement('p'); status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
update.addEventListener('click', () => openUpdate(manifest, status));
later.addEventListener('click', () => {
write(dismissKey, manifest.sha256); setLatest(latest);
try { (header?.querySelector('button,a,[tabindex="0"]') || root.querySelector('button,a,[tabindex="0"]'))?.focus({preventScroll:true}); } catch (_) {}
});
row.append(title, update, later); box.append(row);
const details = doc.createElement('details'), summary = doc.createElement('summary');
summary.textContent = '更新说明'; details.append(summary);
if (manifest.notes) { const note = doc.createElement('p'); note.className = 'spu-notes'; note.textContent = manifest.notes; details.append(note); }
const hint = doc.createElement('p'); hint.textContent = isOtherManager
? '下载后在当前脚本管理器导入,并确认覆盖更新。' : '由脚本猫确认安装更新;完成后刷新课程页面。';
details.append(hint);
const link = doc.createElement('a'); link.href = isOtherManager ? manifest.download_url : installUrl(manifest);
link.target = '_blank'; link.rel = 'noopener noreferrer'; link.textContent = isOtherManager ? '下载脚本文件' : '打开安装确认页';
details.append(link); box.append(details, status);
if (header?.parentElement === root) header.insertAdjacentElement('afterend', box); else root.prepend(box);
}
}
function queueMount() {
if (mountTimer || stopped) return;
mountTimer = setTimeout(() => { mountTimer = null; mount(); }, 250);
}
function setLatest(manifest, showDismissed = false) {
latest = manifest;
if (showDismissed && manifest?.available) write(dismissKey, '');
if (manifest?.available && compareVersions(manifest.version, currentVersion) === 1 && read(dismissKey, '') !== manifest.sha256) {
if (!observer && typeof MutationObserver === 'function') {
observer = new MutationObserver(queueMount);
for (const doc of documents()) if (doc.documentElement) observer.observe(doc.documentElement, {childList:true,subtree:true});
}
} else { observer?.disconnect(); observer = null; }
mount();
}
function schedule(until) {
clearTimeout(nextTimer);
if (!stopped) nextTimer = setTimeout(() => { check(false).catch(() => {}); }, Math.max(1000, until - Date.now()));
}
function requestManifest() {
return new Promise((resolve, reject) => {
let settled = false;
const finish = (error, value) => { if (settled) return; settled = true; clearTimeout(timer); error ? reject(error) : resolve(value); };
const timer = setTimeout(() => finish(Error('timeout')), 12500);
const url = new URL(endpoint); url.searchParams.set('r', 'script-update');
url.searchParams.set('name', identity.name); url.searchParams.set('namespace', identity.namespace);
try {
if (typeof GM_xmlhttpRequest !== 'function') throw Error('unsupported manager');
GM_xmlhttpRequest({method:'GET',url:url.href,timeout:10000,anonymous:true,
onload:response => {
try {
if (Number(response.status) !== 200 || typeof response.responseText !== 'string' || response.responseText.length > 32768) throw Error('invalid response');
if (response.finalUrl && new URL(response.finalUrl).origin !== base.origin) throw Error('redirect rejected');
const body = JSON.parse(response.responseText);
const manifest = body.code === 1 ? validateManifest(body.data) : null;
if (!manifest) throw Error('invalid manifest');
finish(null, manifest);
} catch (error) { finish(error); }
},
onerror:() => finish(Error('network')),ontimeout:() => finish(Error('timeout')),onabort:() => finish(Error('aborted'))});
} catch (error) { finish(error); }
});
}
async function check(force = false) {
if (stopped) return {kind:'stopped'};
if (inFlight) return inFlight;
const cached = read(cacheKey, null), now = Date.now();
if (!force && cached && Number.isFinite(cached.until) && cached.until > now && cached.until <= now + CACHE_TTL) {
const manifest = validateManifest(cached.data);
if (manifest) { setLatest(manifest); schedule(cached.until); return {kind:cached.failed ? 'error' : 'ok',manifest}; }
}
const lease = read(leaseKey, null);
if (lease && lease.owner !== owner && lease.until > now && lease.until <= now + LEASE_TTL) {
schedule(lease.until + 500); return {kind:'waiting'};
}
write(leaseKey, {owner,until:now + LEASE_TTL});
inFlight = (async () => {
// Give sibling frames time to observe the short shared-storage lease.
await new Promise(resolve => setTimeout(resolve, 50));
try {
if (stopped) return {kind:'stopped'};
if (read(leaseKey, {owner}).owner !== owner) { schedule(Date.now() + LEASE_TTL); return {kind:'waiting'}; }
const manifest = await requestManifest(), until = Date.now() + CACHE_TTL;
write(cacheKey, {until,data:manifest,failed:false}); setLatest(manifest, force); schedule(until);
return {kind:'ok',manifest};
} catch (_) {
const until = Date.now() + FAILURE_TTL;
write(cacheKey, {until,data:{available:false},failed:true}); setLatest(null); schedule(until);
return {kind:'error'};
} finally {
if (read(leaseKey, null)?.owner === owner) write(leaseKey, {owner:'',until:0});
inFlight = null;
}
})();
return inFlight;
}
async function manualCheck() {
const result = await check(true);
if (result.kind === 'waiting') { window.alert('另一个页面正在检查更新,请稍后再试。'); return; }
if (result.kind !== 'ok') { window.alert('暂时无法检查更新,请稍后重试。现有脚本功能不受影响。'); return; }
const manifest = result.manifest;
if (!manifest.available || compareVersions(manifest.version, currentVersion) !== 1) {
window.alert('当前没有比 ' + currentVersion + ' 更高的面板更新。'); return;
}
setLatest(manifest, true);
if (targets().length) return;
const action = isOtherManager ? '下载脚本后,请在脚本管理器导入更新。' : '将打开脚本猫安装确认页,请确认覆盖更新。';
if (window.confirm('发现新版本 ' + manifest.version + '\n\n' + manifest.notes.slice(0, 1500) + '\n\n' + action)) openUpdate(manifest);
}
function start() {
if (typeof GM_registerMenuCommand === 'function') {
try { GM_registerMenuCommand('检查脚本更新', () => { manualCheck().catch(() => {}); }); } catch (_) {}
}
schedule(Date.now() + 500 + Math.floor(Math.random() * 1000));
document.addEventListener('visibilitychange', () => { if (!document.hidden) check(false).catch(() => {}); });
window.addEventListener('pagehide', event => {
if (event.persisted) return;
stopped = true; clearTimeout(nextTimer); clearTimeout(mountTimer); observer?.disconnect();
});
}
/* PANEL_UPDATE_TEST_HOOK */
start();
})();
// END script panel update bridge v1.