Luogu AC记录导出器
zhouhaoGG
·
·
个人记录
// ==UserScript==
// @name AC 提交记录导出器
// @namespace http://tampermonkey.net/
// @version 3.2
// @description 导出 AC 记录,Luogu 难度文字着色。
// @author zhouhaoGG
// @match https://www.luogu.com.cn/*
// @match https://codeforces.com/*
// @match https://mirror.codeforces.com/*
// @match https://atcoder.jp/*
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/exceljs.min.js
// @grant none
// ==/UserScript==
(function() {
'use strict';
// ==========================================
// 1. 公共工具
// ==========================================
function createButton(text, color = '#3498db') {
const btn = document.createElement('button');
btn.innerText = text;
btn.style.position = 'fixed';
btn.style.bottom = '20px';
btn.style.left = '20px';
btn.style.zIndex = '999999';
btn.style.padding = '10px 15px';
btn.style.backgroundColor = color;
btn.style.color = 'white';
btn.style.border = 'none';
btn.style.borderRadius = '5px';
btn.style.cursor = 'pointer';
btn.style.boxShadow = '0 2px 5px rgba(0,0,0,0.3)';
btn.style.fontWeight = 'bold';
btn.style.fontSize = '14px';
document.body.appendChild(btn);
return btn;
}
// 通用导出函数,支持为“难度”列文字着色
async function exportToExcel(data, filename, sheetName = "Accepted Records", difficultyFontColorMap = null) {
if (data.length === 0) {
alert('❌ 当前日期范围内没有找到 AC 记录!');
return;
}
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet(sheetName);
const columns = Object.keys(data[0]).map(key => ({ header: key, key: key }));
worksheet.columns = columns;
data.forEach(row => worksheet.addRow(row));
// 如果提供了难度文字颜色映射,则对难度列应用字体颜色
if (difficultyFontColorMap) {
const difficultyIndex = columns.findIndex(col => col.header === '难度') + 1;
if (difficultyIndex > 0) {
worksheet.eachRow((row, rowNumber) => {
if (rowNumber === 1) return; // 表头跳过
const cell = row.getCell(difficultyIndex);
const difficulty = cell.value;
if (difficulty && difficultyFontColorMap[difficulty]) {
cell.font = { color: { argb: difficultyFontColorMap[difficulty] } };
}
});
}
}
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
alert(`✅ 成功导出 ${data.length} 条记录!\n文件已保存为: ${filename}`);
}
function getStartDate() {
const input = prompt("请输入最早爬取日期 (格式: YYYY-MM-DD)\n留空则爬取所有历史记录:", "2026-01-01");
if (!input) return 0;
const timestamp = new Date(input).getTime() / 1000;
if (isNaN(timestamp)) {
alert("日期格式错误,将爬取所有记录。");
return 0;
}
return timestamp;
}
// ==========================================
// 2. 路由
// ==========================================
const host = window.location.hostname;
if (host.includes('luogu')) {
runLuogu();
} else if (host.includes('codeforces')) {
runCodeforces();
} else if (host.includes('atcoder')) {
runAtCoder();
}
// ==========================================
// 3. 洛谷 (Luogu)
// ==========================================
function runLuogu() {
const btn = createButton('📥 导出洛谷 AC', '#e74c3c');
// 难度 → 文字颜色(ARGB)
const difficultyFontColorMap = {
'暂无评定': 'FF909399',
'入门': 'FFFE4C61',
'普及-': 'FFF39C12',
'普及/提高-': 'FFFFC116',
'普及+/提高': 'FF52C41A',
'提高+/省选-': 'FF3498DB',
'省选/NOI-': 'FF9D3DCF',
'NOI/NOI+/CTSC': 'FF0E1D69'
};
const difficultyText = {
0: "暂无评定", 1: "入门", 2: "普及-", 3: "普及/提高-",
4: "普及+/提高", 5: "提高+/省选-", 6: "省选/NOI-", 7: "NOI/NOI+/CTSC"
};
btn.onclick = async () => {
let uid = null;
if (window._feInjection && window._feInjection.currentUser) {
uid = window._feInjection.currentUser.uid;
} else {
const userLink = document.querySelector('a[href^="/user/"]');
if (userLink) uid = userLink.href.match(/\/user\/(\d+)/)[1];
}
let inputUid = prompt("请输入要爬取的洛谷UID:", uid || "");
if (!inputUid) return;
uid = inputUid.trim();
const startTime = getStartDate();
let page = 1;
let rawRecords = [];
let keepRunning = true;
btn.innerText = '⏳ 爬取中...';
btn.disabled = true;
try {
while (keepRunning) {
btn.innerText = `⏳ 第 ${page} 页...`;
const url = `https://www.luogu.com.cn/record/list?user=${uid}&page=${page}&_contentOnly=1`;
const response = await fetch(url);
const json = await response.json();
if (!json.currentData || !json.currentData.records.result.length) break;
const pageRecords = json.currentData.records.result;
const lastRecordTime = pageRecords[pageRecords.length - 1].submitTime;
const validRecords = pageRecords.filter(r => r.submitTime >= startTime);
rawRecords.push(...validRecords);
if (lastRecordTime < startTime) {
keepRunning = false;
}
page++;
await new Promise(r => setTimeout(r, 800));
}
btn.innerText = '⏳ 处理数据...';
rawRecords.sort((a, b) => a.submitTime - b.submitTime);
const processedData = [];
const problemMap = {};
for (const rec of rawRecords) {
const pid = rec.problem.pid;
if (!problemMap[pid]) problemMap[pid] = { solved: false, attempts: 0 };
if (problemMap[pid].solved) continue;
problemMap[pid].attempts++;
if (rec.status === 12) {
problemMap[pid].solved = true;
const diffText = difficultyText[rec.problem.difficulty] || "未知";
processedData.push({
'时间': new Date(rec.submitTime * 1000).toLocaleString(),
'题目': `${rec.problem.pid} ${rec.problem.title}`,
'难度': diffText,
'尝试次数': problemMap[pid].attempts,
'分数': rec.score,
'语言': rec.language,
'ID': rec.id,
'链接': `https://www.luogu.com.cn/record/${rec.id}`
});
}
}
await exportToExcel(processedData, `Luogu_AC_${uid}.xlsx`, "Accepted Records", difficultyFontColorMap);
} catch (err) {
console.error(err);
alert('❌ 发生错误');
} finally {
btn.innerText = '📥 导出洛谷 AC';
btn.disabled = false;
}
};
}
// ==========================================
// 4. Codeforces
// ==========================================
function runCodeforces() {
const btn = createButton('📥 导出 CF AC', '#f39c12');
btn.onclick = async () => {
let handle = null;
const profileLink = document.querySelector('a[href^="/profile/"]');
if (profileLink) handle = profileLink.href.split('/').pop();
let inputHandle = prompt("请输入 Codeforces Handle:", handle || "");
if (!inputHandle) return;
handle = inputHandle.trim();
const startTime = getStartDate();
btn.innerText = '⏳ 获取中...';
btn.disabled = true;
try {
const url = `https://codeforces.com/api/user.status?handle=${handle}&from=1&count=100000`;
const response = await fetch(url);
const json = await response.json();
if (json.status !== 'OK') {
alert('API Error: ' + json.comment);
return;
}
const rawRecords = json.result
.filter(r => r.creationTimeSeconds >= startTime)
.reverse();
const processedData = [];
const problemMap = {};
for (const rec of rawRecords) {
const pid = `${rec.problem.contestId}${rec.problem.index}`;
if (!problemMap[pid]) problemMap[pid] = { solved: false, attempts: 0 };
if (problemMap[pid].solved) continue;
problemMap[pid].attempts++;
if (rec.verdict === 'OK') {
problemMap[pid].solved = true;
const tags = rec.problem.tags ? rec.problem.tags.join(', ') : '';
processedData.push({
'时间': new Date(rec.creationTimeSeconds * 1000).toLocaleString(),
'题目': `${pid} - ${rec.problem.name}`,
'难度': rec.problem.rating || '',
'算法标签': tags,
'尝试次数': problemMap[pid].attempts,
'语言': rec.programmingLanguage,
'ID': rec.id,
'链接': `https://codeforces.com/contest/${rec.contestId}/submission/${rec.id}`
});
}
}
await exportToExcel(processedData, `Codeforces_AC_${handle}.xlsx`);
} catch (e) {
console.error(e);
alert('❌ 网络错误');
} finally {
btn.innerText = '📥 导出 CF AC';
btn.disabled = false;
}
};
}
// ==========================================
// 5. AtCoder
// ==========================================
function runAtCoder() {
const btn = createButton('📥 导出 AC AC', '#2c3e50');
btn.onclick = async () => {
let user = typeof userScreenName !== 'undefined' ? userScreenName : "";
const inputUser = prompt("请输入 AtCoder 用户名:", user);
if (!inputUser) return;
user = inputUser.trim();
const startTime = getStartDate();
btn.innerText = '⏳ 获取题目数据...';
btn.disabled = true;
try {
const problemsUrl = 'https://kenkoooo.com/atcoder/resources/problem-models.json';
const problemsResp = await fetch(problemsUrl);
const problemModels = await problemsResp.json();
btn.innerText = '⏳ 获取提交记录...';
const url = `https://kenkoooo.com/atcoder/atcoder-api/v3/user/submissions?user=${user}&from_second=${startTime}`;
const response = await fetch(url);
if (response.status !== 200) throw new Error("API Failed");
let rawRecords = await response.json();
rawRecords = rawRecords.filter(r => r.epoch_second >= startTime);
rawRecords.sort((a, b) => a.epoch_second - b.epoch_second);
const processedData = [];
const problemMap = {};
for (const rec of rawRecords) {
const pid = rec.problem_id;
if (!problemMap[pid]) problemMap[pid] = { solved: false, attempts: 0 };
if (problemMap[pid].solved) continue;
problemMap[pid].attempts++;
if (rec.result === 'AC') {
problemMap[pid].solved = true;
let difficulty = '-';
if (problemModels[pid] && problemModels[pid].difficulty !== undefined) {
difficulty = problemModels[pid].difficulty;
}
processedData.push({
'时间': new Date(rec.epoch_second * 1000).toLocaleString(),
'题目': rec.problem_id,
'难度': difficulty,
'比赛': rec.contest_id,
'尝试次数': problemMap[pid].attempts,
'语言': rec.language,
'ID': rec.id,
'链接': `https://atcoder.jp/contests/${rec.contest_id}/submissions/${rec.id}`
});
}
}
await exportToExcel(processedData, `AtCoder_AC_${user}.xlsx`);
} catch (e) {
console.error(e);
alert('❌ 获取失败');
} finally {
btn.innerText = '📥 导出 AC AC';
btn.disabled = false;
}
};
}
})();