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

Ajankohdalta 18.6.2023. Katso uusin versio.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

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

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

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

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

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         Pavlov mod.io maps integration with pavlovrcon.com
// @namespace    https://greasyfork.org/en/users/1103172-underpl
// @version      1.5
// @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/*
// @match        https://mod.io/g/pavlov?_sort=*
// @match        https://mod.io/g/pavlov?tags-in=*
// @match        https://mod.io/g/pavlov?platforms*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(function() {
    'use strict';
    var currentPage = window.location.href;
    var defaultGameMode = "INFECTION";
    var storedGameMode = GM_getValue("storedGameMode", defaultGameMode);
     GM_setValue("storedGameMode", storedGameMode);

    var defaultServerId = "0";
    var storedServerId = GM_getValue("storedServerId", defaultServerId);
    GM_setValue("storedServerId", storedServerId);

    const mapsPageRegex = new RegExp("^https:\/\/mod\.io\/g\/pavlov(?:$|\\?tags-in=|\\?_sort=|\\?platforms)");

    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 createSelectsAndLabels() {
        var container = document.createElement('div');
        container.style.cssText = 'justify-content:center;' + (currentPage.startsWith('https://mod.io/g/pavlov/m/') ? 'display:flex;' : "");

        var serverIdDiv = document.createElement('div');
        var serverIdLabel = document.createElement('label');
        serverIdLabel.innerHTML = 'SERVER ID:';
        serverIdLabel.style.cssText = 'font-size: 150%; margin: 0px 10px;';
        serverIdDiv.appendChild(serverIdLabel);

        var serverIdSelect = document.createElement('select');
        serverIdSelect.id = "serverIds";
        serverIdSelect.classList.add("form-select");
        serverIdSelect.style.cssText = "color: black; font-size: 155%; padding-left: 5px; text-align: center; display: inline-block; margin: 0 auto;";
        serverIdDiv.appendChild(serverIdSelect);

        serverIdSelect.innerHTML = Array.from({length: 10}, (_, i) => i)
        .map(id => `<option value="${id}" ${storedServerId == id ? 'selected' : ''}>${id}</option>`).join('');

        serverIdSelect.addEventListener('change', function() {
            storedServerId = serverIdSelect.value;
            GM_setValue("storedServerId", storedServerId);
        });

        var gameModeDiv = document.createElement('div');
        var gameModeLabel = document.createElement('label');
        gameModeLabel.innerHTML = 'MODE:';
        gameModeLabel.style.cssText = 'font-size: 150%; margin: 0px 10px;';
        gameModeDiv.appendChild(gameModeLabel);

        var gameModeSelect = document.createElement('select');
        gameModeSelect.id = "gameModes";
        gameModeSelect.classList.add("form-select");
        gameModeSelect.style.cssText = "color: black; font-size: 150%; padding-left: 5px; text-align: center; display: inline-block; margin: 0 auto;";
        gameModeDiv.appendChild(gameModeSelect);

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

        gameModeSelect.addEventListener('change', function() {
            storedGameMode = gameModeSelect.value;
            GM_setValue("storedGameMode", storedGameMode);
        });

        container.appendChild(serverIdDiv);
        container.appendChild(gameModeDiv);

        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}/${storedServerId}`,
            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.querySelectorAll('select')[1];
        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 = createSelectsAndLabels();

    if (mapsPageRegex.test(currentPage)) {
        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 });
    }
})();