MacPS Button

Allows for people to join the private server whenever it's open.

Stan na 25-05-2026. Zobacz najnowsza wersja.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Greasemonkey lub Violentmonkey.

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

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana będzie instalacja rozszerzenia Tampermonkey lub Userscripts.

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

Aby zainstalować ten skrypt, musisz zainstalować rozszerzenie menedżera skryptów użytkownika.

(Mam już menedżera skryptów użytkownika, pozwól mi to zainstalować!)

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.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Musisz zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

(Mam już menedżera stylów użytkownika, pozwól mi to zainstalować!)

// ==UserScript==
// @name         MacPS Button
// @author       Mac
// @description Allows for people to join the private server whenever it's open.
// @version      1.23
// @namespace    MacPS
// @license MIT
// @match        https://cavegame.io/*
// @match        https://mineroyale.io/*
// @match        https://mineroyale.io/*
// @match        http://localhost:8080/*
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// @connect drive.google.com
// @connect drive.usercontent.google.com
// @connect      trycloudflare.com
// @connect      *.trycloudflare.com
// ==/UserScript==

(() => {
    'use strict';

    const CONFIG_URL = 'https://drive.google.com/uc?export=download&id=1F8AfmLdeXXcpdEGCm04hKYY2T22gbVmz';
    const REQUEST_TIMEOUT = 5000;
    const REFRESH_COOLDOWN = 1500;

    const STATE = Object.freeze({
        CHECKING: 'Checking...',
        ONLINE: 'Online',
        IDLE: 'Idle',
        OFFLINE: 'Offline',
        ERROR: 'Error',
        CONNECTING: 'Connecting...'
    });

    let currentState = STATE.CHECKING;
    let websocketTarget = '';
    let button = null;
    let refreshBtn = null;

    let refreshCooldown = 0;
    let refreshBusy = false;

    const NativeWebSocket = unsafeWindow.WebSocket;
    let wsHookActive = false;
    let wsConsumed = false;

    function isDarkMode() {
        const btn =
            document.getElementById('play-cavegame-io') ||
            document.getElementById('play-mineroyale-io');
        return btn?.classList.contains('dark');
    }

    function isLocked() {
        return currentState === STATE.CHECKING || currentState === STATE.CONNECTING;
    }

    function isMainDisabled() {
        return isDarkMode() || currentState === STATE.ERROR || isLocked();
    }

    function isRefreshDisabled() {
        return isDarkMode() || refreshBusy || isLocked() || Date.now() < refreshCooldown;
    }

    function applyMainButtonState() {
        if (!button) return;

        const disabled = isMainDisabled();

        const s = button.querySelector('.macps-status');
        if (s) {
            s.textContent = currentState;
            s.style.color = getStateColor(currentState);
            s.style.fontWeight = '700';
        }

        button.style.background = 'linear-gradient(-225deg,#4da3ff,#1e66d0)';
        button.style.color = '#fff';
        button.style.border = 'none';

        button.style.opacity = disabled ? '0.6' : '1';
        button.style.pointerEvents = disabled ? 'none' : 'auto';
        button.style.cursor = disabled ? 'not-allowed' : 'pointer';
    }

    function enableWSHook() {
        wsHookActive = true;
        wsConsumed = false;

        unsafeWindow.WebSocket = function (...args) {
            let url = args[0];

            if (!wsHookActive || wsConsumed) {
                return new NativeWebSocket(url, ...args.slice(1));
            }

            wsConsumed = true;
            wsHookActive = false;

            if (
                typeof url === 'string' &&
                websocketTarget &&
                (url.startsWith('ws://') || url.startsWith('wss://'))
            ) {
                url = websocketTarget;
            }

            return new NativeWebSocket(url, ...args.slice(1));
        };

        unsafeWindow.WebSocket.prototype = NativeWebSocket.prototype;
    }

    function disableWSHook() {
        wsHookActive = false;
        unsafeWindow.WebSocket = NativeWebSocket;
    }

    function request(url) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: 'GET',
                url,
                timeout: REQUEST_TIMEOUT,
                onload: resolve,
                onerror: reject,
                ontimeout: reject
            });
        });
    }

    function setState(state, target = '') {
        currentState = state;
        if (target) websocketTarget = target;
        updateUI();
        applyMainButtonState();
    }

    function isValidWebSocketURL(url) {
        try {
            const u = new URL(url);
            return u.protocol === 'wss:' && u.hostname.length > 0;
        } catch {
            return false;
        }
    }

    function getStateColor(state) {
        switch (state) {
            case STATE.ONLINE: return '#22c55e';
            case STATE.IDLE: return '#f59e0b';
            case STATE.CHECKING:
            case STATE.CONNECTING: return '#9ca3af';
            default: return '#ef4444';
        }
    }

    async function fetchServerAddress() {
        try {
            const res = await request(CONFIG_URL);
            const text = (res.responseText || '').trim();
            return isValidWebSocketURL(text) ? text : null;
        } catch {
            return null;
        }
    }

    async function verifyServer(url) {
        return new Promise(resolve => {
            let ws;
            let done = false;

            const finish = ok => {
                if (done) return;
                done = true;
                try { ws?.close(); } catch {}
                resolve(ok);
            };

            try {
                ws = new WebSocket(url);
                const t = setTimeout(() => finish(false), 4000);

                ws.onopen = () => {
                    clearTimeout(t);
                    finish(true);
                };

                ws.onerror = () => {
                    clearTimeout(t);
                    finish(false);
                };
            } catch {
                finish(false);
            }
        });
    }

    async function refreshServerStatus() {
        if (isDarkMode()) return;

        refreshBusy = true;
        setState(STATE.CHECKING);

        const url = await fetchServerAddress();

        if (!url) {
            setState(STATE.ERROR);
            refreshBusy = false;
            refreshCooldown = Date.now() + REFRESH_COOLDOWN;
            return;
        }

        const ok = await verifyServer(url);
        setState(ok ? STATE.ONLINE : STATE.OFFLINE, ok ? url : '');

        refreshBusy = false;
        refreshCooldown = Date.now() + REFRESH_COOLDOWN;
    }

    function updateUI() {
        updateButton();
        updateRefresh();
    }

    function updateButton() {
        applyMainButtonState();
    }

    function updateRefresh() {
        if (!refreshBtn) return;

        const locked = isRefreshDisabled();

        refreshBtn.style.background = '#e5e7eb';
        refreshBtn.style.color = '#111';
        refreshBtn.style.border = 'none';
        refreshBtn.style.width = '55px';
        refreshBtn.style.height = '42px';
        refreshBtn.style.display = 'flex';
        refreshBtn.style.alignItems = 'center';
        refreshBtn.style.justifyContent = 'center';

        refreshBtn.style.cursor = locked ? 'not-allowed' : 'pointer';
        refreshBtn.style.opacity = locked ? '0.6' : '1';
        refreshBtn.style.filter = locked ? 'grayscale(1)' : 'none';
    }

    function onMainClick(e) {
        e.preventDefault();
        e.stopPropagation();

        if (isMainDisabled()) return;
        if (!websocketTarget) return;

        setState(STATE.CONNECTING);

        enableWSHook();

        const play =
            document.getElementById('play-mineroyale-io') ||
            document.getElementById('play-cavegame-io');

        play?.click();
    }

    function onRefreshClick(e) {
        e.preventDefault();
        e.stopPropagation();

        if (isRefreshDisabled()) return;
        refreshServerStatus();
    }

    function isMenuOpen() {
        const overlay = document.getElementById('menu-overlay');
        return overlay && getComputedStyle(overlay).display !== 'none';
    }

    let wasOpen = false;

    function watchMenu() {
        const open = isMenuOpen();

        if (open && !wasOpen) {
            refreshServerStatus();
            updateUI();
        }

        wasOpen = open;
    }

    function createUI() {
        const c = document.getElementById('sub-play-btn-cont');
        if (!c || document.getElementById('cg-macps-wrap')) return;

        const wrap = document.createElement('div');
        wrap.id = 'cg-macps-wrap';
        wrap.style.display = 'inline-flex';
        wrap.style.alignItems = 'center';
        wrap.style.width = '94%';

        button = document.createElement('button');
        button.className = 'play-btn';
        button.innerHTML = `MacPS <div class="macps-status">${currentState}</div>`;
        button.addEventListener('click', onMainClick);

        refreshBtn = document.createElement('button');
        refreshBtn.textContent = '↻';
        refreshBtn.addEventListener('click', onRefreshClick);

        wrap.appendChild(button);
        wrap.appendChild(refreshBtn);
        c.appendChild(wrap);

        updateUI();
    }

    new MutationObserver(() => {
        if (!document.getElementById('cg-macps-wrap')) createUI();
    }).observe(document.body, { childList: true, subtree: true });

    setInterval(() => {
        watchMenu();
        updateRefresh();
    }, 50);

    createUI();
})();