CPR Requirements

Show required CPRs for Torn OCs and highlight invalid ones with visual alert

当前为 2025-07-27 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         CPR Requirements
// @namespace    https://lzpt.io/
// @version      1.2
// @description  Show required CPRs for Torn OCs and highlight invalid ones with visual alert
// @author       Lazerpent
// @match        https://www.torn.com/factions.php?step=your*
// @connect      api.lzpt.io
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function () {
    'use strict';

    const POLL_INTERVAL = 1000;
    const API_BASE = 'https://api.lzpt.io/static/cprs/';

    // Inject pulsing CSS
    const style = document.createElement('style');
    style.textContent = `
        @keyframes cprPulse {
            0% { background-color: rgba(255, 0, 0, 0.3); }
            50% { background-color: rgba(255, 0, 0, 0.7); }
            100% { background-color: rgba(255, 0, 0, 0.3); }
        }
        @keyframes cprPulseDark {
            0% { background-color: rgba(255, 0, 0, 0.2); box-shadow: 0 0 4px rgba(255, 0, 0, 0.5); }
            50% { background-color: rgba(255, 0, 0, 0.6); box-shadow: 0 0 12px rgba(255, 0, 0, 0.8); }
            100% { background-color: rgba(255, 0, 0, 0.2); box-shadow: 0 0 4px rgba(255, 0, 0, 0.5); }
        }
        .cpr-invalid {
            animation: cprPulse 1s infinite;
            border-radius: 3px;
            padding: 0 4px;
            font-weight: bold;
            color: #333333 !important;
        }
        .dark-mode .cpr-invalid {
            color: #DDDDDD !important;
            animation: cprPulseDark 1s infinite;

        }
    `;
    document.head.appendChild(style);

    const getFactionId = () => {
        const link = document.querySelector('a[href*="forums"][href*="a="]');
        if (!link) return null;
        const match = link.href.match(/a=(\d+)/);
        return match ? match[1] : null;
    };

    const fetchCPRs = (factionId) => {
        const url = `${API_BASE}${factionId}.json`;
        console.log("Fetching CPRs from", url);
        return new Promise((resolve, reject) => {
            (GM_xmlhttpRequest ? GM_xmlhttpRequest : GM.xmlhttpRequest)({
                method: 'GET',
                url: url,
                headers: { 'Accept': 'application/json' },
                onload: function (response) {
                    try {
                        const json = JSON.parse(response.responseText);
                        resolve(json);
                    } catch (e) {
                        console.error("Failed to parse CPR response", e);
                        reject(e);
                    }
                },
                onerror: function (err) {
                    console.error("Failed to fetch CPR data", err);
                    reject(err);
                }
            });
        });
    };

    const parseOCName = (wrapper) => {
        const nameNode = wrapper.closest('[class^=contentLayer]')?.querySelector('[class^=panelTitle]');
        return nameNode?.textContent?.trim() || null;
    };

    const processSlots = (data) => {
        console.log("CPR: Updating slots");
        const slots = document.querySelectorAll('[class^=wrapper][class*="success"]');
        const redSuccessClass = findSuccessRedClass();

        slots.forEach((slot) => {
            const successEl = slot.querySelector('[class^=successChance]');
            const titleEl = slot.querySelector('[class^=title]');
            if (!successEl || !titleEl) return;

            const currentCPR = parseInt(successEl.textContent.split(/\s+/)[0].trim(), 10);
            const roleName = titleEl.textContent.trim();
            const ocName = parseOCName(slot);
            if (!ocName || !data[ocName]) return;

            const ocInfo = data[ocName];
            const requiredCPR = ocInfo.roles?.[roleName] ?? ocInfo.default;
            if (requiredCPR === undefined) return;

            if (successEl.dataset._cpr_patched) return;
            successEl.dataset._cpr_patched = true;

            // Only show CPR (no required value)
            successEl.textContent = `${currentCPR}`;

            if (currentCPR < requiredCPR) {
                successEl.classList.add('cpr-invalid');

                const wrapper = slot.closest('[class*="success"][class*="wrapper"]');
                if (wrapper && !wrapper.dataset._cpr_patched) {
                    for (const cls of [...wrapper.classList]) {
                        if (/^success[A-Z]/.test(cls)) {
                            wrapper.classList.remove(cls);
                        }
                    }

                    wrapper.classList.add(redSuccessClass);
                    wrapper.dataset._cpr_patched = 'true';
                }
            }
        });
    };

    function findSuccessRedClass() {
        for (const sheet of document.styleSheets) {
            let rules;
            try {
                rules = sheet.cssRules || sheet.rules;
            } catch (e) {
                continue; // Some stylesheets are CORS-restricted
            }
            if (!rules) continue;

            for (const rule of rules) {
                if (!rule.selectorText) continue;

                const match = rule.selectorText.match(/\.successRed___[a-zA-Z0-9_-]+/);
                if (match) {
                    return match[0].substring(1); // Remove leading '.'
                }
            }
        }
        return null;
    }

    const patchTooltip = (tooltipId, requiredCPR, currentCPR) => {
        const tooltipEl = document.getElementById(tooltipId);
        if (!tooltipEl || tooltipEl.dataset._cpr_patched) return;

        const wrapper = tooltipEl.querySelector('[class*="wrapper___"]');
        if (!wrapper) return;

        const refSection = wrapper.querySelector('[class*="section___"][class*="iconWithText___"]');
        const refIcon = wrapper.querySelector('[class*="icon___"]');

        // Determine icon and color
        const isInvalid = currentCPR < requiredCPR;
        const iconColor = isInvalid ? '#cc0000' : '#33aa33';
        const iconSVG = isInvalid
            ? `<line x1="2" y1="2" x2="10" y2="10" stroke="${iconColor}" stroke-width="2"/><line x1="10" y1="2" x2="2" y2="10" stroke="${iconColor}" stroke-width="2"/>`
            : `<path d="M8.452,2,3.75,6.82l-2.2-2.088L0,6.28,3.75,9.917,10,3.548Z" transform="translate(0 -2)" fill="${iconColor}" stroke="rgba(0,0,0,0)" stroke-width="1"></path>`;

        // Build section container
        const newSection = document.createElement('div');
        newSection.className = refSection?.className || '';

        const iconDiv = document.createElement('div');
        iconDiv.className = refIcon?.className || '';
        iconDiv.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12">
                <g>${iconSVG}</g>
            </svg>
        `;

        const textSpan = document.createElement('span');
        textSpan.textContent = `Required pass rate: ${requiredCPR}%`;
        textSpan.style.fontWeight = isInvalid ? 'bold' : '';

        newSection.appendChild(iconDiv);
        newSection.appendChild(textSpan);

        // Insert after "Checkpoint pass rate"
        const sections = wrapper.querySelectorAll('[class*="section___"][class*="iconWithText___"]');
        let inserted = false;
        for (let i = 0; i < sections.length; i++) {
            const s = sections[i];
            if (s.textContent.includes('Checkpoint pass rate')) {
                if (s.nextSibling) {
                    wrapper.insertBefore(newSection, s.nextSibling);
                } else {
                    wrapper.appendChild(newSection);
                }
                inserted = true;
                break;
            }
        }

        if (!inserted) wrapper.appendChild(newSection);
        tooltipEl.dataset._cpr_patched = true;
    };

    const monitorTooltips = (requiredMap) => {
        const tooltipObserver = new MutationObserver(() => {
            document.querySelectorAll('button[aria-describedby]').forEach(btn => {
                const id = btn.getAttribute('aria-describedby');
                const successEl = btn.querySelector('[class^=successChance]');
                const titleEl = btn.querySelector('[class^=title]');
                const ocName = parseOCName(btn);
                if (!successEl || !titleEl || !ocName || !requiredMap[ocName]) return;

                const roleName = titleEl.textContent.trim();
                const requiredCPR = requiredMap[ocName].roles?.[roleName] ?? requiredMap[ocName].default;
                if (requiredCPR === undefined) return;

                const currentCPR = parseInt(successEl.textContent.trim(), 10);
                if (isNaN(currentCPR)) return;

                patchTooltip(id, requiredCPR, currentCPR);
            });
        });

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




    const run = async (cprData) => {
        const root = document.getElementById('faction-crimes-root');
        if (!root) {
            setTimeout(() => run(cprData), 200);
            return;
        }
        const observer = new MutationObserver((mutations) => {
            const isRelevant = mutations.some(m => !m.target.closest('[class^=phase]'));
            if (isRelevant) processSlots(cprData);
            monitorTooltips(cprData);
        });
        observer.observe(root, { childList: true, subtree: true });
    };

    const start = async () => {
        const factionId = getFactionId();
        if (!factionId) {
            setTimeout(start, 100);
            return;
        }

        try {
            const cprData = await fetchCPRs(factionId);
            if (!cprData || typeof cprData !== 'object') {
                alert("Failed to get CPR Requirements");
                return;
            }
            run(cprData);
        } catch (e) {
            console.error("CPR Userscript failed to start", e);
        }
    };

    start();
    window.addEventListener("hashchange", function() {
        start();
    });

})();