☰

PH Feed - Instant WebM Cache + Download

Instantly cache feed WebM videos, open them in a pseudo-fullscreen overlay, and download the cached video

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 or Violentmonkey to install this script.

Tendrás que 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.

Tendrás que instalar una extensión como Tampermonkey antes de poder 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)

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

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

// ==UserScript==
// @name         PH Feed - Instant WebM Cache + Download
// @namespace    local
// @version      1.2.0
// @description  Instantly cache feed WebM videos, open them in a pseudo-fullscreen overlay, and download the cached video
// @match        https://www.pornhub.com/*
// @grant        GM_download
// @grant        GM_xmlhttpRequest
// @connect      phncdn.com
// @run-at       document-idle
// ==/UserScript==

(() => {
    'use strict';

    const BUTTON_CLASS = 'userscript-webm-button';

    // URL -> Promise<Blob>
    const blobCache = new Map();

    // Prevent duplicate fetches.
    const fetching = new Set();

    /*
     * Start caching immediately.
     *
     * The request begins as soon as a video appears in the feed.
     * The returned Promise resolves to the complete video Blob.
     */
    function cacheVideo(url) {
        if (!url) return null;

        // Already cached.
        if (blobCache.has(url)) {
            return blobCache.get(url);
        }

        // Already being fetched.
        if (fetching.has(url)) {
            return blobCache.get(url);
        }

        fetching.add(url);

        const promise = fetch(url, {
            method: 'GET',
            credentials: 'omit',
            cache: 'force-cache'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }

                return response.blob();
            })
            .then(blob => {
                if (!blob || !blob.size) {
                    throw new Error('Empty video response');
                }

                blobCache.set(url, Promise.resolve(blob));
                return blob;
            })
            .catch(error => {
                console.warn('[WebM Cache]', error);

                // Remove failed cache entry so it can be retried.
                blobCache.delete(url);

                throw error;
            })
            .finally(() => {
                fetching.delete(url);
            });

        blobCache.set(url, promise);

        return promise;
    }

    function getWebmUrl(element) {
        const link = element.querySelector('[data-webm]');
        if (!link) return null;

        return link
            .getAttribute('data-webm')
            ?.replace(/&amp;/g, '&');
    }

    function createOverlay(url, title = 'Video') {
        const old = document.getElementById('userscript-webm-overlay');
        if (old) old.remove();

        const overlay = document.createElement('div');
        overlay.id = 'userscript-webm-overlay';

        overlay.innerHTML = `
            <div class="uw-overlay-bg"></div>

            <div class="uw-player-wrap">
                <video
                    class="uw-video"
                    controls
                    autoplay
                    playsinline
                    preload="auto"
                ></video>

                <div class="uw-toolbar">
                    <span class="uw-title"></span>

                    <button class="uw-download" title="Download video">
                        ↓
                    </button>

                    <button class="uw-close" title="Close">
                        ×
                    </button>
                </div>
            </div>
        `;

        overlay.querySelector('.uw-title').textContent = title;

        document.body.appendChild(overlay);

        const video = overlay.querySelector('.uw-video');
        const downloadButton = overlay.querySelector('.uw-download');

        /*
         * Use the already-started cache request.
         *
         * The video itself can also use the original CDN URL immediately,
         * so playback does not have to wait for the complete Blob.
         */
        video.src = url;

        // Real browser fullscreen on double-click.
        video.addEventListener('dblclick', () => {
            if (video.requestFullscreen) {
                video.requestFullscreen().catch(() => {});
            }
        });

        /*
         * Download the cached Blob.
         *
         * If caching is still in progress, await the same Promise.
         * No duplicate network request is made.
         */
        downloadButton.addEventListener('click', async (e) => {
            e.stopPropagation();

            if (downloadButton.disabled) return;

            const originalText = downloadButton.textContent;

            try {
                downloadButton.disabled = true;
                downloadButton.textContent = '…';

                const blobPromise = blobCache.get(url);

                const blob = blobPromise
                    ? await blobPromise
                    : await cacheVideo(url);

                if (!blob || !blob.size) {
                    throw new Error('Video cache is empty');
                }

                const blobUrl = URL.createObjectURL(blob);
                const filename = makeFilename(title);

                const a = document.createElement('a');

                a.href = blobUrl;
                a.download = filename;
                a.style.display = 'none';

                document.body.appendChild(a);
                a.click();
                a.remove();

                // Keep the Blob URL alive briefly for the browser.
                setTimeout(() => {
                    URL.revokeObjectURL(blobUrl);
                }, 10000);

                downloadButton.textContent = '✓';

                setTimeout(() => {
                    if (downloadButton.isConnected) {
                        downloadButton.textContent = originalText;
                    }
                }, 1500);

            } catch (error) {
                console.error('[WebM Downloader]', error);

                downloadButton.textContent = '×';

                setTimeout(() => {
                    if (downloadButton.isConnected) {
                        downloadButton.textContent = originalText;
                    }
                }, 1500);

            } finally {
                downloadButton.disabled = false;
            }
        });

        function close() {
            video.pause();
            video.removeAttribute('src');
            video.load();

            overlay.remove();

            document.body.style.overflow = '';
        }

        overlay.querySelector('.uw-close')
            .addEventListener('click', close);

        overlay.querySelector('.uw-overlay-bg')
            .addEventListener('click', close);

        function escHandler(e) {
            if (e.key === 'Escape') {
                close();
                document.removeEventListener('keydown', escHandler);
            }
        }

        document.addEventListener('keydown', escHandler);

        document.body.style.overflow = 'hidden';
    }

    function makeFilename(title) {
        let name = title
            .replace(/[\\/:*?"<>|]/g, '')
            .replace(/\s+/g, ' ')
            .trim();

        if (!name) {
            name = 'video';
        }

        return name.slice(0, 180) + '.mp4';
    }

    function addButton(videoItem) {
        if (videoItem.querySelector(`.${BUTTON_CLASS}`)) return;

        const url = getWebmUrl(videoItem);
        if (!url) return;

        const title =
            videoItem.querySelector('.thumbnailTitle')
                ?.textContent
                ?.trim() ||
            videoItem.querySelector('.videoThumb')?.alt ||
            'Video';

        /*
         * IMPORTANT:
         * Start downloading/caching immediately when this feed item
         * is discovered.
         */
        cacheVideo(url);

        const button = document.createElement('button');

        button.className = BUTTON_CLASS;
        button.type = 'button';
        button.textContent = '⛶';
        button.title = 'Open video';

        button.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();

            createOverlay(url, title);
        });

        const wrapper =
            videoItem.querySelector('.singleVideo') ||
            videoItem.querySelector('.videoWrapper');

        if (!wrapper) return;

        wrapper.style.position = 'relative';
        wrapper.appendChild(button);
    }

    function scan() {
        document
            .querySelectorAll('li[data-video-id]')
            .forEach(addButton);
    }

    const style = document.createElement('style');

    style.textContent = `
        .${BUTTON_CLASS} {
            position: absolute !important;
            right: 5px !important;
            bottom: 5px !important;

            width: 24px !important;
            height: 24px !important;

            min-width: 24px !important;
            min-height: 24px !important;

            padding: 0 !important;
            margin: 0 !important;

            border: 0 !important;
            border-radius: 4px !important;

            background: rgba(0, 0, 0, .72) !important;
            color: #fff !important;

            font-size: 13px !important;
            line-height: 24px !important;
            text-align: center !important;

            cursor: pointer !important;
            z-index: 9999 !important;

            opacity: .65;

            transition:
                opacity .12s ease,
                transform .12s ease;
        }

        .${BUTTON_CLASS}:hover {
            opacity: 1;
            transform: scale(1.08);
        }

        .${BUTTON_CLASS}:disabled {
            cursor: wait !important;
            opacity: .8 !important;
        }

        #userscript-webm-overlay {
            position: fixed !important;
            inset: 0 !important;

            width: 100vw !important;
            height: 100vh !important;

            z-index: 2147483647 !important;

            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .uw-overlay-bg {
            position: absolute !important;
            inset: 0 !important;

            background: rgba(0, 0, 0, .94) !important;
        }

        .uw-player-wrap {
            position: relative !important;

            width: min(96vw, 1400px) !important;
            max-height: 94vh !important;

            display: flex !important;
            flex-direction: column !important;

            z-index: 1 !important;
        }

        .uw-video {
            display: block !important;

            width: 100% !important;
            max-width: 100% !important;
            max-height: calc(94vh - 34px) !important;

            object-fit: contain !important;

            background: #000 !important;

            border-radius: 4px !important;
        }

        .uw-toolbar {
            height: 30px !important;

            display: flex !important;
            align-items: center !important;

            gap: 5px !important;

            padding: 2px 3px !important;

            color: #aaa !important;

            font-family: Arial, sans-serif !important;
            font-size: 11px !important;
        }

        .uw-title {
            flex: 1 !important;

            overflow: hidden !important;
            white-space: nowrap !important;
            text-overflow: ellipsis !important;
        }

        .uw-download,
        .uw-close {
            width: 25px !important;
            height: 25px !important;

            padding: 0 !important;
            margin: 0 !important;

            border: 0 !important;
            border-radius: 3px !important;

            background: rgba(255,255,255,.08) !important;
            color: #ddd !important;

            cursor: pointer !important;

            font-size: 15px !important;
            line-height: 25px !important;
            text-align: center !important;
        }

        .uw-download:hover,
        .uw-close:hover {
            background: rgba(255,255,255,.18) !important;
            color: #fff !important;
        }

        .uw-download:disabled {
            cursor: wait !important;
            opacity: .6 !important;
        }

        .uw-close {
            font-size: 18px !important;
        }
    `;

    document.head.appendChild(style);

    // Initial scan.
    scan();

    /*
     * PH dynamically adds feed items.
     * Newly discovered videos are immediately cached.
     */
    const observer = new MutationObserver(() => {
        scan();
    });

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

})();