Greasy Fork

Check for Pet Matches in Other Trades

Check if pets in the current trade are in other trades and show a warning message in a new section

目前为 2025-01-10 提交的版本。查看 最新版本

// ==UserScript==
// @name         Check for Pet Matches in Other Trades
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Check if pets in the current trade are in other trades and show a warning message in a new section
// @author       winx from CS
// @match        https://www.chickensmoothie.com/trades/viewtrade.php*
// @match        https://www.chickensmoothie.com/trades/tradingcenter.php
// @grant        GM_xmlhttpRequest
// @grant        GM_cookie
// ==/UserScript==

(function() {
    'use strict';

    // Function to extract pet IDs from the current trade page
    function extractMyPetIDs(pageHTML) {
        const petIDs = [];
        const parser = new DOMParser();
        const doc = parser.parseFromString(pageHTML, 'text/html');

        // Find all <div class="section panel bg4"> elements (both sides of the trade)
        const tradePanels = doc.querySelectorAll('.section.panel.bg4');
        console.log('Trade Panels:', tradePanels.length);

        // Ensure we're targeting only your side of the trade (second section)
        if (tradePanels.length > 1) {
            const mySidePanel = tradePanels[1]; // Your side is always the second panel
            console.log('Found your side panel');

            // Get all pet links inside this panel (your side of the trade)
            const petLinks = mySidePanel.querySelectorAll('.trade-things .pets a');
            console.log('Found pet links:', petLinks.length);

            // Loop through the pet links and extract pet IDs
            petLinks.forEach(link => {
                const petID = link.href.split('id=')[1]; // Extract the ID from the URL
                petIDs.push(petID);
            });
        }

        console.log('My pet IDs:', petIDs);
        return petIDs;
    }

    // Function to fetch all trade IDs from the active trades section
    function fetchActiveTradeIDs(excludeTradeID) {
        return new Promise((resolve, reject) => {
            const url = 'https://www.chickensmoothie.com/trades/tradingcenter.php';
            GM_xmlhttpRequest({
                method: 'GET',
                url: url,
                onload: function(response) {
                    const pageHTML = response.responseText;
                    const tradeIDs = [];

                    // Parse the page HTML and target only the active trades section
                    const activeTradesTable = pageHTML.match(/<table class="cstable tradelist" id='active-trades'([\s\S]*?)<\/table>/);
                    if (activeTradesTable) {
                        const tradeLinks = Array.from(activeTradesTable[0].matchAll(/viewtrade\.php\?id=(\d+)/g));
                        tradeLinks.forEach(link => {
                            const tradeID = link[1];
                            if (tradeID !== excludeTradeID) {
                                tradeIDs.push(tradeID);
                            }
                        });
                    }

                    console.log('Fetched active trade IDs:', tradeIDs);
                    resolve(tradeIDs);
                },
                onerror: function(error) {
                    console.error('Failed to fetch trade IDs:', error);
                    reject(error);
                }
            });
        });
    }

    // Function to fetch pet IDs from a trade page
    function fetchTradePetIDs(tradeID) {
        return new Promise((resolve, reject) => {
            const url = `https://www.chickensmoothie.com/trades/viewtrade.php?id=${tradeID}`;
            GM_xmlhttpRequest({
                method: 'GET',
                url: url,
                onload: function(response) {
                    console.log('Fetching trade page:', url);
                    const petIDs = extractMyPetIDs(response.responseText);
                    resolve({ tradeID, petIDs });
                },
                onerror: function(error) {
                    console.error('Failed to fetch trade page:', url, error);
                    reject(error);
                }
            });
        });
    }

    // Function to compare pet IDs and show warning message
    function checkForMatches(currentPetIDs) {
        const currentTradeID = window.location.href.split('id=')[1];
        console.log('Current Trade ID:', currentTradeID);

        fetchActiveTradeIDs(currentTradeID)
            .then(tradeIDs => {
                const promises = tradeIDs.map(tradeID => fetchTradePetIDs(tradeID));

                Promise.all(promises)
                    .then(results => {
                        const matchingTrades = [];

                        // Loop through fetched trade pet IDs and check for matches
                        results.forEach(({ tradeID, petIDs }) => {
                            const matchedPets = petIDs.filter(petID => currentPetIDs.includes(petID));
                            console.log(`Matching pets for trade ${tradeID}:`, matchedPets);

                            if (matchedPets.length > 0) {
                                matchingTrades.push({ tradeID, matchedPets });
                            }
                        });

                        // If matches are found, inject the warning into the page
                        if (matchingTrades.length > 0) {
                            let warningHTML = '<div class="section panel bg5 time">';
                            warningHTML += '<div class="inner">';
                            warningHTML += '<span class="corners-top"><span></span></span>';
                            warningHTML += '<div class="infoline view-trade-share-link-infoline">';
                            warningHTML += '<div class="warning-box">';
                            warningHTML += 'Warning: Your pets are in other active trades!';
                            warningHTML += '<ul>';

                            matchingTrades.forEach(({ tradeID, matchedPets }) => {
                                warningHTML += `<li><a href="https://www.chickensmoothie.com/trades/viewtrade.php?id=${tradeID}" target="_blank">Trade ID: ${tradeID}</a> - Matched Pets: `;

                                matchedPets.forEach(petID => {
                                    warningHTML += `<a href="https://www.chickensmoothie.com/viewpet.php?id=${petID}" target="_blank">Pet ID: ${petID}</a> `;
                                });

                                warningHTML += '</li>';
                            });

                            warningHTML += '</ul>';
                            warningHTML += '</div>';
                            warningHTML += '</div>';
                            warningHTML += '<span class="corners-bottom"><span></span></span>';
                            warningHTML += '</div>';
                            warningHTML += '</div>';

                            // Insert warning after bg5 time section and before the trade action buttons
                            const bg5TimeSection = document.querySelector('.section.panel.bg5.time');
                            const tradeActionButtons = document.querySelector('.trade-action-buttons');

                            if (bg5TimeSection && tradeActionButtons) {
                                bg5TimeSection.insertAdjacentHTML('afterend', warningHTML);
                                console.log('Injected warning message with matching trades:', matchingTrades);
                            } else {
                                console.error('Could not find bg5 time section or trade action buttons to insert the warning.');
                            }
                        } else {
                            console.log('No matching pets found in other trades.');
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching trade details:', error);
                    });
            })
            .catch(error => {
                console.error('Error fetching trade IDs:', error);
            });
    }

    // Check if we are on the Trading Center page or a trade page
    const currentURL = window.location.href;
    if (currentURL.includes('viewtrade.php?id=')) {
        // We are on a trade page, extract pet IDs and check for matches
        const currentPetIDs = extractMyPetIDs(document.body.innerHTML);
        checkForMatches(currentPetIDs);
    }

    // Add custom styles for the warning box
    const style = document.createElement('style');
    style.textContent = `
        .warning-box {
            background-color: #f8d7da;
            color: #721c24;
            padding: 8px 15px; /* Adjust padding for top and bottom, and left and right */
            border: 1px solid #f5c6cb;
            border-radius: 4px;
            font-size: 14px;
            margin-top: 10px;
            margin-bottom: 10px; /* Added bottom margin */
        }

        .warning-box a {
            color: #721c24;
            text-decoration: underline;
        }

        .warning-box a:hover {
            color: #491217;
        }

        .section.panel.bg5.time .trade-icon-info {
            display: none;
        }
    `;
    document.head.appendChild(style);
})();