跳到正文

个人记录

洛谷首页显示At和Cf的比赛

csxx601cjy约 45 分钟
原文
文章信息与版本

文章信息

发布
2026年2月15日
收录
2026年2月15日
更新
2026年10月3日
篇幅
约 45 分钟

版本

  1. v3当前
  2. v2
  3. v1

我终于不用担心错过任何一场 ABC 了

——我

你需要安装油猴插件,然后把这段脚本粘贴进去。

显示效果

代码
JavaScript
// ==UserScript==
// @name         Luogu Contest Aggregator
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  在洛谷首页显示 AtCoder 和 Codeforces 比赛列表
// @author       Assistant
// @match        https://www.luogu.com.cn/
// @match        https://www.luogu.com.cn
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// @connect      codeforces.com
// @connect      atcoder.jp
// ==/UserScript==

(function() {
    'use strict';

    // 默认设置
    const DEFAULT_SETTINGS = {
        showAtCoder: true,
        showCodeforces: true,
        atCoderColor: "#ff8500", // lg-bg-orange
        codeforcesColor: "#0e90d2", // lg-bg-blue
        maxContests: 8
    };

    function getSettings() {
        return {
            showAtCoder: GM_getValue("showAtCoder", DEFAULT_SETTINGS.showAtCoder),
            showCodeforces: GM_getValue("showCodeforces", DEFAULT_SETTINGS.showCodeforces),
            atCoderColor: GM_getValue("atCoderColor", DEFAULT_SETTINGS.atCoderColor),
            codeforcesColor: GM_getValue("codeforcesColor", DEFAULT_SETTINGS.codeforcesColor),
            maxContests: GM_getValue("maxContests", DEFAULT_SETTINGS.maxContests)
        };
    }

    GM_addStyle(`
        #lg-contest-settings-btn {
            cursor: pointer;
            margin-left: 10px;
            font-size: 16px;
            color: #3498db;
            vertical-align: middle;
        }
        #lg-contest-settings-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0,0,0,0.3);
            z-index: 9999;
            width: 300px;
        }
        #lg-contest-settings-modal h3 { margin-top: 0; }
        .setting-item { margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between; }
        .setting-item input[type="text"], .setting-item input[type="number"] { width: 80px; }
        #lg-contest-settings-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 9998;
        }
        .setting-btns { margin-top: 20px; text-align: right; }
        .setting-btns button { padding: 5px 15px; cursor: pointer; border-radius: 4px; border: 1px solid #ccc; }
        .btn-save { background: #3498db; color: white; border: none !important; margin-left: 10px; }
    `);

    function createSettingsUI() {
        const settings = getSettings();
        const html = `
            <div id="lg-contest-settings-overlay"></div>
            <div id="lg-contest-settings-modal">
                <h3>比赛列表设置</h3>
                <div class="setting-item">
                    <label>显示 AtCoder</label>
                    <input type="checkbox" id="set-show-atcoder" ${settings.showAtCoder ? 'checked' : ''}>
                </div>
                <div class="setting-item">
                    <label>显示 Codeforces</label>
                    <input type="checkbox" id="set-show-cf" ${settings.showCodeforces ? 'checked' : ''}>
                </div>
                <div class="setting-item">
                    <label>AtCoder 颜色</label>
                    <input type="text" id="set-atcoder-color" value="${settings.atCoderColor}">
                </div>
                <div class="setting-item">
                    <label>Codeforces 颜色</label>
                    <input type="text" id="set-cf-color" value="${settings.codeforcesColor}">
                </div>
                <div class="setting-item">
                    <label>最大显示数量</label>
                    <input type="number" id="set-max-contests" value="${settings.maxContests}" min="1" max="50">
                </div>
                <div class="setting-btns">
                    <button id="set-cancel">取消</button>
                    <button id="set-save" class="btn-save">保存并刷新</button>
                </div>
            </div>
        `;
        document.body.insertAdjacentHTML('beforeend', html);

        const modal = document.getElementById('lg-contest-settings-modal');
        const overlay = document.getElementById('lg-contest-settings-overlay');

        document.getElementById('set-cancel').onclick = () => {
            modal.style.display = 'none';
            overlay.style.display = 'none';
        };

        document.getElementById('set-save').onclick = () => {
            GM_setValue("showAtCoder", document.getElementById('set-show-atcoder').checked);
            GM_setValue("showCodeforces", document.getElementById('set-show-cf').checked);
            GM_setValue("atCoderColor", document.getElementById('set-atcoder-color').value);
            GM_setValue("codeforcesColor", document.getElementById('set-cf-color').value);
            GM_setValue("maxContests", parseInt(document.getElementById('set-max-contests').value));
            location.reload();
        };
    }

    function showSettings() {
        document.getElementById('lg-contest-settings-modal').style.display = 'block';
        document.getElementById('lg-contest-settings-overlay').style.display = 'block';
    }10; // 在这里设置最多显示比赛数量

    // 格式化时间
    function formatTimeRemaining(ms) {
        const seconds = Math.floor(Math.abs(ms) / 1000);
        const days = Math.floor(seconds / 86400);
        const hours = Math.floor((seconds % 86400) / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);

        let res = "";
        if (days > 0) res += `${days}天`;
        if (hours > 0 || days > 0) res += `${hours}时`;
        res += `${minutes}分`;
        return res;
    }

    async function fetchCFContests() {
        return new Promise((resolve) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: "https://codeforces.com/api/contest.list",
                onload: function(response) {
                    try {
                        const data = JSON.parse(response.responseText);
                        if (data.status === "OK") {
                            const contests = data.result
                                .filter(c => c.phase === "BEFORE" || c.phase === "CODING")
                                .map(c => ({
                                    name: c.name,
                                    url: `https://codeforces.com/contests/${c.id}`,
                                    startTime: c.startTimeSeconds * 1000,
                                    endTime: (c.startTimeSeconds + c.durationSeconds) * 1000,
                                    platform: "Codeforces",
                                    platformUrl: "https://codeforces.com/",
                                    rated: !c.name.includes("unrated"),
                                    status: c.phase === "CODING" ? "进行中" : "未开始"
                                }));
                            resolve(contests);
                        } else {
                            resolve([]);
                        }
                    } catch (e) {
                        console.error("Failed to parse CF contests", e);
                        resolve([]);
                    }
                },
                onerror: () => resolve([])
            });
        });
    }

    async function fetchAtCoderContests() {
        return new Promise((resolve) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: "https://atcoder.jp/contests?lang=en",
                onload: function(response) {
                    try {
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(response.responseText, "text/html");
                        const contests = [];

                        const parseTable = (tableSelector, status) => {
                            const table = doc.querySelector(tableSelector + " tbody");
                            if (!table) return;
                            table.querySelectorAll("tr").forEach(tr => {
                                const tds = tr.querySelectorAll("td");
                                if (tds.length >= 2) {
                                    const timeA = tds[0].querySelector("a");
                                    let startTime = 0;
                                    if (timeA) {
                                        const href = timeA.getAttribute("href");
                                        const isoMatch = href.match(/iso=(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/);
                                        if (isoMatch) {
                                            const [_, y, m, d, hh, mm] = isoMatch;
                                            startTime = new Date(`${y}-${m}-${d}T${hh}:${mm}:00+09:00`).getTime();
                                        }
                                    }
                                    if (!startTime) {
                                        const timeStr = tds[0].querySelector("time")?.textContent || tds[0].textContent;
                                        startTime = new Date(timeStr).getTime();
                                    }

                                    const nameA = tds[1].querySelector("a");
                                    // AtCoder sometimes has icons before the name, get the last <a> or the one with contest link
                                    const contestLink = tds[1].querySelector("a[href^='/contests/']");
                                    const name = contestLink ? contestLink.textContent.trim() : (nameA ? nameA.textContent.trim() : "");
                                    const url = contestLink ? "https://atcoder.jp" + contestLink.getAttribute("href") : (nameA ? "https://atcoder.jp" + nameA.getAttribute("href") : "");

                                    const durationStr = tds[2]?.textContent.trim() || "02:00";
                                    const parts = durationStr.split(":");
                                    let durationMs = 0;
                                    if (parts.length === 2) {
                                        durationMs = (parseInt(parts[0]) * 3600 + parseInt(parts[1]) * 60) * 1000;
                                    }

                                    contests.push({
                                        name: name,
                                        url: url,
                                        startTime: startTime,
                                        endTime: startTime + durationMs,
                                        platform: "AtCoder",
                                        platformUrl: "https://atcoder.jp/",
                                        rated: tds[3]?.textContent.trim() !== "-",
                                        status: status
                                    });
                                }
                            });
                        };

                        parseTable("#contest-table-upcoming", "未开始");
                        parseTable("#contest-table-active", "进行中");

                        resolve(contests);
                    } catch (e) {
                        console.error("Failed to parse AtCoder contests", e);
                        resolve([]);
                    }
                },
                onerror: () => resolve([])
            });
        });
    }

    function parseLuoguContests() {
        const contests = [];
        // The container usually has a specific structure
        const h2 = Array.from(document.querySelectorAll("h2")).find(h => h.textContent.includes("近期比赛"));
        if (!h2) return [];

        const container = h2.parentElement;
        const contestSections = container.querySelectorAll("section.am-panel");
        console.log("[LuoguContestAggregator] Found potential sections in container:", contestSections.length);

        contestSections.forEach((section, index) => {
            const titleA = section.querySelector("h3 a, .am-panel-title a");
            const timeDisplay = section.querySelector(".lg-right, .am-panel-bd span.lg-right");

            if (!titleA) {
                console.log(`[LuoguContestAggregator] Section ${index}: No title found`);
                return;
            }

            if (!timeDisplay) {
                // Fallback: search for something that looks like a time
                const allSpans = Array.from(section.querySelectorAll("span"));
                const timeSpan = allSpans.find(s => s.innerText.match(/\d{2}-\d{2} \d{2}:\d{2}/));
                if (timeSpan) {
                    console.log(`[LuoguContestAggregator] Section ${index}: Found time via fallback`);
                    extractData(section, titleA, timeSpan);
                } else {
                    console.log(`[LuoguContestAggregator] Section ${index}: No time display found`);
                }
            } else {
                extractData(section, titleA, timeDisplay);
            }
        });

        function extractData(section, titleA, timeElement) {
            const text = timeElement.innerText;
            const timeMatches = text.match(/\d{2}-\d{2} \d{2}:\d{2}/g);

            if (timeMatches && timeMatches.length >= 2) {
                const year = new Date().getFullYear();
                const startTime = new Date(`${year}-${timeMatches[0]}`).getTime();
                const endTime = new Date(`${year}-${timeMatches[1]}`).getTime();

                if (!isNaN(startTime)) {
                    contests.push({
                        name: titleA.textContent.trim(),
                        url: new URL(titleA.getAttribute("href"), "https://www.luogu.com.cn").href,
                        startTime, endTime,
                        platform: "Luogu", platformUrl: "https://www.luogu.com.cn/",
                        rated: !!section.querySelector(".lg-bg-green"),
                        status: section.querySelector("strong")?.textContent.trim() || "",
                        originalHtml: section.outerHTML
                    });
                }
            } else {
                console.log(`[LuoguContestAggregator] Section ${titleA.textContent.trim()}: Time format mismatch: "${text}"`);
            }
        }

        return contests;
    }

    function formatDateToMMddHHmm(date) {
        // 检查传入的是否是有效的Date对象
        if (!(date instanceof Date) || isNaN(date.getTime())) {
            throw new Error('请传入有效的Date对象');
        }

        // 获取月份(月份从0开始,所以要+1),不足两位补0
        const month = String(date.getMonth() + 1).padStart(2, '0');
        // 获取日期,不足两位补0
        const day = String(date.getDate()).padStart(2, '0');
        // 获取小时,不足两位补0
        const hours = String(date.getHours()).padStart(2, '0');
        // 获取分钟,不足两位补0
        const minutes = String(date.getMinutes()).padStart(2, '0');

        // 拼接成指定格式
        return `${month}-${day} ${hours}:${minutes}`;
    }

    function renderContest(contest) {
        if (contest.platform === "Luogu" && contest.originalHtml) {
            return contest.originalHtml;
        }

        const settings = getSettings();
        const now = Date.now();
        let statusHtml = "";
        let panelClass = "am-panel-success";

        if (contest.status === "进行中" || (now >= contest.startTime && now <= contest.endTime)) {
            statusHtml = `<strong style="color:#0e90d2;">进行中</strong>`;
            panelClass = "am-panel-primary";
        } else if (now < contest.startTime) {
            const diff = contest.startTime - now;
            statusHtml = `<strong class="lg-fg-green">未开始</strong>&nbsp;${formatTimeRemaining(diff)}后`;
            panelClass = "am-panel-success";
        } else {
            const diff = now - contest.endTime;
            statusHtml = `<strong class="lg-fg-red">已结束</strong>&nbsp;${formatTimeRemaining(diff)}前`;
            panelClass = "am-panel-danger";
        }

        const ratedBadge = contest.rated ? `<span class="am-badge am-radius lg-bg-green">Rated</span>` : "";

        let platformBadgeStyle = "";
        if (contest.platform === "AtCoder") {
            platformBadgeStyle = `style="background-color: ${settings.atCoderColor};"`;
        } else if (contest.platform === "Codeforces") {
            platformBadgeStyle = `style="background-color: ${settings.codeforcesColor};"`;
        }

        // Only show relevant platform link
        const platformLink = `<a class="colored" href="${contest.platformUrl}" target="_blank">${contest.platform} 官网</a>`;

        return `
            <section class="am-panel lg-index-contest ${panelClass}">
                <header class="am-panel-hd">
                    <h3 class="am-panel-title">
                        <a href="${contest.url}" target="_blank">${contest.name}</a>
                        ${ratedBadge}
                    </h3>
                </header>
                <div class="am-panel-bd">
                    <span class="lg-small lg-inline-up">
                        <span class="am-badge am-radius" ${platformBadgeStyle}>${contest.platform}</span>
                    </span>
                    <span class="lg-small lg-inline-up">
                        ${statusHtml}<br>
                        ${platformLink}
                    </span>
                    <span class="lg-small lg-inline-up lg-right lg-md-hide">
                    ${formatDateToMMddHHmm(new Date(contest.startTime))}<br>
                    ${formatDateToMMddHHmm(new Date(contest.endTime))}
                    </span>
                </div>
            </section>
        `;
    }

    let isInjected = false;
    let retryCount = 0;
    const MAX_RETRIES = 5;

    async function init() {
        console.log("[LuoguContestAggregator] Initializing...");
        if (isInjected) {
            console.log("[LuoguContestAggregator] Already injected, skipping.");
            return;
        }

        const h2 = Array.from(document.querySelectorAll("h2")).find(h => h.textContent.includes("近期比赛"));
        const luoguContainer = h2 ? h2.parentElement : null;

        if (!luoguContainer || !h2) return;

        // 注入设置按钮
        if (!document.getElementById('lg-contest-settings-btn')) {
            h2.insertAdjacentHTML('beforeend', `<span id="lg-contest-settings-btn" title="设置" style="margin-left: 10px;background-color: #0080bbff;color: #ffffff;border-radius: 5px;font-size: 14px;font-weight: normal;">设置</span>`);
            document.getElementById('lg-contest-settings-btn').onclick = showSettings;
            createSettingsUI();
        }

        const settings = getSettings();

        // Get Luogu contests BEFORE removing them
        const lgContests = parseLuoguContests();
        console.log("[LuoguContestAggregator] Found Luogu contests:", lgContests.length);

        if (lgContests.length === 0 && retryCount < MAX_RETRIES) {
            retryCount++;
            console.log(`[LuoguContestAggregator] No Luogu contests found, retry ${retryCount}/${MAX_RETRIES}...`);
            return;
        }

        isInjected = true;
        console.log("[LuoguContestAggregator] Proceeding with injection...");

        try {
            const fetchPromises = [];
            if (settings.showCodeforces) {
                fetchPromises.push(fetchCFContests().then(res => { console.log("[LuoguContestAggregator] CF fetched:", res.length); return res; }));
            } else {
                fetchPromises.push(Promise.resolve([]));
            }

            if (settings.showAtCoder) {
                fetchPromises.push(fetchAtCoderContests().then(res => { console.log("[LuoguContestAggregator] AtCoder fetched:", res.length); return res; }));
            } else {
                fetchPromises.push(Promise.resolve([]));
            }

            const [cfContests, atContests] = await Promise.all(fetchPromises);

            const allContests = [...lgContests, ...cfContests, ...atContests];
            console.log("[LuoguContestAggregator] Total contests before sorting:", allContests.length);

            // Sort: start time asc, then end time asc
            allContests.sort((a, b) => {
                if (a.startTime !== b.startTime) return a.startTime - b.startTime;
                return a.endTime - b.endTime;
            });

            // Filter: only show upcoming or in-progress
            const now = Date.now();
            const displayContests = allContests.filter(c => c.endTime > now).slice(0, settings.maxContests);
            console.log("[LuoguContestAggregator] Contests to display:", displayContests.length);

            // Clear existing contests
            const existingSections = Array.from(luoguContainer.querySelectorAll("section.lg-index-contest, section.am-panel")).filter(s => {
                return h2.parentElement.contains(s);
            });
            console.log("[LuoguContestAggregator] Removing existing sections:", existingSections.length);
            existingSections.forEach(s => s.remove());

            // Insert new contests
            const html = displayContests.map(renderContest).join("");
            h2.insertAdjacentHTML('afterend', html);
            console.log("[LuoguContestAggregator] Injection complete.");
        } catch (err) {
            console.error("[LuoguContestAggregator] Error during init:", err);
            isInjected = false;
        }
    }

    // Run
    const observer = new MutationObserver(() => {
        if (document.querySelector(".lg-index-contest") && !isInjected) {
            init();
        }
    });

    observer.observe(document.body, { childList: true, subtree: true });

    // Also try on load
    window.addEventListener('load', init);
    setTimeout(init, 1000);
    setTimeout(init, 3000);
})();
原文