☰

Sankaku Complex Video Download

Add a download button for Sankaku Complex videos

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         Sankaku Complex Video Download
// @namespace    https://www.example.com/
// @version      1.2
// @description  Add a download button for Sankaku Complex videos
// @match        https://www.sankakucomplex.com/*
// @grant        none
// @run-at       document-end
// @icon         https://www.sankakucomplex.com/images/favicon-32x32.png
// @license      none
// ==/UserScript==

(function() {
    'use strict';

    const BUTTON_ID = 'sankaku-video-source-button';
    const RETRY_DELAY = 300;
    const MAX_RETRIES = 20;
    const LOG_PREFIX = '[SankakuVideoDownload]';
    let navigationVersion = 0;

    function log(message, ...args) {
        console.debug(LOG_PREFIX, message, ...args);
    }

    function isPostPage() {
        const result = /^\/posts\/[^/?]+/.test(location.pathname);
        log('isPostPage', location.pathname, result);
        return result;
    }

    function getVideoSource() {
        const videos = Array.from(document.querySelectorAll('video')).filter(video => video.isConnected);
        if (!videos.length) return null;

        const scoredVideos = videos.map(video => {
            const rect = video.getBoundingClientRect();
            const style = getComputedStyle(video);
            const width = rect.width;
            const height = rect.height;
            const area = width * height;
            const isVisible = width > 0 && height > 0 && style.display !== 'none' && style.visibility !== 'hidden';
            const hasSource = !!(video.currentSrc || video.src || video.querySelector('source')?.src);
            const inMainContent = !!video.closest('main, article, .post-content, [role="main"]');
            const isPlaying = !video.paused && video.readyState >= 2;
            const hasControls = video.controls || video.getAttribute('controls') !== null;
            const score = Number(isVisible) * 5 + Number(hasSource) * 3 + Number(inMainContent) * 2 + Number(isPlaying) * 4 + Number(hasControls) + Math.min(area / 200000, 2);
            return { video, score };
        });

        const selected = scoredVideos.sort((a, b) => b.score - a.score)[0];
        if (!selected) return null;

        const video = selected.video;
        const src = video.currentSrc || video.src || video.querySelector('source')?.src || null;
        log('video lookup', { src, videoCount: videos.length, score: selected.score });
        return src;
    }

    function openVideoSourceInBackground(src) {
        if (!src) return false;

        const popup = window.open(src, '_blank', 'noopener,noreferrer');
        if (popup) {
            popup.opener = null;
            return true;
        }

        const tempLink = document.createElement('a');
        tempLink.href = src;
        tempLink.target = '_blank';
        tempLink.rel = 'noopener noreferrer';
        document.body.appendChild(tempLink);
        tempLink.click();
        tempLink.remove();
        return true;
    }

    function tryGetVideoSource(retries = 0, version = navigationVersion) {
        if (version !== navigationVersion) {
            log('ignoring stale video lookup', { version, navigationVersion });
            return;
        }

        const src = getVideoSource();
        log('tryGetVideoSource', { retries, src, version });
        if (src || retries >= 8) {
            if (src) {
                log('video source found', src);
                openVideoSourceInBackground(src);
            } else {
                log('video source missing after retries', retries);
                window.alert('No video found on this page.');
            }
            return;
        }

        setTimeout(() => tryGetVideoSource(retries + 1, version), 150);
    }

    function handleClick() {
        log('button clicked');
        navigationVersion += 1;
        setTimeout(() => tryGetVideoSource(0, navigationVersion), 600);
    }

    function ensureButton() {
        const existing = document.getElementById(BUTTON_ID);
        if (existing) {
            return existing;
        }

        const container = document.body || document.documentElement;
        if (!container) return null;

        const button = document.createElement('button');
        button.id = BUTTON_ID;
        button.type = 'button';
        button.title = 'Open video source';
        button.setAttribute('aria-label', 'Open video source');
        button.style.cssText = 'position:fixed;top:0.75rem;right:0.75rem;z-index:2147483647;display:inline-flex;align-items:center;justify-content:center;padding:0.35rem 0.6rem;font-size:0.95rem;line-height:1;cursor:pointer;border:1px solid #ccc;border-radius:0.25rem;background:#fff;box-shadow:0 2px 6px rgba(0,0,0,0.15);';
        button.innerHTML = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v10"></path><path d="m7 8 5 5 5-5"></path><path d="M5 14v3a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-3"></path></svg>';
        button.addEventListener('click', handleClick);

        container.appendChild(button);
        log('button created');
        return button;
    }

    const observer = new MutationObserver(() => {
        ensureButton();
    });
    if (document.body) {
        observer.observe(document.body, { childList: true, subtree: true });
    }

    const originalPushState = history.pushState;
    const originalReplaceState = history.replaceState;
    history.pushState = function(...args) {
        originalPushState.apply(this, args);
        window.dispatchEvent(new Event('locationchange'));
    };
    history.replaceState = function(...args) {
        originalReplaceState.apply(this, args);
        window.dispatchEvent(new Event('locationchange'));
    };
    window.addEventListener('popstate', () => {
        log('popstate');
        navigationVersion += 1;
        ensureButton();
        window.dispatchEvent(new Event('locationchange'));
    });
    window.addEventListener('locationchange', () => {
        log('locationchange', location.pathname);
        navigationVersion += 1;
        ensureButton();
    });

    ensureButton();
})();