Pavlov mod.io maps integration with pavlovrcon.com

Add extra buttons to mod.io pavlov map pages to allow switching to the map or adding it to the rotation of a server by using pavlovrcon.com

Versión del día 18/6/2023. Echa un vistazo a la versión más reciente.

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

You will need to install an extension such as Tampermonkey to install this script.

Necesitarás instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Necesitará instalar una extensión como Tampermonkey para instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==UserScript==
// @name         Pavlov mod.io maps integration with pavlovrcon.com
// @namespace    https://greasyfork.org/en/users/1103172-underpl
// @version      1.0
// @description  Add extra buttons to mod.io pavlov map pages to allow switching to the map or adding it to the rotation of a server by using pavlovrcon.com
// @author       UnderPL
// @match        https://mod.io/g/pavlov
// @match        https://mod.io/g/pavlov/m/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(function() {
    'use strict';
    var defaultMode = "INFECTION";
    var storedGameModeValue = GM_getValue("storedSelectedGameMode", defaultMode);
    var storedSelectedGameMode = storedGameModeValue || defaultMode;

    //var defaultServerId = "0";
    //var storedServerId = GM_getValue("selectedServerId", defaultMode);
    //var selectedServerId = storedServerId || defaultServerId;

    GM_setValue("storedSelectedGameMode", storedSelectedGameMode);
    //GM_setValue("storedSelectedServerId", storedSelectedServerId);

    function createButton(id, color, text, subscribeButton) {
        var newButton = subscribeButton.cloneNode(true);
        newButton.id = id;
        newButton.querySelector('span div span').textContent = text;
        newButton.style.borderColor = color;
        newButton.style.setProperty('--primary-hover', color);

        newButton.addEventListener('mouseover', function() {
            newButton.querySelector('span div span').style.color = color;
        });

        newButton.addEventListener('mouseout', function() {
            newButton.querySelector('span div span').style.color = 'inherit';
        });

        return newButton;
    };

    function confirmAction(mapName, mapId, selectedGameMode) {
        var confirmationMessage = `Are you sure you want to add "${mapName}" to the map rotation?\nMapRotation=(MapId="${mapId}",GameMode="${selectedGameMode}")`;
        return window.confirm(confirmationMessage);
    }

    function createSelectAndLabel() {
        var container = document.createElement('div');
        container.style.textAlign = 'center';

        var newLabel = document.createElement('label');
        newLabel.innerHTML = 'Mode:';
        newLabel.style.display = 'inline-block';
        newLabel.style.fontSize = '150%';
        newLabel.style.marginRight = '10px';
        newLabel.style.display = 'inline-block';
        container.appendChild(newLabel);

        var newSelect = document.createElement('select');
        newSelect.id = "gameModes";
        newSelect.classList.add("form-select");
        newSelect.style.color = 'black';
        newSelect.style.fontSize = '150%';
        newSelect.style.paddingLeft = '5px';
        newSelect.style.textAlign = 'center';
        newSelect.style.display = 'block';
        newSelect.style.margin = '0 auto';
        newSelect.style.display = 'inline-block';
        container.appendChild(newSelect);

        newSelect.innerHTML = ['SND', 'TDM', 'DM', 'GUN', 'ZWV', 'WW2GUN', 'TANKTDM', 'KOTH', 'TTT', 'OITC', 'INFECTION', 'HIDE', 'PUSH', 'PH', 'CUSTOM']
        .map(mode => `<option value="${mode}" ${storedSelectedGameMode === mode ? 'selected' : ''}>${mode}</option>`).join('');

        newSelect.addEventListener('change', function() {
            storedSelectedGameMode = newSelect.value;
            GM_setValue("storedSelectedGameMode", storedSelectedGameMode);
        });

        return container;
    };

    const headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "application/json"
    }

    function mapAction(mapId, selectedGameMode, action) {
        var body = JSON.stringify({
            data: selectedGameMode,
            "Map Name": "UGC" + mapId,
            uid: null
        });

        console.log(`Request Data for action '${action}':\n`, JSON.parse(body));

        GM_xmlhttpRequest({
            method: "POST",
            url: `https://pavlovrcon.com/api/${action}/0`,
            headers: headers,
            data: body,
            onload: function(response) {
                console.log('GM_xmlhttpRequest response:', response);
            }
        });
    }

    function addButtonsWithEventListeners(mapId, subscribeButton, specificMapPage = false) {
        var playButton = createButton("playButton", "green", "Play", subscribeButton);
        playButton.style.marginBottom = "10px";
        playButton.style.marginTop = "8px";

        var addToMapRotationButton = createButton("addToMapRotationButton", "blue", "Add to map rotation", subscribeButton);
        addToMapRotationButton.style.marginBottom = "10px";
        addToMapRotationButton.style.display = subscribeButton.style.display;

        subscribeButton.parentNode.insertBefore(playButton, subscribeButton);
        subscribeButton.parentNode.insertBefore(addToMapRotationButton, playButton.nextElementSibling);

        if(specificMapPage){
            addSelectElement(playButton, 'before');
        }

        var selectElement = selectElementContainer.querySelector('select');
        var selectedGameMode = selectElement.value;

        playButton.addEventListener('click', function(e) {
            e.stopPropagation();
            mapAction(mapId, selectedGameMode, "switch_map");
        });

        addToMapRotationButton.addEventListener('click', function(e) {
            e.stopPropagation();
            var mapName;
            specificMapPage ? mapName = document.querySelector('.tw-util-truncate-two-lines.tw-font-bold').textContent : mapName = subscribeButton.parentNode.parentNode.parentNode.querySelectorAll('a > div')[1].textContent;


            if (confirmAction(mapName, mapId, selectedGameMode)) {
                mapAction(mapId, selectedGameMode, "addmaprotation");
            }
        });
    }

    let addedMaps = new Set();

    function addButtonsToMapsPage() {
        const divs = document.querySelectorAll('div.tw-bg-center.tw-bg-cover.tw-w-full.tw-h-full[role="img"]');
        const subscribeButtons = document.querySelectorAll('button.tw-button-transition.tw-outline-none.tw-shrink-0.tw-items-center.tw-justify-center.tw-space-x-2.tw-font-bold.tw-bg-theme-1--hover.tw-text-md[id^="input"]');

        for(let i = 0; i < divs.length; i++) {
            const altText = divs[i].getAttribute('alt');
            const style = divs[i].getAttribute('style');
            const urlMatch = style.match(/url\("([^"]+)"\)/);

            if(urlMatch) {
                const url = urlMatch[1];
                const mapIdMatch = url.match(/\/(\d+)\//);

                if(mapIdMatch) {
                    const mapId = mapIdMatch[1];

                    if (addedMaps.has(mapId)) {
                        continue;
                    }

                    addButtonsWithEventListeners(mapId, subscribeButtons[i]);

                    addedMaps.add(mapId);
                } else {
                    console.log('Map ID not found');
                }
            } else {
                console.log('URL match not found');
            }
        }
    };

    function addControlsToSpecificMapPage() {
        var subscribeButton = document.querySelector('button.tw-button-transition.tw-outline-none.tw-shrink-0.tw-items-center.tw-justify-center.tw-space-x-2.tw-font-bold.tw-bg-theme-1--hover.tw-text-md[id^="input"]');
        if (!subscribeButton || document.getElementById('playButton') || document.getElementById('addToMapRotationButton')) {
            return;
        }

        var mapIdElement = document.querySelector('div.tw-justify-between.tw-items-center.tw-flex:last-child > span.tw-whitespace-nowrap:last-child > span');
        var mapId = mapIdElement.textContent;

        addButtonsWithEventListeners(mapId, subscribeButton, true);
    };

    function adjustElementStylesForMapsPage() {
        const elements = document.querySelectorAll('.tw-flex.tw-items-center.tw-flex-col.tw-absolute.tw-bottom-3.lg\\:tw-bottom-4.tw-inset-x-3.lg\\:tw-inset-x-4');

        elements.forEach((element) => {
            element.classList.remove('tw-absolute');
        });

        const elementsTwo = document.querySelectorAll('.tw-px-3.lg\\:tw-px-4.tw-pb-14.lg\\:tw-pb-\\[3\\.75rem\\]');
        elementsTwo.forEach((element) => {
            element.classList.remove('tw-pb-14');
            element.classList.remove('lg:tw-pb-[3.75rem]');
            element.classList.add('tw-pb-4');
        });
    }

    function addSelectElement(targetElement, position) {
        position === "before" ? targetElement.before(selectElementContainer) : targetElement.after(selectElementContainer);
    }

    var selectElementContainer = createSelectAndLabel();
    if (window.location.href === "https://mod.io/g/pavlov") {
        var targetElementSelector = 'md:tw-rounded-lg md:dark:tw-bg-dark-1 md:tw-bg-light-1 tw-border-opacity-40 tw-border-grey md:tw-border-0 tw-border-b md:tw-mb-2 tw-relative';
        var targetElement = document.getElementsByClassName(targetElementSelector)[1]
        addSelectElement(targetElement, 'after');

        var observerForAllMapsPage = new MutationObserver(function(mutationsList) {
            for (var mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    addButtonsToMapsPage();
                    adjustElementStylesForMapsPage();
                    break;
                }
            }
        });
        observerForAllMapsPage.observe(document.body, { childList: true, subtree: true });
    } else {
        var observerForSpecificMapPage = new MutationObserver(function(mutationsList) {
            for (var mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    addControlsToSpecificMapPage();
                    break;
                }
            }
        });
        observerForSpecificMapPage.observe(document.body, { childList: true, subtree: true });
    }
})();