跳到正文

个人记录

GenGen-RMJ 3.0 测试公测

#SUSPENDED#约 53 分钟
原文
文章信息与版本

文章信息

收录
2026年1月3日
更新
2026年2月6日
篇幅
约 53 分钟

版本

  1. v1当前

本脚本分为 5 个模块。

代码
**2025/12/31** 完成 AT 模块(2/5)

**2026/1** 完成 CF 模块(4/5)

**2025/1~2** 完成 AT/CF 提交详细模块(5/5)

现在阶段:2025/12/31 完成 AT 模块(2/5)

GenGen RMJ AT 提交模块

代码
// ==UserScript==
// @name        Gen-AT-RMJ
// @namespace   http://tampermonkey.net/
// @version     1.0
// @description  GenGen RMJ AT 提交模块
// @match       https://*luogu.com.cn/problem/AT_*
// @match       https://atcoder.jp/contests/*/submit?RMJ=1
// @grant       GM_setValue
// @grant       GM_getValue
// @grant       GM_addStyle
// @require     https://html2canvas.hertzen.com/dist/html2canvas.min.js
// @connect     atcoder.jp
// @connect     luogu.com.cn
// @run-at      document-start
// ==/UserScript==

(() => {
    'use strict';

    // === 1. 立即注入全局样式(document-start 安全)===
    GM_addStyle(`
        #rmj-overlay {
            position: fixed !important;
            inset: 0 !important;
            background: rgba(255, 255, 255, 0.95) !important;
            z-index: 999998 !important;
            display: flex !important;
            flex-direction: column !important;
            justify-content: center !important;
            align-items: center !important;
            pointer-events: none !important;
        }
        #rmj-screenshot {
            position: absolute !important;
            inset: 0 !important;
            width: 100% !important;
            height: 100% !important;
            object-fit: fill !important;
            filter: blur(0px) !important;
            transition: filter 0.4s ease !important;
        }
        #rmj-screenshot.blurred {
            filter: blur(5px) !important;
        }

        /* 40% 黑色半透明遮罩 */
        #rmj-overlay::before {
            content: "" !important;
            position: absolute !important;
            inset: 0 !important;
            background: rgba(0, 0, 0, 0.4) !important;
            z-index: 999999 !important;
            pointer-events: none !important;
        }

        #rmj-overlay-content {
            text-align: center !important;
            max-width: 100% !important;
            z-index: 1000000 !important;
            position: relative !important;
            pointer-events: auto !important;
        }
        #rmj-message {
            color: white !important;
            font-size: 20px !important;
            margin-bottom: 120px !important;
            z-index: 1000001 !important;
            pointer-events: none !important;
        }

        body.rmj-loading {
            overflow: hidden !important;
            height: 100vh !important;
        }
    `);

    const href = location.href;
    const storeData = (key, value) => GM_setValue(`gen-at-${key}`, value);
    const getData = (key) => GM_getValue(`gen-at-${key}`, '');
    const clearData = () => ['code', 'contest', 'task', 'back', 'screenshot'].forEach(k => GM_setValue(`gen-at-${k}`, ''));

    // === 2. 安全创建遮罩(即使 body 未就绪)===
    const createOverlay = () => {
        if (document.getElementById('rmj-overlay')) return document.getElementById('rmj-overlay');

        const overlay = document.createElement('div');
        overlay.id = 'rmj-overlay';
        overlay.innerHTML = `
            <img id="rmj-screenshot" alt="Screenshot">
            <div id="rmj-overlay-content">
                <div id="rmj-message">请完成验证</div>
            </div>
        `;

        if (document.body) {
            document.body.appendChild(overlay);
        } else {
            const observer = new MutationObserver(() => {
                if (document.body) {
                    document.body.appendChild(overlay);
                    observer.disconnect();
                }
            });
            observer.observe(document.documentElement, { childList: true });
        }
        return overlay;
    };

    // === 3. 等待 body 可用后再启动主逻辑 ===
    const waitForBody = (callback) => {
        if (document.body) {
            callback();
        } else {
            const observer = new MutationObserver(() => {
                if (document.body) {
                    observer.disconnect();
                    callback();
                }
            });
            observer.observe(document.documentElement, { childList: true });
        }
    };

    // === 4. 主入口(延迟到 body 可用)===
    waitForBody(() => {
        /* ========== PART A: Luogu 页面 ========== */
        if (href.includes('luogu.com.cn')) {
            const initLuogu = async () => {
                storeData('back', location.href);

                let btn;
                while (true) {
                    btn = document.querySelector('#app > div.main-container > main > div > div > div.main > div > div.body > button');
                    if (btn) break;
                    await new Promise(r => setTimeout(r, 100));
                }
                if (!btn) return;

                const newBtn = btn.cloneNode(true);
                btn.replaceWith(newBtn);

                let view = null;
                while (true) {
                    for (const el of document.querySelectorAll('.cm-content, .cm-editor')) {
                        const v = el.cmView?.view || el.parentElement?.cmView?.view;
                        if (v?.state?.doc) { view = v; break; }
                    }
                    if (view) break;
                    await new Promise(r => setTimeout(r, 100));
                }
                if (!view) return;

                newBtn.addEventListener('click', async (e) => {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    try {
                        const code = view.state.doc.toString();
                        if (!code?.trim()) throw new Error('代码为空');

                        let contestId = '', taskScreenName = '';
                        for (const link of document.querySelectorAll('a[href*="atcoder.jp/contests/"], a[href*="atcoder.jp/tasks/"]')) {
                            const m = link.href.match(/atcoder\.jp\/contests\/([^\/]+)\/tasks\/([^\/?#]+)/);
                            if (m) {
                                contestId = m[1];
                                taskScreenName = m[2];
                                break;
                            }
                        }
                        if (!contestId || !taskScreenName) throw new Error('未找到 AtCoder 题目链接');

                        const { innerWidth: w, innerHeight: h } = window;
                        const screenshot = await html2canvas(document.documentElement, {
                            width: w,
                            height: h,
                            x: 0,
                            y: 0,
                            scrollX: 0,
                            scrollY: 0,
                            scale: 0.8,
                            useCORS: true,
                            allowTaint: true,
                            backgroundColor: null,
                            logging: false,
                            removeContainer: true
                        });
                        const screenshotData = screenshot.toDataURL('image/jpeg', 0.75);

                        storeData('code', code);
                        storeData('contest', contestId);
                        storeData('task', taskScreenName);
                        storeData('screenshot', screenshotData);

                        const overlay = createOverlay();
                        const img = document.getElementById('rmj-screenshot');
                        if (img) {
                            img.src = screenshotData;
                            setTimeout(() => img.classList.add('blurred'), 50);
                        }

                        setTimeout(() => {
                            location.href = `https://atcoder.jp/contests/${contestId}/submit?RMJ=1`;
                        }, 400);

                    } catch (err) {
                        alert('❌ ' + err.message);
                    }
                });
            };

            if (document.readyState === 'loading') {
                window.addEventListener('DOMContentLoaded', initLuogu);
            } else {
                initLuogu();
            }
            return;
        }

        /* ========== PART B: AtCoder 提交页 ========== */
        if (!href.includes('RMJ=1')) return;

        (function initAtCoder() {
            document.documentElement.classList.add('rmj-loading');
            createOverlay();
            const img = document.getElementById('rmj-screenshot');

            const screenshotData = getData('screenshot');
            if (screenshotData && img) {
                img.src = screenshotData;
                img.classList.add('blurred');
            }

            const execute = () => setTimeout(executeAtCoderLogic, 300);
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', execute);
            } else {
                execute();
            }
        })();

        async function executeAtCoderLogic() {
            const code = getData('code');
            if (!code?.trim()) {
                alert('❌ 代码为空,请返回洛谷重试');
                return;
            }

            document.documentElement.classList.remove('rmj-loading');

            const moveCF = () => {
                const cf = document.querySelector('.cf-challenge, .cf-turnstile, iframe[src*="challenges.cloudflare.com"]');
                if (cf) {
                    cf.style.cssText += 'position: fixed !important; top: 50% !important; left: 50% !important; transform: translate(-50%, -50%) !important; z-index: 999999 !important;';
                }
                return !!cf;
            };

            let form = null;
            for (let i = 0;; i++) {
                form = document.querySelector('form[action*="/submit"]');
                if (form) break;
                await new Promise(r => setTimeout(r, 100));
            }
            if (!form) return;

            for (let i = 0;; i++) {
                if (moveCF()) break;
                await new Promise(r => setTimeout(r, 100));
            }

            const plain = document.getElementById('plain-textarea');
            if (plain) {
                plain.value = code;
                plain.dispatchEvent(new Event('input', { bubbles: true }));
                plain.dispatchEvent(new Event('change', { bubbles: true }));
            }

            const aceDiv = document.getElementById('editor');
            if (aceDiv && typeof ace !== 'undefined') {
                try {
                    const editor = ace.edit(aceDiv);
                    editor.setValue(code, 1);
                    editor.clearSelection();
                    editor.focus();
                } catch (e) { /* silent */ }
            }

            const task = getData('task');
            if (task) {
                const sel = document.querySelector('select[name="data.TaskScreenName"]');
                if (sel) {
                    sel.value = task;
                    sel.dispatchEvent(new Event('change', { bubbles: true }));
                }
            }

            const lang = document.querySelector('select[name="data.LanguageId"]');
            if (lang) {
                lang.value = '6017'; // C++ 23 (gcc 12.2)
                lang.dispatchEvent(new Event('change', { bubbles: true }));
            }

            let verified = false;
            for (let i = 0; ; i++) {
                const token = document.querySelector('input[name="cf-turnstile-response"]');
                if (token?.value?.length > 10) {
                    verified = true;
                    break;
                }
                await new Promise(r => setTimeout(r, 100));
            }

            if (!verified) {
                const content = document.getElementById('rmj-overlay-content');
                if (content) content.innerHTML = `<div id="rmj-message">⚠️ 验证超时</div>`;
                return;
            }

            // === 提取 contest ID 用于跳转 ===
            const contestMatch = location.pathname.match(/^\/contests\/([^\/]+)/);
            const contestId = contestMatch ? contestMatch[1] : 'unknown';

            // === 手动提交表单(避免页面跳转到 AtCoder 结果页)===
            const formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                body: formData,
                credentials: 'include',
                headers: {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
                }
            })
            .then(() => {
                clearData();
                window.location.href = `https://www.luogu.com.cn/record/list?rmj=2&contest=${encodeURIComponent(contestId)}`;
            })
            .catch(err => {
                alert('⚠️ 提交失败,请手动提交:' + err.message);
                clearData();
            });
        }
    });
})();

GenGen RMJ AT 记录模块

C++
// ==UserScript==
// @name         Gen-AT-RMJ-JL
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  GenGen RMJ AT 记录模块
// @author       liyifan202201
// @match        https://*luogu.com.cn/record/list*
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @connect      atcoder.jp
// @run-at       document-end
// ==/UserScript==

(function () {
  'use strict';

  const params = new URLSearchParams(window.location.search);
  const rmj = params.get('rmj');
  const contest = params.get('contest');
  const pid = params.get('pid') || '';

  if (rmj !== '2') return;

  // ========== 配置 ==========
  const FINAL_STATUSES = new Set(['AC', 'WA', 'CE', 'RE', 'TLE', 'MLE', 'OLE', 'IE']);
  const STATUS_MAP = {
    'AC': { full: 'Accepted', cls: 'cf-status-accepted' },
    'WA': { full: 'Wrong Answer', cls: 'cf-status-wrong' },
    'CE': { full: 'Compilation Error', cls: 'cf-status-ce' },
    'RE': { full: 'Runtime Error', cls: 'cf-status-re' },
    'TLE': { full: 'Time Limit Exceeded', cls: 'cf-status-limit' },
    'MLE': { full: 'Memory Limit Exceeded', cls: 'cf-status-limit' },
    'OLE': { full: 'Output Limit Exceeded', cls: 'cf-status-limit' },
    'IE': { full: 'Internal Error', cls: 'cf-status-ce' }
  };

  // ========== 注入样式 ==========
  const style = document.createElement('style');
  style.textContent = `
    .cf-card { display: flex; align-items: center; font-size: 16px; padding: 10px 0; border-bottom: 1px solid #eee; }
    .cf-avatar img { width: 36px; height: 36px; border-radius: 50%; margin-right: 12px; }
    .cf-nameblock { display: flex; flex-direction: column; width: 180px; margin-right: 12px; }
    .cf-name { font-weight: bold; color: #333; font-size: 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .cf-time { font-size: 14px; color: #888; line-height: 1.2; margin-top: 2px; white-space: nowrap; }
    .cf-status { flex: 0 0 auto; margin-right: 12px; width: 250px; text-align: left; }
    .cf-status span {
      border-radius: 2px; padding: 4px 8px; font-size: 14px; font-weight: 600; white-space: nowrap;
      display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis;
    }
    .cf-status-accepted { background: rgb(82, 196, 26); color: #fff; }
    .cf-status-wrong { background: rgb(231, 76, 60); color: #fff; }
    .cf-status-re { background: rgb(157, 61, 207); color: #fff; }
    .cf-status-ce { background: rgb(250, 219, 20); color: #fff; }
    .cf-status-limit { background: rgb(5, 34, 66); color: #fff; }
    .cf-status-running { background: #888; color: #fff; }
    .cf-status-other { background: rgb(243, 156, 17); color: #fff; }
    .cf-problem { flex: 1; color: rgb(52, 152, 219); font-size: 16px; text-align: left; min-width: 100px; margin-left: 60px; }
    .cf-error { padding: 10px; color: #e74c3c; font-weight: bold; }
  `;
  document.head.appendChild(style);

  // ========== 工具函数 ==========
  function getLuoguUserInfo() {
    const nameEl = document.querySelector('#app .user-nav > a > span') ||
                   document.querySelector('div.header span a span') ||
                   document.querySelector('.username');
    const avatarEl = document.querySelector('#app .user-nav a img');
    return {
      name: (nameEl?.textContent || 'User').trim(),
      color: nameEl?.style?.color || '#333',
      avatar: (avatarEl?.src || 'https://cdn.luogu.com.cn/upload/usericon/default.png').trim()
    };
  }

  function sanitizeAtcoderUrl(url, contestId) {
    if (url.startsWith('https://atcoder.jp/')) return url;
    const luoguMatch = url.match(/luogu\.com\.cn\/contests\/([^\/]+)\/submissions\/(\d+)/);
    if (luoguMatch) return `https://atcoder.jp/contests/${luoguMatch[1]}/submissions/${luoguMatch[2]}`;
    try {
      return new URL(url, `https://atcoder.jp/contests/${contestId}/`).href;
    } catch {
      return `https://atcoder.jp/contests/${contestId}/submissions/${url.split('/').pop()}`;
    }
  }

  function createCfCard(taskDisplay, isFinal, rawStatus, timeText, atcoderUrl, luoguUrl, id = '') {
    const card = document.createElement('div');
    card.className = 'cf-card';
    if (id) card.dataset.id = id;

    const { name, color, avatar } = getLuoguUserInfo();
    const avatarDiv = document.createElement('div');
    avatarDiv.className = 'cf-avatar';
    const img = document.createElement('img');
    img.src = avatar;
    img.onerror = () => img.src = 'https://cdn.luogu.com.cn/upload/usericon/1.png';
    avatarDiv.appendChild(img);

    const nameBlock = document.createElement('div');
    nameBlock.className = 'cf-nameblock';
    const nameDiv = document.createElement('div');
    nameDiv.className = 'cf-name';
    nameDiv.style.color = color;
    nameDiv.textContent = name;
    const timeDiv = document.createElement('div');
    timeDiv.className = 'cf-time';
    timeDiv.textContent = timeText;
    nameBlock.append(nameDiv, timeDiv);

    const statusDiv = document.createElement('div');
    statusDiv.className = 'cf-status';
    const statusLink = document.createElement('a');
    statusLink.href = atcoderUrl;
    statusLink.target = '_blank';
    statusLink.rel = 'noopener noreferrer';
    const span = document.createElement('span');

    if (isFinal) {
      const { full, cls } = STATUS_MAP[rawStatus] || { full: rawStatus, cls: 'cf-status-other' };
      span.className = cls;
      span.textContent = full;
    } else {
      span.className = 'cf-status-running';
      span.textContent = rawStatus;
    }
    statusLink.appendChild(span);
    statusDiv.appendChild(statusLink);

    const problemDiv = document.createElement('div');
    problemDiv.className = 'cf-problem';
    const probLink = document.createElement('a');
    probLink.href = luoguUrl;
    probLink.textContent = taskDisplay;
    probLink.target = '_blank';
    probLink.rel = 'noopener noreferrer';
    problemDiv.appendChild(probLink);
    card.append(avatarDiv, nameBlock, statusDiv, problemDiv);
    return card;
  }

  function getCache() {
    try {
      return JSON.parse(GM_getValue('at-submissions-cache', '[]')).map(item => ({
        ...item,
        atcoderSubmissionUrl: sanitizeAtcoderUrl(item.atcoderSubmissionUrl, item.taskKey?.split('_')[0] || '')
      }));
    } catch {
      console.warn('[Gen-AT-RMJ] 缓存解析失败,重置');
      return [];
    }
  }

  function saveCache(cache) {
    const clean = cache.map(item => ({
      ...item,
      atcoderSubmissionUrl: sanitizeAtcoderUrl(item.atcoderSubmissionUrl, item.taskKey?.split('_')[0] || '')
    }));
    GM_setValue('at-submissions-cache', JSON.stringify(clean));
  }

  async function fetchLatestSubmission(contest) {
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(() => reject(new Error('Timeout')), 8000);
      GM_xmlhttpRequest({
        method: 'GET',
        url: `https://atcoder.jp/contests/${contest}/submissions/me`,
        onload: res => {
          clearTimeout(timeout);
          if (res.status !== 200) return reject(new Error(`HTTP ${res.status}`));
          try {
            const doc = new DOMParser().parseFromString(res.responseText, 'text/html');
            const row = doc.querySelector('table.table tbody tr');
            if (!row) return resolve(null);

            const cells = Array.from(row.querySelectorAll('td'));
            if (cells.length < 7) throw new Error('Invalid columns');

            const timeEl = cells[0]?.querySelector('time');
            const timeText = timeEl?.innerText.trim() || 'Unknown Time';

            const taskLink = cells[1]?.querySelector('a');
            const taskHref = taskLink?.href || '';
            const taskName = taskLink?.innerText?.trim() || 'Unknown Task';
            const taskKey = taskHref.match(/\/tasks\/([^\/\s]+)/)?.[1] || 'Unknown';
            const taskDisplay = `${taskKey} - ${taskName}`;
            const luoguProblemUrl = `https://www.luogu.com.cn/problem/AT_${taskKey}`;
            let rawStatus = 'Unknown';
            for (const cell of cells) {
              const label = cell.querySelector('.label');
              if (label) {
                rawStatus = label.innerText.trim();
                break;
              }
            }

            const detailAnchor = cells[cells.length - 1]?.querySelector('a.submission-details-link');
            if (!detailAnchor?.href) throw new Error('No detail link');

            const submissionId = detailAnchor.href.split('/').pop();
            const atcoderSubmissionUrl = `https://atcoder.jp/contests/${contest}/submissions/${submissionId}`;
            const isFinal = FINAL_STATUSES.has(rawStatus);

            resolve({ submissionId, taskKey, taskName, taskDisplay, rawStatus, atcoderSubmissionUrl, luoguProblemUrl, timeText, isFinal });
          } catch (err) {
            reject(err);
          }
        },
        onerror: () => {
          clearTimeout(timeout);
          reject(new Error('Network error'));
        }
      });
    });
  }

  function updateRecordCount(count) {
    const countSpan = document.querySelector('#app > div.main-container > main > div > section > div > div > span > span');
    if (countSpan) {
      countSpan.textContent = count.toString();
    }
  }

  function renderCache(cache, mainDiv) {
    let filtered = cache;
    if (searchFilter) {
      const normQuery = searchFilter.replace(/^AT_/i, '').toLowerCase();
      filtered = cache.filter(s => s.taskDisplay.toLowerCase().includes(normQuery));
    }

    displayedIds.clear();

    mainDiv.innerHTML = '';
    updateRecordCount(filtered.length);

    if (filtered.length === 0) {
      const msg = document.createElement('div');
      msg.className = 'cf-error';
      msg.textContent = '没有提交记录';
      mainDiv.appendChild(msg);
    } else {
      filtered.forEach(sub => {
        const timeText = new Date(sub.timestamp).toLocaleString('zh-CN');
        const card = createCfCard(sub.taskDisplay, sub.isFinal, sub.status, timeText, sub.atcoderSubmissionUrl, sub.luoguProblemUrl, sub.id);
        displayedIds.add(sub.id);
        mainDiv.appendChild(card);
      });
    }
  }

  function waitForElement(selector, timeout = 10000) {
    return new Promise((resolve, reject) => {
      const el = document.querySelector(selector);
      if (el) return resolve(el);
      const observer = new MutationObserver(() => {
        const found = document.querySelector(selector);
        if (found) {
          observer.disconnect();
          resolve(found);
        }
      });
      observer.observe(document.body, { childList: true, subtree: true });
      setTimeout(() => {
        observer.disconnect();
        reject(new Error(`Timeout: ${selector}`));
      }, timeout);
    });
  }

  // ========== 主流程 ==========
  let displayedIds = new Set();
  let searchFilter = pid;

  async function bindSearch(mainDiv) {
    try {
      const input = await waitForElement('#app main section div section:nth-child(1) div div:nth-child(1) input', 8000);
      input.value = searchFilter;
      const originalOnInput = input.oninput;
      input.oninput = (e) => {
        searchFilter = e.target.value.trim();
        const url = new URL(window.location);
        if (searchFilter) url.searchParams.set('pid', searchFilter);
        else url.searchParams.delete('pid');
        history.replaceState(null, '', url);
        renderCache(getCache(), mainDiv);
        originalOnInput?.call(input, e);
      };
    } catch (e) {
      console.warn('[Gen-AT-RMJ] 搜索框未找到');
    }
  }

  async function main() {
    let mainDiv;
    try {
      mainDiv = await waitForElement('main > div > div', 10000);
    } catch {
      const appMain = document.querySelector('#app main') || document.body;
      mainDiv = document.createElement('div');
      appMain.appendChild(mainDiv);
    }

    renderCache(getCache(), mainDiv);
    await bindSearch(mainDiv);

    let pollingInterval;
    const finalized = new Set();

    if (contest) {
      pollingInterval = setInterval(async () => {
        try {
          const res = await fetchLatestSubmission(contest);
          if (!res) return;

          const { submissionId, isFinal } = res;
          if (isFinal && finalized.has(submissionId)) return;

          const cache = getCache();
          const existingIndex = cache.findIndex(s => s.id === submissionId);

          const newEntry = {
            id: submissionId,
            taskKey: res.taskKey,
            taskName: res.taskName,
            taskDisplay: res.taskDisplay,
            status: res.rawStatus,
            atcoderSubmissionUrl: res.atcoderSubmissionUrl,
            luoguProblemUrl: res.luoguProblemUrl,
            timestamp: existingIndex >= 0 ? cache[existingIndex].timestamp : Date.now(),
            isFinal: isFinal
          };

          if (existingIndex >= 0) {
            cache[existingIndex] = newEntry;
          } else {
            cache.unshift(newEntry);
          }

          saveCache(cache);
          renderCache(cache, mainDiv);

          if (isFinal) finalized.add(submissionId);
        } catch (err) {
          console.log('[Gen-AT-RMJ] 轮询失败:', err.message || err);
        }
      }, 1000);

      window.addEventListener('beforeunload', () => {
        if (pollingInterval) clearInterval(pollingInterval);
      });
    }
  }

  main().catch(console.error);
})();
原文