☰

Rule34 Downloader

Descarga imágenes y vídeos de la Rule34 con un solo click.

คุณจะต้องติดตั้งส่วนขยาย เช่น Tampermonkey, Greasemonkey หรือ Violentmonkey เพื่อติดตั้งสคริปต์นี้

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

คุณจะต้องติดตั้งส่วนขยาย เช่น Tampermonkey หรือ Violentmonkey เพื่อติดตั้งสคริปต์นี้

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         Rule34 Downloader
// @namespace    https://github.com/RogzcaDev
// @version      1.0
// @description  Descarga imágenes y vídeos de la Rule34 con un solo click.
// @author       RogzcaDev
// @license      MIT
// @match        *://rule34.xxx/index.php?page=post&s=list*
// @grant        GM_download
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @connect      *
// ==/UserScript==

(function() {
    'use strict';

    const MAX_CONCURRENT_DOWNLOADS = 4;
    const DELAY_BETWEEN_REQUESTS_MS = 1000;

    // --- DICCIONARIO DE IDIOMAS (ES / EN) ---
    const I18N = {
        es: {
            download: '⬇ Descargar',
            downloaded: '✔ Descargado',
            blocked: '🚫 Bloqueado',
            blockedTitle: 'Bloqueado por filtro de etiquetas',
            queued: '⏳ En cola',
            searching: 'Buscando...',
            downloading: 'Bajando...',
            done: '✔ Listo (100%)',
            notFound: 'No hallado',
            error: '❌ Error',
            downloadAll: (n) => `⬇ Descargar todo (${n} nuevos)`,
            allDownloaded: '✔ Todo lo permitido descargado',
            downloadingStatus: (act, q) => `⏳ Descargando (${act} activos / ${q} en cola)`,
            videosOnly: (n) => `🎬 Solo videos (${n})`,
            folderLabel: '📁 Carpeta:',
            folderPlaceholder: 'Sin carpeta',
            subfoldersLabel: 'Subcarpetas (Videos/GIFs/Images)',
            blockLabel: '🚫 Bloquear:',
            blockPlaceholder: 'Ej: ai, 3d, furry...',
            confirmRedownload: 'Este archivo ya fue descargado anteriormente. ¿Quieres volver a descargarlo?'
        },
        en: {
            download: '⬇ Download',
            downloaded: '✔ Downloaded',
            blocked: '🚫 Blocked',
            blockedTitle: 'Blocked by tag filter',
            queued: '⏳ Queued',
            searching: 'Fetching...',
            downloading: 'Downloading...',
            done: '✔ Done (100%)',
            notFound: 'Not found',
            error: '❌ Error',
            downloadAll: (n) => `⬇ Download all (${n} new)`,
            allDownloaded: '✔ All allowed items downloaded',
            downloadingStatus: (act, q) => `⏳ Downloading (${act} active / ${q} queued)`,
            videosOnly: (n) => `🎬 Videos only (${n})`,
            folderLabel: '📁 Folder:',
            folderPlaceholder: 'No folder',
            subfoldersLabel: 'Subfolders (Videos/GIFs/Images)',
            blockLabel: '🚫 Block:',
            blockPlaceholder: 'Ex: ai, 3d, furry...',
            confirmRedownload: 'This file was already downloaded. Do you want to download it again?'
        }
    };

    // Detectar idioma guardado o usar el idioma del navegador por defecto
    const browserLang = (navigator.language || navigator.userLanguage || 'en').toLowerCase().startsWith('es') ? 'es' : 'en';
    let currentLang = GM_getValue('r34_ui_lang', browserLang);
    const t = () => I18N[currentLang] || I18N.en;

    // 1. Estilos globales ligeros
    const style = document.createElement('style');
    style.textContent = `
        .thumb {
            display: inline-flex !important;
            flex-direction: column !important;
            align-items: center !important;
            height: auto !important;
            vertical-align: top !important;
        }
        .r34-dl-btn {
            box-sizing: border-box;
            margin-top: 5px;
            height: 28px;
            padding: 0 8px;
            font-size: 12px;
            font-weight: bold;
            cursor: pointer;
            color: #ffffff;
            background-color: #388e3c;
            border: 1px solid #2e7d32;
            border-radius: 6px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            transition: background-color 0.15s;
            width: 150px;
        }
        .r34-dl-btn:hover:not(:disabled) {
            background-color: #43a047;
        }
        .r34-dl-btn.downloaded {
            background-color: #1565c0;
            border-color: #0d47a1;
        }
        .r34-dl-btn.downloaded:hover:not(:disabled) {
            background-color: #1976d2;
        }
        .r34-dl-btn.queued {
            background-color: #ef6c00;
            border-color: #e65100;
            cursor: not-allowed;
        }
        .r34-dl-btn.working {
            background-color: #555;
            border-color: #444;
            cursor: not-allowed;
        }
        .r34-dl-btn.error {
            background-color: #c62828;
            border-color: #b71c1c;
        }
        .r34-dl-btn.blocked {
            background-color: #757575 !important;
            border-color: #616161 !important;
            color: #e0e0e0 !important;
            cursor: not-allowed !important;
            opacity: 0.75;
        }
        .r34-top-bar {
            margin: 10px 0 15px 0;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
            gap: 12px;
            background: rgba(0, 0, 0, 0.06);
            padding: 8px 14px;
            border-radius: 8px;
        }
        .r34-control-group {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            font-weight: bold;
        }
        .r34-input, .r34-select {
            padding: 5px 8px;
            border-radius: 6px;
            border: 1px solid #888;
            font-size: 12px;
        }
        .r34-checkbox-label {
            display: flex;
            align-items: center;
            gap: 4px;
            cursor: pointer;
            user-select: none;
        }
    `;
    document.head.appendChild(style);

    // 2. Cargar configuraciones guardadas
    const downloadedSet = new Set(GM_getValue('r34_downloaded_ids', []));
    const savedBlockedRaw = GM_getValue('r34_blocked_tags_v4', 'ai');
    let baseFolder = GM_getValue('r34_base_folder', 'Rule34');
    let useSubfolders = GM_getValue('r34_use_subfolders', true);

    const parseBlockedTerms = (rawText) => {
        return rawText
            .split(',')
            .map(t => t.trim().toLowerCase().replace(/\s+/g, '_'))
            .filter(t => t.length > 0);
    };

    let blockedTermsList = parseBlockedTerms(savedBlockedRaw);

    const saveDownloadedId = (id) => {
        if (!downloadedSet.has(id)) {
            downloadedSet.add(id);
            GM_setValue('r34_downloaded_ids', Array.from(downloadedSet));
        }
    };

    const sanitizeFolderName = (name) => {
        return name.replace(/[<>:"/\\|?*]+/g, '').trim();
    };

    const buildDownloadPath = (postId, ext) => {
        const cleanExt = ext.toLowerCase();
        const parts = [];

        const cleanBase = sanitizeFolderName(baseFolder);
        if (cleanBase) {
            parts.push(cleanBase);
        }

        if (useSubfolders) {
            if (['mp4', 'webm', 'mkv', 'mov'].includes(cleanExt)) {
                parts.push('Videos');
            } else if (cleanExt === 'gif') {
                parts.push('GIFs');
            } else {
                parts.push('Images');
            }
        }

        parts.push(`r34_${postId}.${cleanExt}`);
        return parts.join('/');
    };

    // --- SISTEMA DE COLA DE DESCARGAS ---
    const downloadQueue = [];
    let activeDownloads = 0;

    const enqueueDownload = (taskFn) => {
        downloadQueue.push(taskFn);
        processQueue();
    };

    const processQueue = () => {
        while (activeDownloads < MAX_CONCURRENT_DOWNLOADS && downloadQueue.length > 0) {
            const nextTask = downloadQueue.shift();
            activeDownloads++;
            nextTask().finally(() => {
                activeDownloads--;
                setTimeout(processQueue, DELAY_BETWEEN_REQUESTS_MS);
            });
        }
        updateGlobalButtons();
    };

    // --- BARRA SUPERIOR ---
    const itemControls = [];
    let btnAll = null;
    let btnVideosOnly = null;
    let folderLabel = null;
    let folderInput = null;
    let subTextNode = null;
    let filterLabel = null;
    let filterInput = null;

    const updateGlobalButtons = () => {
        if (!btnAll || !btnVideosOnly) return;

        const pendingAll = itemControls.filter(i => !i.isBlocked() && !i.isDownloaded() && !i.isBusy()).length;
        const pendingVideos = itemControls.filter(i => !i.isBlocked() && i.isVideo && !i.isDownloaded() && !i.isBusy()).length;
        const inProgressCount = activeDownloads + downloadQueue.length;

        if (inProgressCount > 0) {
            btnAll.innerText = t().downloadingStatus(activeDownloads, downloadQueue.length);
        } else if (pendingAll > 0) {
            btnAll.innerText = t().downloadAll(pendingAll);
            btnAll.disabled = false;
            btnAll.style.backgroundColor = '#2e7d32';
            btnAll.style.cursor = 'pointer';
        } else {
            btnAll.innerText = t().allDownloaded;
            btnAll.disabled = true;
            btnAll.style.backgroundColor = '#1565c0';
            btnAll.style.cursor = 'default';
        }

        if (pendingVideos > 0) {
            btnVideosOnly.style.display = 'inline-block';
            btnVideosOnly.innerText = t().videosOnly(pendingVideos);
            btnVideosOnly.disabled = false;
        } else {
            btnVideosOnly.style.display = 'none';
        }
    };

    const refreshAllLanguageStrings = () => {
        if (folderLabel) folderLabel.innerText = t().folderLabel;
        if (folderInput) folderInput.placeholder = t().folderPlaceholder;
        if (subTextNode) subTextNode.nodeValue = t().subfoldersLabel;
        if (filterLabel) filterLabel.innerText = t().blockLabel;
        if (filterInput) filterInput.placeholder = t().blockPlaceholder;

        itemControls.forEach(ctrl => ctrl.refreshState());
        updateGlobalButtons();
    };

    const contentContainer = document.querySelector('.image-list') || document.querySelector('#post-list .content');
    if (contentContainer) {
        const topBar = document.createElement('div');
        topBar.className = 'r34-top-bar';

        btnAll = document.createElement('button');
        btnAll.style.cssText = 'padding: 7px 14px; font-size: 12px; font-weight: bold; color: #fff; border: 1px solid #1b5e20; border-radius: 6px;';
        btnAll.addEventListener('click', () => {
            itemControls.forEach(ctrl => {
                if (!ctrl.isBlocked() && !ctrl.isDownloaded() && !ctrl.isBusy()) ctrl.triggerDownload(true);
            });
            updateGlobalButtons();
        });

        btnVideosOnly = document.createElement('button');
        btnVideosOnly.style.cssText = 'padding: 7px 12px; font-size: 12px; font-weight: bold; color: #fff; background-color: #00695c; border: 1px solid #004d40; border-radius: 6px; cursor: pointer;';
        btnVideosOnly.addEventListener('click', () => {
            itemControls.forEach(ctrl => {
                if (!ctrl.isBlocked() && ctrl.isVideo && !ctrl.isDownloaded() && !ctrl.isBusy()) ctrl.triggerDownload(true);
            });
            updateGlobalButtons();
        });

        // Controles de carpetas
        const folderGroup = document.createElement('div');
        folderGroup.className = 'r34-control-group';

        folderLabel = document.createElement('span');
        folderLabel.innerText = t().folderLabel;

        folderInput = document.createElement('input');
        folderInput.type = 'text';
        folderInput.className = 'r34-input';
        folderInput.style.width = '100px';
        folderInput.placeholder = t().folderPlaceholder;
        folderInput.value = baseFolder;

        folderInput.addEventListener('input', () => {
            baseFolder = folderInput.value;
            GM_setValue('r34_base_folder', baseFolder);
        });

        const subLabel = document.createElement('label');
        subLabel.className = 'r34-checkbox-label';

        const subCheckbox = document.createElement('input');
        subCheckbox.type = 'checkbox';
        subCheckbox.checked = useSubfolders;
        subCheckbox.addEventListener('change', () => {
            useSubfolders = subCheckbox.checked;
            GM_setValue('r34_use_subfolders', useSubfolders);
        });

        subTextNode = document.createTextNode(t().subfoldersLabel);
        subLabel.appendChild(subCheckbox);
        subLabel.appendChild(subTextNode);

        folderGroup.appendChild(folderLabel);
        folderGroup.appendChild(folderInput);
        folderGroup.appendChild(subLabel);

        // Control del bloqueador
        const filterGroup = document.createElement('div');
        filterGroup.className = 'r34-control-group';

        filterLabel = document.createElement('span');
        filterLabel.innerText = t().blockLabel;

        filterInput = document.createElement('input');
        filterInput.type = 'text';
        filterInput.className = 'r34-input';
        filterInput.style.width = '150px';
        filterInput.placeholder = t().blockPlaceholder;
        filterInput.value = savedBlockedRaw;

        filterInput.addEventListener('input', () => {
            const rawVal = filterInput.value;
            GM_setValue('r34_blocked_tags_v4', rawVal);
            blockedTermsList = parseBlockedTerms(rawVal);

            itemControls.forEach(ctrl => ctrl.refreshState());
            updateGlobalButtons();
        });

        filterGroup.appendChild(filterLabel);
        filterGroup.appendChild(filterInput);

        // Selector de idioma manual (ES / EN)
        const langGroup = document.createElement('div');
        langGroup.className = 'r34-control-group';

        const langSelect = document.createElement('select');
        langSelect.className = 'r34-select';
        langSelect.title = 'Language / Idioma';

        const optEs = document.createElement('option');
        optEs.value = 'es';
        optEs.text = '🌐 ES';

        const optEn = document.createElement('option');
        optEn.value = 'en';
        optEn.text = '🌐 EN';

        langSelect.appendChild(optEs);
        langSelect.appendChild(optEn);
        langSelect.value = currentLang;

        langSelect.addEventListener('change', () => {
            currentLang = langSelect.value;
            GM_setValue('r34_ui_lang', currentLang);
            refreshAllLanguageStrings();
        });

        langGroup.appendChild(langSelect);

        topBar.appendChild(btnAll);
        topBar.appendChild(btnVideosOnly);
        topBar.appendChild(folderGroup);
        topBar.appendChild(filterGroup);
        topBar.appendChild(langGroup);
        contentContainer.parentNode.insertBefore(topBar, contentContainer);
    }

    // --- PROCESAR MINIATURAS ---
    const thumbs = document.querySelectorAll('.thumb');

    const AI_SPECIFIC_TAGS = new Set([
        'ai_generated', 'ai_assisted', 'ai_art', 'ai-generated', 'ai-assisted',
        'novelai', 'midjourney', 'stable_diffusion', 'dall-e', 'nai_diffusion'
    ]);

    thumbs.forEach(thumb => {
        const img = thumb.querySelector('img');
        const link = thumb.querySelector('a');
        if (!img || !link) return;

        const rawTitle = (img.title || img.alt || '').toLowerCase();
        const postTags = rawTitle
            .split(/\s+/)
            .filter(token => token && !token.startsWith('score:') && !token.startsWith('rating:'));

        const isVideo = postTags.includes('video') || postTags.includes('mp4') || postTags.includes('webm') || img.style.borderColor === 'blue';

        const idMatch = link.href.match(/[?&]id=(\d+)/);
        const postId = idMatch ? idMatch[1] : 'file';
        let isAlreadyDownloaded = downloadedSet.has(postId);
        let isBusy = false;
        let isBlocked = false;

        const btn = document.createElement('button');
        btn.className = 'r34-dl-btn';

        const checkIfBlocked = () => {
            if (blockedTermsList.length === 0) return false;
            return blockedTermsList.some(term => {
                if (term === 'ai') {
                    return postTags.some(tag => AI_SPECIFIC_TAGS.has(tag) || tag.startsWith('ai_'));
                }
                return postTags.some(tag => tag === term || tag.includes(term));
            });
        };

        const setNormalState = () => {
            isBusy = false;
            isBlocked = checkIfBlocked();
            btn.style.background = '';

            if (isBlocked) {
                btn.disabled = true;
                btn.className = 'r34-dl-btn blocked';
                btn.innerText = t().blocked;
                btn.title = t().blockedTitle;
            } else {
                btn.disabled = false;
                btn.title = '';
                btn.className = isAlreadyDownloaded ? 'r34-dl-btn downloaded' : 'r34-dl-btn';
                btn.innerText = isAlreadyDownloaded ? t().downloaded : t().download;
            }
            updateGlobalButtons();
        };

        setNormalState();

        const matchImgWidth = () => {
            if (img.offsetWidth > 0) btn.style.width = `${img.offsetWidth}px`;
        };
        if (img.complete) {
            matchImgWidth();
        } else {
            img.addEventListener('load', matchImgWidth, { once: true });
        }

        const downloadWithRealProgress = (mediaUrl, targetPath) => {
            return new Promise((resolve, reject) => {
                GM_xmlhttpRequest({
                    method: 'GET',
                    url: mediaUrl,
                    responseType: 'blob',
                    onprogress: (progress) => {
                        if (progress.lengthComputable && progress.total > 0) {
                            const percent = Math.round((progress.loaded / progress.total) * 100);
                            btn.innerText = `${t().downloading} ${percent}%`;
                            btn.style.background = `linear-gradient(90deg, #388e3c ${percent}%, #555 ${percent}%)`;
                        } else {
                            btn.innerText = t().downloading;
                        }
                    },
                    onload: (res) => {
                        if (res.status >= 200 && res.status < 300 && res.response) {
                            const blobUrl = URL.createObjectURL(res.response);
                            GM_download({
                                url: blobUrl,
                                name: targetPath,
                                onload: () => {
                                    URL.revokeObjectURL(blobUrl);
                                    resolve();
                                },
                                onerror: (err) => {
                                    URL.revokeObjectURL(blobUrl);
                                    reject(err);
                                }
                            });
                        } else {
                            reject(new Error(`HTTP ${res.status}`));
                        }
                    },
                    onerror: (err) => reject(err)
                });
            });
        };

        const executeDownloadTask = () => {
            return new Promise(async (resolve) => {
                btn.className = 'r34-dl-btn working';
                btn.innerText = t().searching;

                try {
                    const response = await fetch(link.href);
                    const htmlText = await response.text();
                    const doc = new DOMParser().parseFromString(htmlText, 'text/html');

                    let mediaUrl = null;
                    const videoSource = doc.querySelector('video source') || doc.querySelector('#gelcomVideoPlayer source');

                    if (videoSource && videoSource.src) {
                        mediaUrl = videoSource.src;
                    } else {
                        const originalLink = Array.from(doc.querySelectorAll('.sidebar a, #stats a, li a'))
                            .find(a => a.textContent.toLowerCase().includes('original image'));
                        mediaUrl = originalLink ? originalLink.href : (doc.querySelector('#image')?.src || null);
                    }

                    if (mediaUrl) {
                        btn.innerText = `${t().downloading} 0%`;
                        const ext = mediaUrl.split('?')[0].split('.').pop() || (isVideo ? 'mp4' : 'jpg');
                        const targetPath = buildDownloadPath(postId, ext);

                        await downloadWithRealProgress(mediaUrl, targetPath);

                        saveDownloadedId(postId);
                        isAlreadyDownloaded = true;
                        btn.style.background = '';
                        btn.style.backgroundColor = '#1b5e20';
                        btn.innerText = t().done;
                        setTimeout(setNormalState, 1200);
                        resolve();
                    } else {
                        btn.innerText = t().notFound;
                        setTimeout(setNormalState, 2000);
                        resolve();
                    }
                } catch (err) {
                    console.error('Error en descarga:', err);
                    btn.style.background = '';
                    btn.className = 'r34-dl-btn error';
                    btn.innerText = t().error;
                    setTimeout(setNormalState, 2500);
                    resolve();
                }
            });
        };

        const triggerDownload = (skipConfirm = false) => {
            if (isBusy || isBlocked) return;
            if (isAlreadyDownloaded && !skipConfirm) {
                if (!confirm(t().confirmRedownload)) return;
            }
            isBusy = true;
            btn.disabled = true;
            btn.style.background = '';
            btn.className = 'r34-dl-btn queued';
            btn.innerText = t().queued;
            enqueueDownload(executeDownloadTask);
        };

        btn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            triggerDownload(false);
        });

        thumb.appendChild(btn);

        itemControls.push({
            isVideo,
            isBlocked: () => isBlocked,
            isDownloaded: () => isAlreadyDownloaded,
            isBusy: () => isBusy,
            refreshState: () => { if (!isBusy) setNormalState(); },
            triggerDownload
        });
    });

    updateGlobalButtons();
})();