Greasy Fork

MZ_Track_Youth_Exchange_Players

Using this userscript will send your youth exchanges to the table on this page: https://mz-guide.vercel.app/16.html

目前为 2024-08-02 提交的版本。查看 最新版本

// ==UserScript==
// @name         MZ_Track_Youth_Exchange_Players
// @namespace    http://tampermonkey.net/
// @version      2.1
// @description  Using this userscript will send your youth exchanges to the table on this page: https://mz-guide.vercel.app/16.html
// @author       You
// @match        *://www.managerzone.com/?p=youth_academy*
// @grant        GM_xmlhttpRequest
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    let username = '';
    let nationality = '';
    const youthExchangePlayerAge = 16;

    console.log("Will save youth exchange data to db.");

    const fetchNationality = (username) => {
        GM_xmlhttpRequest({
            method: "GET",
            url: `http://www.managerzone.com/xml/manager_data.php?sport_id=1&username=${username}`,
            onload: function (response) {
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(response.responseText, "text/xml");
                const countryShortname = xmlDoc.querySelector('UserData') ? xmlDoc.querySelector('UserData').getAttribute('countryShortname') : 'Not found';
                getCountryFullName(countryShortname);
            },
            onerror: function () {
                console.log("Error fetching nationality.");
                setupRejectExchListeners();
            }
        });
    };

    const getCountryFullName = (shortName) => {
        GM_xmlhttpRequest({
            method: "GET",
            url: 'https://gist.githubusercontent.com/douglasdotv/ab34745e73c41fa612913e96a968fba9/raw/b21e8512e6a0ae2fb1f37d2fc547140435932b1d/countries.json',
            onload: function (response) {
                const countries = JSON.parse(response.responseText);
                const country = countries.find(c => c.code === shortName);
                nationality = country ? country.name : shortName;
                setupRejectExchListeners();
            },
            onerror: function () {
                console.log("Error fetching full country name.");
            }
        });
    };

    const sendDataToAzure = (youthExchangeObj) => {
        GM_xmlhttpRequest({
            method: "POST",
            url: "https://mziscool.azurewebsites.net/save",
            headers: {
                "Content-Type": "application/json"
            },
            data: JSON.stringify(youthExchangeObj),
            onload: function (response) {
                console.log(`Youth player data sent. Response code ${response.status}: ${response.responseText}`);
            },
            onerror: function (error) {
                console.log('Error when sending data to API:', error);
            }
        });
    };

    const extractSkillNameAndLevel = (skillString) => {
        const match = skillString.trim().match(/([HL])(\d+) (.+)/);
        return match ? { level: parseInt(match[2]), name: match[3] } : { level: 0, name: skillString.trim() };
    };

    const preparePlayerData = (playerData) => {
        return {
            partitionKey: playerData.totalSkillBalls + "Balls",
            rowKey: playerData.playerID,
            name: playerData.playerName,
            age: youthExchangePlayerAge,
            country: nationality,
            hp: playerData.hp,
            firstHpSkill: playerData.firstHpSkill,
            secondHpSkill: playerData.secondHpSkill,
            lp: playerData.lp,
            firstLpSkill: playerData.firstLpSkill,
            secondLpSkill: playerData.secondLpSkill,
            trainingSpeed: playerData.trainingSpeed,
            totalBalls: playerData.totalSkillBalls,
            owner: username,
            stats: playerData.stats
        };
    };

    const extractPlayerStats = (playerContainer) => {
        const stats = {};

        const skillsNames = [
            "speed", "stamina", "playIntelligence", "passing", "shooting",
            "heading", "keeping", "ballControl", "tackling", "aerialPassing", "setPlays",
            "experience", "form"
        ];

        const skillsRows = playerContainer.querySelectorAll('.player_skills tr');

        skillsRows.forEach((row, index) => {
            if (index < skillsNames.length) {
                const skillValueElement = row.querySelector('.skillval span');
                const skillValue = skillValueElement ? parseInt(skillValueElement.textContent.trim()) : 0;
                const skillName = skillsNames[index];
                stats[skillName] = skillValue;
            }
        });

        return stats;
    };

    const extractPlayerData = () => {
        const playerContainer = document.getElementById("thePlayers_x");
        if (!playerContainer) {
            console.log("Where is the player?");
            return;
        }

        GM_xmlhttpRequest({
            method: "GET",
            url: `https://www.managerzone.com/ajax.php?p=players&sub=scout_report&pid=null&sport=soccer`,
            onload: function (response) {
                let responseText = response.responseText.replace(/Trzxyvopaxis/g, '');
                const parser = new DOMParser();
                const doc = parser.parseFromString(responseText, "text/html");
                const dataList = doc.querySelectorAll('dl > dd');

                const extractSkillsAndPotentials = (skillContainers) => {
                    const skills = {
                        firstHpSkill: "",
                        secondHpSkill: "",
                        firstLpSkill: "",
                        secondLpSkill: ""
                    };

                    if (skillContainers.length > 1) {
                        const hpSkills = Array.from(skillContainers[0].querySelectorAll('li > span:last-child')).map(span => span.textContent.trim());
                        const lpSkills = Array.from(skillContainers[1].querySelectorAll('li > span:last-child')).map(span => span.textContent.trim());

                        if (hpSkills.length >= 2) {
                            skills.firstHpSkill = hpSkills[0];
                            skills.secondHpSkill = hpSkills[1];
                        }
                        if (lpSkills.length >= 2) {
                            skills.firstLpSkill = lpSkills[0];
                            skills.secondLpSkill = lpSkills[1];
                        }
                    }

                    return skills;
                };

                const skillsAndPotentials = extractSkillsAndPotentials(dataList);
                const stats = extractPlayerStats(playerContainer);

                const playerData = {
                    playerID: playerContainer.querySelector('.player_id_span').textContent,
                    playerName: playerContainer.querySelector('.player_name').textContent,
                    hp: dataList[0].querySelectorAll('.lit').length,
                    lp: dataList[1].querySelectorAll('.lit').length,
                    totalSkillBalls: playerContainer.querySelectorAll('tbody > tr')[6].querySelector('.bold').textContent,
                    trainingSpeed: dataList[2].querySelectorAll('.lit').length,
                    stats: stats,
                    ...skillsAndPotentials
                };

                const youthExchangeObj = preparePlayerData(playerData);
                console.log(youthExchangeObj);
                sendDataToAzure(youthExchangeObj);
            },
            onerror: function () {
                console.error("Error fetching player data.");
            }
        });
    };

    const setupRejectExchListeners = () => {
        setInterval(() => {
            const rejectButton = document.querySelector('#discard_youth_button');
            const exchangeButton = document.querySelector('#exchange_button');
            if (rejectButton && !rejectButton.dataset.listenerAdded) {
                rejectButton.addEventListener('click', extractPlayerData);
                rejectButton.dataset.listenerAdded = true;
            }
            if (exchangeButton && !exchangeButton.dataset.listenerAdded) {
                exchangeButton.addEventListener('click', extractPlayerData);
                exchangeButton.dataset.listenerAdded = true;
            }
        }, 400);
    };

    window.addEventListener('load', () => {
        const usernameElement = document.getElementById('header-username');
        username = usernameElement ? usernameElement.textContent : 'Unknown';
        fetchNationality(username);
    });
})();