//@connect ' + L.hostname +
' 加到脚本头部注释里,否则请求会被管理器拦截。',
'#e53935'
);
}
/* =====================================================================
* 4. 日志:改成 DOM 增量追加(原来每次 addLog 都 join 全量 HTML 重设 innerHTML)
* ===================================================================== */
const Log = (() => {
let box = null;
const entries = []; // { text, color, html }
// 页面外壳会被整体替换(挂机页/主界面),缓存的节点失效时要重新取
const ensure = () => {
if (box && box.isConnected) return box;
box = el('log');
return box;
};
function autoScroll() {
const panel = D.querySelector('#tab-log .panel-body');
if (!box) return;
try {
box.scrollTop = box.scrollHeight;
if (panel) panel.scrollTop = panel.scrollHeight;
} catch (_) { /* ignore */ }
}
function node(entry) {
const span = D.createElement('span');
span.style.color = entry.color;
if (entry.html) span.innerHTML = entry.text;
else span.textContent = entry.text;
return span;
}
function append(entry) {
entries.push(entry);
if (entries.length > CONFIG.logLimit) entries.shift();
const host = ensure();
if (!host) return;
host.appendChild(node(entry));
while (host.children.length > CONFIG.logLimit) host.removeChild(host.firstChild);
autoScroll();
}
/** UI 挂载前产生的日志先缓存在内存里,挂载后一次性补渲染(否则前几条会凭空消失) */
function flush() {
const host = ensure();
if (!host) return;
host.textContent = '';
entries.forEach((entry) => host.appendChild(node(entry)));
autoScroll();
}
function add(text, color = '#333') {
const { hour, minute, second } = formatTime();
append({ text: `[${hour}:${minute}:${second}] ${text}`, color, html: false });
}
/** 少数几条日志确实需要 //
,单独走这个入口,避免正文被当 HTML 解析 */
function addHTML(html, color = '#333') {
const { hour, minute, second } = formatTime();
append({ text: `[${hour}:${minute}:${second}] ${html}`, color, html: true });
}
function clear() {
entries.length = 0;
const host = ensure();
if (host) host.textContent = '';
}
function dump() {
return entries.map((entry) => (entry.html
? entry.text.replace(/<[^>]+>/g, '')
: entry.text)).join('\n');
}
return { add, addHTML, clear, dump, autoScroll, flush };
})();
/* =====================================================================
* 5. 进度面板
* ===================================================================== */
const Progress = {
state: { name: '暂无任务', percent: 0, type: '-', detail: '等待任务开始' },
els: null,
init() {
if (this.els && this.els.name) return true;
this.els = {
name: el('progressTaskName'),
percent: el('progressTaskPercent'),
bar: el('progressBarFill'),
detail: el('progressTaskDetail'),
type: el('progressTaskType'),
};
return !!(this.els.name && this.els.percent && this.els.bar);
},
render() {
if (!this.init()) return;
const s = this.state;
this.els.name.textContent = s.name;
this.els.percent.textContent = `${s.percent}%`;
this.els.bar.style.width = `${s.percent}%`;
this.els.bar.setAttribute('aria-valuenow', String(s.percent));
if (this.els.detail) this.els.detail.textContent = s.detail;
if (this.els.type) this.els.type.textContent = `类型:${s.type}`;
},
update(patch = {}) {
this.state = Object.assign({}, this.state, patch);
this.state.percent = clampPercent(this.state.percent);
this.render();
},
reset(detail = '等待任务开始') {
this.update({ name: '暂无任务', percent: 0, type: '-', detail });
},
};
const taskName = (item) => {
if (!item) return '未命名任务';
if (item.name) return item.name;
const p = item.property || {};
return p.name || p.title || '未命名任务';
};
function report(typeLabel, item, percent, detail) {
Progress.update({
name: `[${typeLabel}] ${taskName(item)}`,
type: typeLabel,
percent,
detail,
});
}
/* =====================================================================
* 6. 页面外壳(只构建一次;原来每个 tab 都用 innerHTML 拼接 + base64 重排)
* ===================================================================== */
function shellHTML() {
const qr = CONFIG.assets.qr
? `
`
: '';
return `
学习通小助手
任务配置
任务列表
运行日志
学习进度
默认接 DeepSeek:https://api.deepseek.com/v1 + deepseek-chat,在
platform.deepseek.com 生成 Key 填进去即可,
也兼容 OpenAI、中转站、Ollama、vLLM 等 /chat/completions 端点。
填完点「保存」→「测试连接」→「AI 答题」打开开关。改 Key 不需要先清空:直接覆盖输入框点保存/测试即可,
输入框留空保存表示「不改动」;用过的 Key 会进右侧「历史 Key」下拉,随时切回;点「清空 Key」只清当前配置,历史仍在。
答案按「题干 + 选项」哈希缓存在本地,同一题只请求一次;置信度低于 ${CONFIG.ai.minConfidence}
时先问题库,题库没有答案才采用 AI 结果。
提示:Ctrl+1~4 切换面板
当前任务
暂无任务
0%
等待任务开始
`;
}
const BUTTON_CLASS = { DEFAULT: 'btn btn-default', SUCCESS: 'btn btn-success' };
/** 挂载 UI 并绑定一次事件(原脚本把 bind 写在 100ms 轮询里,重复绑定过多次) */
function mountShell() {
D.documentElement.innerHTML = shellHTML();
el('unrivalRate').value = state.rate;
el('token').value = state.token;
el('updateToken').onclick = () => {
const next = el('token').value.trim();
state.token = next;
GM.set('tikutoken', next);
Log.add(`题库 Token 已更新:${next || '(空)'}`, 'green');
};
el('updateRateButton').onclick = () => {
const next = normalizeRate(el('unrivalRate').value);
state.rate = next;
GM.set('unrivalrate', next);
Log.add(next > 0 ? `倍速已更新为 ${next}x,3 秒内生效` : '倍速为 0,将跳过所有视频', next > 0 ? 'green' : 'orange');
};
el('backGround').onclick = () => {
topSet('backNow', 1);
Log.add('挂机已激活,可以最小化页面了', 'green');
};
if (!CONFIG.backGround) el('fuckMeModeButton').style.display = 'none';
bindToggle('reviewModeButton', 'unrivalreview', 'unrivalReviewMode',
'复习模式已开启:已完成的视频也会重刷', '复习模式已关闭:已完成的视频自动跳过');
bindToggle('loopModeButton', 'unrivalloop', 'unrivalLoop',
'循环模式已开启:刷完最后一节会回到第一章第一节,并强制重刷已完成视频',
'循环模式已关闭:刷完最后一章就停下');
bindToggle('autoDoWorkButton', 'unrivaldowork', 'unrivalDoWork',
'自动做章节测试已开启', '自动做章节测试已关闭');
bindToggle('autoSubmitButton', 'unrivalautosubmit', 'unrivalAutoSubmit',
'达到正确率将自动提交', '不会自动提交,请手动提交');
bindToggle('autoSaveButton', 'unrivalautosave', 'unrivalAutoSave',
'未达正确率将自动保存', '不会自动保存,请手动操作');
restoreToggleStates();
bindAI();
bindTabs();
bindLogTools();
bindHotkeys();
Progress.render();
Log.flush(); // 补渲染挂载前缓存的日志
// 只启动一条中继:把 iframe 里的状态字符串搬到日志里(原来每次 doWork 都新建一条)
every(200, () => {
const info = topGet('unrivalWorkInfo', '');
if (info) {
Log.add(info, 'blue');
topSet('unrivalWorkInfo', '');
}
});
}
function restoreToggleStates() {
const restore = (id, key, message) => {
const node = el(id);
if (!node) return;
const on = topGet(key, '0') === '1';
node.setAttribute('class', on ? BUTTON_CLASS.SUCCESS : BUTTON_CLASS.DEFAULT);
if (on && message) Log.add(message, 'green');
};
restore('reviewModeButton', 'unrivalReviewMode', '复习模式已开启');
restore('loopModeButton', 'unrivalLoop', '循环模式已开启:刷完最后一节会回到第一章第一节');
restore('autoDoWorkButton', 'unrivalDoWork', '自动做章节测试已开启');
restore('autoSubmitButton', 'unrivalAutoSubmit');
restore('autoSaveButton', 'unrivalAutoSave');
}
function bindToggle(buttonId, storageKey, topKey, onText, offText) {
const button = el(buttonId);
if (!button) return;
button.onclick = () => {
const isOn = button.getAttribute('class') === BUTTON_CLASS.SUCCESS;
const next = isOn ? '0' : '1';
button.setAttribute('class', isOn ? BUTTON_CLASS.DEFAULT : BUTTON_CLASS.SUCCESS);
GM.set(storageKey, next);
topSet(topKey, next);
Log.add(isOn ? offText : onText, 'green');
};
}
function bindTabs() {
const items = Array.from(D.querySelectorAll('.tab-item'));
const panes = Array.from(D.querySelectorAll('.tab-content'));
const activate = (name) => {
const target = D.querySelector(`[data-tab="${name}"]`);
const pane = el(`tab-${name}`);
if (!target || !pane) return;
items.forEach((i) => i.classList.remove('active'));
panes.forEach((p) => p.classList.remove('active'));
target.classList.add('active');
pane.classList.add('active');
GM.set('lastSelectedTab', name);
if (name === 'log') setTimeout(() => Log.autoScroll(), 60);
};
items.forEach((item) => {
item.onclick = () => activate(item.dataset.tab);
});
const last = GM.get('lastSelectedTab', 'config');
if (last && last !== 'config') setTimeout(() => activate(last), 150);
state.activateTab = activate;
}
function bindLogTools() {
el('clearLogBtn').onclick = () => {
if (!W.confirm('确定清空日志?')) return;
Log.clear();
Log.add('日志已清空', 'green');
};
el('exportLogBtn').onclick = () => {
const blob = new Blob([Log.dump()], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = D.createElement('a');
a.href = url;
a.download = `学习通日志_${new Date().toISOString().replace(/[:.]/g, '-')}.txt`;
D.body.appendChild(a);
a.click();
D.body.removeChild(a);
URL.revokeObjectURL(url);
};
}
function bindHotkeys() {
D.addEventListener('keydown', (e) => {
if (!e.ctrlKey) return;
const map = { 1: 'config', 2: 'joblist', 3: 'log', 4: 'progress' };
const name = map[e.key];
if (!name) return;
e.preventDefault();
if (state.activateTab) state.activateTab(name);
});
}
function addJobRow(label, name) {
const box = el('joblist');
if (!box) return;
const wrap = D.createElement('div');
wrap.className = 'panel panel-default';
const body = D.createElement('div');
body.className = 'panel-body';
body.textContent = `[${label}] ${name}`;
wrap.appendChild(body);
box.appendChild(wrap);
}
/* =====================================================================
* 7. 知识卡片页(knowledge/cards)
* ===================================================================== */
function detectChromeVersion() {
if (IS_FF) return 999;
const m = UA.match(/Chrome\/(\d{2,3})/);
return m ? parseInt(m[1], 10) : 999;
}
function handleClosedChapter() {
if (!L.href.includes('knowledge/cards')) return true;
for (const span of D.getElementsByTagName('span')) {
if (!String(span.innerHTML).includes('章节未开放')) continue;
if (L.href.includes('ut=s')) {
L.href = L.href.replace('ut=s', 'ut=t').replace(/&cpi=[0-9]{1,10}/, '');
} else if (L.href.includes('ut=t')) {
span.innerHTML = '此课程为闯关模式,请回到上一章节完成学习任务!';
return false;
}
break;
}
return true;
}
/** 从内联