写在前面
前几天偶然看到了这个清朝工单。
我很疑惑,这玩意没人做个插件解决它吗?
嗯,有的兄弟,现在就有了()
代码部分由 AI 辅助完成,有错敬请打飞我的脸。
找人模式有点暴力,直接扫描整个排行榜,没找到就返回,懒得写二分。
代码
// ==UserScript==
// @name Luogu contest better!
// @namespace https://github.com/lcb-userscript
// @version 1.0.3
// @description 洛谷比赛增强:排行榜查人(动态显示)
// @match https://www.luogu.com.cn/*
// @match https://luogu.com.cn/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_addStyle
// @grant GM_notification
// @grant GM_registerMenuCommand
// @run-at document-idle
// @license MIT
// ==/UserScript==
(function () {
'use strict';
/* ================= 配置 ================= */
const CFG = Object.assign({
f1: true, // 排行榜查人
maxScanPages: 100, // 查人时最多扫描的排行榜页数(每页约100人)
}, GM_getValue('lcb_cfg', {}));
const saveCfg = () => GM_setValue('lcb_cfg', CFG);
GM_registerMenuCommand('排行榜查人:' + (CFG.f1 ? '开' : '关'), () => { CFG.f1 = !CFG.f1; saveCfg(); location.reload(); });
/* ================= 工具 ================= */
const now = () => Math.floor(Date.now() / 1000);
const log = (...a) => console.info('[LCB]', ...a);
async function fetchJSON(path, { lentille = false } = {}) {
const sep = path.includes('?') ? '&' : '?';
const url = path + sep + '_contentOnly=1';
const headers = {};
if (lentille) headers['x-lentille-request'] = 'content-only';
const res = await fetch(url, { headers, credentials: 'include' });
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
}
const unwrap = j => (j && (j.currentData || j.data)) || j || {};
function listItems(l) {
if (!l) return [];
const r = l.result;
if (Array.isArray(r)) return r;
if (r && typeof r === 'object') return Object.keys(r).map(k => r[k]);
return [];
}
function myUid() {
try {
const el = document.getElementById('lentille-context');
if (el) { const j = JSON.parse(el.textContent); if (j.user && j.user.uid) return j.user.uid; }
} catch (e) {}
return null;
}
const UID = myUid();
const apiScoreboard = (cid, page = 1) => fetchJSON(`/fe/api/contest/scoreboard/${cid}?page=${page}`);
const apiRecords = p => fetchJSON('/record/list?' + new URLSearchParams(p), { lentille: true }).then(unwrap);
function extractMeta(cd) {
const c = cd.contest || cd || {};
const cand = cd.problems || cd.contestProblems || c.problems || c.problemList || [];
const problems = [];
for (const e of cand) {
const p = (e && e.problem) || e || {};
const pid = p.pid || e.pid;
if (pid) problems.push({ pid, full: (e.score ?? e.fullScore ?? p.fullScore ?? null) });
}
return {
id: c.id, name: c.name || '', startTime: c.startTime || 0, endTime: c.endTime || 0,
ruleType: c.ruleType ?? c.type ?? null, problems
};
}
const isPassed = (meta, pid, score) => {
if (meta.ruleType === 2) return score >= 0;
const full = (meta.problems.find(p => p.pid === pid) || {}).full;
return full != null ? score >= full : score > 0;
};
/* ================= 样式 ================= */
GM_addStyle(`
#lcb-bar{margin:10px 0;padding:10px 12px;background:#fff;border:1px solid #ddd;border-radius:6px;display:flex;gap:8px;align-items:center;flex-wrap:wrap;font-size:14px}
#lcb-bar input{padding:5px 8px;border:1px solid #bbb;border-radius:4px;width:200px}
#lcb-bar button{padding:5px 12px;border:none;border-radius:4px;background:#3498db;color:#fff;cursor:pointer}
#lcb-bar button.sec{background:#8ea4b8}
#lcb-result{width:100%;display:none;margin-top:8px}
#lcb-result .card{background:#f6f8fa;border:1px solid #d6e0ea;border-radius:6px;padding:8px 10px}
#lcb-result .rk{font-size:20px;font-weight:700;color:#e67e22;margin-right:8px}
#lcb-result .chip{display:inline-block;margin:2px;padding:2px 8px;border-radius:10px;background:#e8f5e9;color:#2e7d32;font-size:12px}
#lcb-result .chip.fail{background:#eceff1;color:#90a4ae}
#lcb-toasts{position:fixed;top:12px;right:12px;z-index:2147483646;display:flex;flex-direction:column;gap:8px;max-width:340px}
.lcb-toast{background:rgba(33,51,66,.94);color:#fff;border-radius:8px;padding:10px 14px;font-size:14px;box-shadow:0 4px 14px rgba(0,0,0,.3);animation:lcb-in .3s ease}
.lcb-toast b{color:#ffd54a;font-size:18px}
#lcb-notices{position:fixed;bottom:16px;right:16px;z-index:2147483646;display:flex;flex-direction:column;gap:10px;width:320px}
.lcb-notice{background:#fff;border-left:4px solid #3498db;border-radius:6px;box-shadow:0 6px 20px rgba(0,0,0,.25);padding:12px 14px;font-size:13px;animation:lcb-in .35s ease}
.lcb-notice h4{margin:0 0 6px;font-size:14px;color:#2c3e50}
.lcb-notice a{color:#3498db;text-decoration:none}
.lcb-notice .close{float:right;cursor:pointer;color:#999}
#lcb-fx-layer{position:fixed;inset:0;pointer-events:none;z-index:2147483645}
#lcb-fx-banner{position:fixed;top:38%;left:0;right:0;text-align:center;pointer-events:none;z-index:2147483646;animation:lcb-pop .6s cubic-bezier(.2,1.6,.4,1)}
#lcb-fx-banner h1{font-size:64px;margin:0;color:var(--lcb-accent,#ffd54a);text-shadow:0 0 24px rgba(0,0,0,.45),0 4px 0 rgba(0,0,0,.3);letter-spacing:6px}
#lcb-fx-banner p{font-size:22px;color:#fff;text-shadow:0 2px 8px rgba(0,0,0,.6)}
@keyframes lcb-in{from{transform:translateX(60px);opacity:0}to{transform:none;opacity:1}}
@keyframes lcb-pop{0%{transform:scale(.2);opacity:0}100%{transform:scale(1);opacity:1}}
`);
/* ================= 排行榜查人 ================= */
function injectSearchBar(cid) {
if (document.getElementById('lcb-bar')) return;
const host = document.querySelector('.main-container') || document.querySelector('main') || document.body;
const bar = document.createElement('div'); bar.id = 'lcb-bar';
bar.innerHTML = `查询:<input id="lcb-q" placeholder="请输入用户名 / UID">
<button id="lcb-go">全场比赛查找</button>
<button id="lcb-fl" class="sec">过滤当前页</button>
<button id="lcb-rs" class="sec">清除</button>
<div id="lcb-result"></div>`;
host.insertBefore(bar, host.firstChild);
const input = bar.querySelector('#lcb-q'), result = bar.querySelector('#lcb-result');
const match = (item, q) => {
const u = item.user || {};
return String(u.uid) === q || (u.name || '').toLowerCase().includes(q.toLowerCase());
};
bar.querySelector('#lcb-go').onclick = async () => {
const q = input.value.trim(); if (!q) return;
result.style.display = 'block'; result.innerHTML = '<div class="card">正在查找中…(逐页扫描排行榜)</div>';
let pageSize = null;
for (let page = 1; page <= CFG.maxScanPages; page++) {
let sb; try { sb = await apiScoreboard(cid, page); } catch (e) { break; }
const items = listItems(sb.scoreboard);
if (pageSize == null) pageSize = items.length || 100;
if (!items.length) break;
const idx = items.findIndex(it => match(it, q));
if (idx >= 0) { renderRow(items[idx], (page - 1) * pageSize + idx + 1, sb.scoreboard.count); return; }
if (page * pageSize >= (sb.scoreboard.count || Infinity)) break;
result.firstChild.textContent = `查找中… 已扫描 ${page * pageSize} / ${sb.scoreboard.count || '?'} 人`;
}
result.innerHTML = '<div class="card">未找到该选手(选手可能未参赛)。</div>';
};
bar.querySelector('#lcb-fl').onclick = () => {
const q = input.value.trim().toLowerCase();
document.querySelectorAll('table tbody tr').forEach(tr => {
const a = tr.querySelector('a[href^="/user/"]');
tr.style.display = (!q || (a ? a.textContent.toLowerCase().includes(q) : tr.textContent.toLowerCase().includes(q))) ? '' : 'none';
});
};
bar.querySelector('#lcb-rs').onclick = () => {
result.style.display = 'none'; input.value = '';
document.querySelectorAll('table tbody tr').forEach(tr => tr.style.display = '');
};
function renderRow(item, rank, count) {
const u = item.user || {};
const chips = Object.entries(item.details || {}).map(([pid, d]) =>
`<span class="chip${(d.score ?? 0) > 0 || (d.score ?? -1) >= 0 ? '' : ' fail'}">${pid}:${d.score}${d.runningTime ? '(' + fmtT(d.runningTime) + ')' : ''}</span>`).join('');
result.innerHTML = `<div class="card"><span class="rk">#${rank}</span>
<a href="/user/${u.uid}" target="_blank"><b>${esc(u.name)}</b></a>
<span style="margin-left:8px">总分 ${item.score ?? 0} 罚时/耗时 ${fmtT(item.runningTime || 0)}</span>
<span style="color:#999">(共 ${count} 人)</span><br>${chips}</div>`;
}
}
const fmtT = s => { s = Math.floor(s); const h = s / 3600 | 0, m = (s % 3600) / 60 | 0, x = s % 60; return h ? `${h}h${m}m` : `${m}m${x}s`; };
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
function setupRanklistInjection(cid) {
const isRanklistView = () => {
if (!CFG.f1) return false;
// 匹配 URL hash (例如 #scoreboard 或 #ranklist)
if (/scoreboard|ranklist/i.test(location.hash)) return true;
// 兼容独立路径
if (location.pathname.includes('/ranklist')) return true;
// 兼容 Vue/React 等 SPA 标签页切换 (匹配激活状态的 Tab)
const activeTab = document.querySelector('.active[data-tab], .tab-item.active, .nav-item.active, [role="tab"][aria-selected="true"], .lg-tab-item.active, .lfe-tab-item.active');
if (activeTab && /排行榜|scoreboard|ranklist/i.test(activeTab.textContent || '')) return true;
return false;
};
const updateVisibility = () => {
const bar = document.getElementById('lcb-bar');
if (isRanklistView()) {
if (!bar) injectSearchBar(cid);
else bar.style.display = 'flex';
} else {
if (bar) bar.style.display = 'none';
}
};
updateVisibility();
window.addEventListener('hashchange', updateVisibility);
window.addEventListener('popstate', updateVisibility);
// 监听 DOM 变化以应对 SPA 内部无 hash 变化的标签切换
let debounceTimer;
const observer = new MutationObserver(() => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(updateVisibility, 300);
});
observer.observe(document.body, { childList: true, subtree: true });
}
/* ================= 路由 & 启动 ================= */
function saveMeta(cid, meta) {
GM_setValue('lcb_meta_' + cid, meta);
const idx = GM_getValue('lcb_metaindex', {}); idx[cid] = 1; GM_setValue('lcb_metaindex', idx);
}
const contestRunning = meta => !meta.endTime || now() < meta.endTime + 60;
function boot() {
const mC = location.pathname.match(/^\/contest\/(\d+)/);
const mP = location.pathname.match(/^\/problem\/([A-Za-z0-9]+)/);
if (mC) {
const cid = +mC[1];
(async () => {
let meta = null;
try { meta = extractMeta(unwrap(await fetchJSON('/contest/' + cid, { lentille: true }))); } catch (e) {}
if (!meta || !meta.id) {
try { meta = extractMeta(unwrap(JSON.parse(document.getElementById('lentille-context').textContent))); } catch (e) {}
}
if (!meta || !meta.id) meta = { id: cid, problems: [] };
saveMeta(cid, meta);
// 动态注入查人栏(修复 hash 路由与 SPA 标签切换问题)
setupRanklistInjection(cid);
if (CFG.f2 && contestRunning(meta)) startFxLoop(cid, meta);
if (CFG.f3 && UID) startRankWatcher(cid, null);
})();
}
if (mP && UID) {
let cid = null, meta = null;
try {
const cd = unwrap(JSON.parse(document.getElementById('lentille-context').textContent));
cid = cd.contest && cd.contest.id;
if (cid) meta = extractMeta(cd);
} catch (e) {}
if (!cid) {
const idx = GM_getValue('lcb_metaindex', {});
for (const k of Object.keys(idx)) {
const m = GM_getValue('lcb_meta_' + k);
if (m && m.startTime && now() < m.endTime) { cid = m.id; meta = m; }
}
}
if (cid) {
meta = meta && meta.id ? meta : (GM_getValue('lcb_meta_' + cid) || { id: cid, problems: [] });
if (CFG.f2 && contestRunning(meta)) startFxLoop(cid, meta);
if (CFG.f3) startRankWatcher(cid, mP[1]);
}
}
if (CFG.f4 && UID) startTicketWatcher();
}
boot();
})();错误反馈与修改
null