Advanced YouTube Age Restriction Bypass Pro

Watch age-restricted YouTube videos without login or age verification 😎 with enhanced features!

// ==UserScript==
// @name         Advanced YouTube Age Restriction Bypass Pro
// @description  Watch age-restricted YouTube videos without login or age verification 😎 with enhanced features!
// @version      4.1.0
// @author       Zerody (Enhanced by Cody)
// @namespace    https://github.com/zerodytrash/Simple-YouTube-Age-Restriction-Bypass/
// @supportURL   https://github.com/zerodytrash/Simple-YouTube-Age-Restriction-Bypass/issues
// @license      MIT
// @match        https://www.youtube.com/*
// @match        https://www.youtube-nocookie.com/*
// @match        https://m.youtube.com/*
// @match        https://music.youtube.com/*
// @grant        none
// @run-at       document-start
// @compatible   chrome
// @compatible   firefox
// @compatible   opera
// @compatible   edge
// @compatible   safari
// ==/UserScript==

(function () {
    'use strict';

    // Configuration constants
    const CONFIG = {
        ENABLE_UNLOCK_NOTIFICATION: true,
        ENABLE_AUTO_AD_SKIPPER: true,
        DEFAULT_VIDEO_QUALITY: '1080p', // Options: '144p', '240p', '360p', '480p', '720p', '1080p', '4K'
        ENABLE_ERROR_REPORTING: true,
        COUNTRY_SPECIFIC_PROXIES: {
            US: 'https://us-proxy.server.com',
            EU: 'https://eu-proxy.server.com',
        },
        RATE_LIMIT_REQUESTS: 10,
        LOG_LEVEL: 'INFO', // Levels: INFO, WARN, ERROR
    };

    const UNLOCKABLE_PLAYABILITY_STATUSES = ['AGE_VERIFICATION_REQUIRED', 'CONTENT_WARNING'];
    let rateLimitCount = 0;

    const logger = {
        info: (msg) => logMessage('INFO', msg),
        warn: (msg) => logMessage('WARN', msg),
        error: (msg) => logMessage('ERROR', msg),
    };

    function logMessage(level, msg) {
        if (['INFO', 'WARN', 'ERROR'].indexOf(level) >= ['INFO', 'WARN', 'ERROR'].indexOf(CONFIG.LOG_LEVEL)) {
            console.log(`%cYouTube Bypass Pro [${level}]`, `color: ${getLogColor(level)};`, msg);
        }
    }

    function getLogColor(level) {
        return {
            INFO: 'blue',
            WARN: 'orange',
            ERROR: 'red',
        }[level] || 'black';
    }

    // Dynamic notification system
    function showNotification(message) {
        if (!CONFIG.ENABLE_UNLOCK_NOTIFICATION) return;
        const notification = document.createElement('div');
        notification.textContent = message;
        Object.assign(notification.style, {
            position: 'fixed',
            bottom: '10px',
            right: '10px',
            backgroundColor: '#007BFF',
            color: '#FFF',
            padding: '10px',
            borderRadius: '5px',
            zIndex: 9999,
            fontSize: '14px',
        });
        document.body.appendChild(notification);
        setTimeout(() => notification.remove(), 5000);
    }

    // Country-specific proxy selection
    function getProxyForCountry(countryCode) {
        return CONFIG.COUNTRY_SPECIFIC_PROXIES[countryCode] || Object.values(CONFIG.COUNTRY_SPECIFIC_PROXIES)[0];
    }

    // Auto-skip ads
    function enableAdSkipper() {
        if (!CONFIG.ENABLE_AUTO_AD_SKIPPER) return;

        const observer = new MutationObserver((mutations) => {
            mutations.forEach(() => {
                const skipButton = document.querySelector('.ytp-ad-skip-button');
                if (skipButton) {
                    skipButton.click();
                    logger.info('Skipped an ad.');
                    observer.disconnect(); // Temporarily stop observing
                    setTimeout(() => observer.observe(document.body, { childList: true, subtree: true }), 1000); // Reconnect
                }
            });
        });

        observer.observe(document.body, { childList: true, subtree: true });
    }

    // Video quality enforcement
    function setDefaultVideoQuality() {
        const observer = new MutationObserver(() => {
            const settingsButton = document.querySelector('.ytp-settings-button');
            if (settingsButton) {
                settingsButton.click();

                const interval = setInterval(() => {
                    const qualityMenu = [...document.querySelectorAll('.ytp-menuitem')].find(
                        (item) => item.textContent.includes(CONFIG.DEFAULT_VIDEO_QUALITY)
                    );
                    if (qualityMenu) {
                        qualityMenu.click();
                        logger.info(`Set video quality to ${CONFIG.DEFAULT_VIDEO_QUALITY}`);
                        clearInterval(interval);
                    }
                }, 200);

                observer.disconnect();
            }
        });

        observer.observe(document.body, { childList: true, subtree: true });
    }

    // Error reporting
    function reportError(error) {
        if (!CONFIG.ENABLE_ERROR_REPORTING) return;
        fetch('https://error-reporting.server.com/report', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ error: error.message, timestamp: new Date().toISOString() }),
        });
        logger.error('Error reported to server.');
    }

    // Unlock video response
    async function unlockResponse(response) {
        try {
            if (response.playabilityStatus && UNLOCKABLE_PLAYABILITY_STATUSES.includes(response.playabilityStatus.status)) {
                showNotification('Attempting to unlock video...');
                const proxy = getProxyForCountry('US');

                const unlockedResponse = await fetch(`${proxy}/unlock`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ videoId: response.videoDetails.videoId }),
                }).then((res) => res.json());

                if (unlockedResponse.errorMessage) {
                    throw new Error(unlockedResponse.errorMessage);
                }

                Object.assign(response, unlockedResponse);
                logger.info('Video unlocked successfully.');
                showNotification('Video unlocked successfully!');
            }
        } catch (error) {
            logger.warn(`Proxy failed: ${error.message}. Retrying with fallback...`);
            const fallbackProxy = getProxyForCountry('EU');
            if (fallbackProxy && fallbackProxy !== proxy) {
                unlockResponse({ ...response, proxy: fallbackProxy });
            } else {
                reportError(error);
                logger.error(`Failed to unlock video: ${error.message}`);
                showNotification('Failed to unlock video.');
            }
        }
    }

    // Hook into XMLHttpRequest.open
    const nativeXHROpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (method, url, ...args) {
        if (url.includes('/youtubei/v1/player')) {
            this.addEventListener('readystatechange', function () {
                if (this.readyState === 4 && this.status === 200) {
                    try {
                        const response = JSON.parse(this.responseText);
                        unlockResponse(response);
                        this.responseText = JSON.stringify(response);
                    } catch (err) {
                        logger.error('Error processing video response: ' + err.message);
                    }
                }
            });
        }
        nativeXHROpen.call(this, method, url, ...args);
    };

    // Initialize script features
    function init() {
        logger.info('Initializing Advanced YouTube Bypass Pro...');
        enableAdSkipper();
        setDefaultVideoQuality();
        logger.info('Features initialized successfully!');
    }

    init();
})();