Nijie Popup Preview & Downloader

Show a popup preview next to the hovered thumbnail, add download button on the thumbnail, strictly filter unwanted filter/mask images, and download as a multilingual ZIP archive.

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

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

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

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         Nijie Popup Preview & Downloader
// @namespace    http://tampermonkey.net/
// @version      3.7
// @description  Show a popup preview next to the hovered thumbnail, add download button on the thumbnail, strictly filter unwanted filter/mask images, and download as a multilingual ZIP archive.
// @author       (´・ω・`)
// @license      MIT
// @match        *://nijie.info/*
// @icon         https://nijie.info/icon/favicon.ico?1786790486
// @require      https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js
// @grant        none
// ==/UserScript==

/*
MIT License

Copyright (c) 2026 (´・ω・`)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

(function() {
    'use strict';

    // --- Internationalization (i18n) setup ---
    const isJapanese = (navigator.language || navigator.userLanguage || '').toLowerCase().startsWith('ja');
    const i18n = {
        loading: isJapanese ? '読み込み中...' : 'Loading...',
        error: isJapanese ? 'エラーが発生しました' : 'An error occurred',
        notFound: isJapanese ? '画像が見つかりません' : 'No images found',
        wheel: isJapanese ? '(ホイールで切替)' : '(Wheel to switch)',
        zipping: isJapanese ? 'ZIP作成中...' : 'Zipping...',
        zipError: isJapanese ? 'ZIP作成に失敗しました' : 'Failed to create ZIP'
    };

    // --- Create popup element and set styles ---
    const popup = document.createElement('div');
    popup.id = 'nijie-hover-popup';
    Object.assign(popup.style, {
        position: 'fixed',
        backgroundColor: 'rgba(0, 0, 0, 0.85)',
        border: '2px solid #555',
        borderRadius: '8px',
        padding: '10px',
        zIndex: '999999',
        display: 'none',
        flexDirection: 'column',
        alignItems: 'center',
        boxShadow: '0 4px 15px rgba(0,0,0,0.6)',
        transition: 'opacity 0.15s ease-in-out',
        opacity: '0',
        boxSizing: 'border-box',
        pointerEvents: 'none'
    });

    const counterEl = document.createElement('div');
    Object.assign(counterEl.style, {
        color: '#fff',
        marginBottom: '8px',
        fontSize: '14px',
        fontWeight: 'bold',
        fontFamily: 'sans-serif',
        textShadow: '1px 1px 2px #000'
    });

    const imgEl = document.createElement('img');
    Object.assign(imgEl.style, {
        maxWidth: 'calc(100vw - 40px)', 
        maxHeight: 'calc(100vh - 80px)',
        objectFit: 'contain',
        display: 'none',
        borderRadius: '4px'
    });

    popup.appendChild(counterEl);
    popup.appendChild(imgEl);
    document.body.appendChild(popup);

    // --- Create Thumbnail Overlay Download Button ---
    const thumbDownloadBtn = document.createElement('button');
    thumbDownloadBtn.innerHTML = '📥';
    Object.assign(thumbDownloadBtn.style, {
        position: 'absolute',
        top: '8px',
        right: '8px',
        backgroundColor: '#3498db',
        color: '#fff',
        border: 'none',
        borderRadius: '4px',
        width: '32px',
        height: '32px',
        fontSize: '16px',
        cursor: 'pointer',
        zIndex: '99998',
        display: 'none',
        alignItems: 'center',
        justifyContent: 'center',
        boxShadow: '0 2px 6px rgba(0,0,0,0.4)',
        transition: 'background-color 0.2s'
    });
    thumbDownloadBtn.addEventListener('mouseover', () => thumbDownloadBtn.style.backgroundColor = '#2980b9');
    thumbDownloadBtn.addEventListener('mouseout', () => thumbDownloadBtn.style.backgroundColor = '#3498db');
    document.body.appendChild(thumbDownloadBtn);

    // --- State management variables ---
    let currentImages = [];
    let currentIndex = 0;
    let currentPopupId = null; 
    let activeThumbnail = null;
    const cache = {};
    const indexCache = {};

    // --- Core functions ---

    function renderImage() {
        imgEl.src = currentImages[currentIndex];
        imgEl.style.display = 'block';
        if (currentImages.length > 1) {
            counterEl.textContent = `${currentIndex + 1} / ${currentImages.length} ${i18n.wheel}`;
            counterEl.style.display = 'block';
        } else {
            counterEl.style.display = 'none';
        }
        updatePopupPosition();
    }

    function updatePopupPosition() {
        if (popup.style.display === 'none' || !activeThumbnail) return;
        
        const thumbRect = activeThumbnail.getBoundingClientRect();
        const pWidth = popup.offsetWidth;
        const pHeight = popup.offsetHeight;
        
        const gap = 15;
        let left = thumbRect.right + gap;
        let top = thumbRect.top;

        if (left + pWidth > window.innerWidth - 10) {
            left = thumbRect.left - pWidth - gap;
        }
        
        if (left < 10) {
            left = 10;
        }

        if (top + pHeight > window.innerHeight - 10) {
            top = window.innerHeight - pHeight - 10;
        }
        
        if (top < 10) top = 10;

        popup.style.left = left + 'px';
        popup.style.top = top + 'px';
        popup.style.right = 'auto';
        popup.style.bottom = 'auto';

        thumbDownloadBtn.style.display = 'flex';
        thumbDownloadBtn.style.top = (window.scrollY + thumbRect.top + 6) + 'px';
        thumbDownloadBtn.style.left = (window.scrollX + thumbRect.right - 38) + 'px';
    }

    imgEl.addEventListener('load', () => {
        updatePopupPosition();
    });

    async function showPopup(id, thumbElement) {
        currentPopupId = id;
        activeThumbnail = thumbElement;
        
        counterEl.textContent = i18n.loading;
        counterEl.style.display = 'block';
        imgEl.src = '';
        imgEl.style.display = 'none';

        popup.style.display = 'flex';
        updatePopupPosition();
        setTimeout(() => { popup.style.opacity = '1'; }, 10);

        if (!cache[id]) {
            try {
                const res = await fetch(`https://nijie.info/view_popup.php?id=${id}`);
                const text = await res.text();
                const doc = new DOMParser().parseFromString(text, 'text/html');
                
                const validSrcs = [];
                const targetImages = doc.querySelectorAll('#img_window div[id^="diff_"] img');
                
                targetImages.forEach(img => {
                    const src = img.getAttribute('data-src') || img.getAttribute('src');
                    if (src) {
                        const absoluteUrl = new URL(src, window.location.origin).href;
                        
                        // フィルター、マスク、エフェクト画像などを強力にブロック
                        const lowerUrl = absoluteUrl.toLowerCase();
                        if (
                            lowerUrl.includes('filter') ||
                            lowerUrl.includes('mask') || 
                            lowerUrl.includes('thumbnail') || 
                            lowerUrl.includes('icon') || 
                            lowerUrl.includes('ef_') || 
                            lowerUrl.includes('effect') ||
                            lowerUrl.includes('frame') ||
                            lowerUrl.includes('decoration') ||
                            lowerUrl.includes('overlay')
                        ) {
                            return;
                        }

                        // クラス名や親要素に filter が含まれる場合も除外
                        if (
                            img.classList.contains('filter') || 
                            img.classList.contains('mask') || 
                            img.classList.contains('effect') ||
                            img.closest('.view_filter')
                        ) {
                            return;
                        }

                        validSrcs.push(absoluteUrl);
                    }
                });
                
                cache[id] = [...new Set(validSrcs)];
            } catch(e) {
                if (currentPopupId === id) {
                    counterEl.textContent = i18n.error;
                    updatePopupPosition();
                }
                return;
            }
        }

        if (currentPopupId !== id) return;

        currentImages = cache[id];
        
        currentIndex = indexCache[id] !== undefined ? indexCache[id] : 0;
        if (currentIndex >= currentImages.length) {
            currentIndex = 0;
        }
        
        if (currentImages.length > 0) {
            renderImage();
        } else {
            counterEl.textContent = i18n.notFound;
            updatePopupPosition();
        }
    }

    function hidePopup() {
        popup.style.opacity = '0';
        thumbDownloadBtn.style.display = 'none';
        setTimeout(() => {
            if (popup.style.opacity === '0') {
                popup.style.display = 'none';
                currentPopupId = null;
                activeThumbnail = null;
            }
        }, 150);
    }

    // --- Helper function to sanitize filename and extract metadata ---
    function getCleanMetadata(thumbElement) {
        let title = 'artwork';
        let author = 'unknown';

        let container = thumbElement.closest('.nijie, .nijie_og, .gazou-box, .box, li');
        if (!container) {
            container = thumbElement.parentElement?.parentElement?.parentElement || document.body;
        }

        if (container) {
            const titleEl = container.querySelector('.title a, .title, a[title], .details-title, h3, h4');
            if (titleEl) {
                title = titleEl.getAttribute('title') || titleEl.textContent;
            }

            const authorEl = container.querySelector('.popup_member span, .popup_member, a[href*="members.php"], .name, .author, .profile-name');
            if (authorEl) {
                author = authorEl.textContent.replace(/^by\s*/i, '').trim();
            }
        }

        if (author === 'unknown' && activeThumbnail) {
            const href = activeThumbnail.getAttribute('href');
            if (href) {
                const matchId = href.match(/id=(\d+)/);
                if (matchId) {
                    const targetId = matchId[1];
                    const generalContainer = document.querySelector(`[illust_id="${targetId}"], a[href*="${targetId}"]`)?.closest('.nijie, .box, div');
                    if (generalContainer) {
                        const fallbackAuthor = generalContainer.querySelector('.popup_member span, a[href*="members.php"]');
                        if (fallbackAuthor) {
                            author = fallbackAuthor.textContent.replace(/^by\s*/i, '').trim();
                        }
                        const fallbackTitle = generalContainer.querySelector('.title');
                        if (fallbackTitle) {
                            title = fallbackTitle.textContent;
                        }
                    }
                }
            }
        }

        const sanitize = (str) => str.trim().replace(/[\\/:*?"<>|]/g, '_');
        return {
            title: sanitize(title),
            author: sanitize(author)
        };
    }

    // --- ZIP Download Handler ---
    thumbDownloadBtn.addEventListener('click', async (e) => {
        e.preventDefault();
        e.stopPropagation();
        if (!currentPopupId || currentImages.length === 0) return;

        const originalHTML = thumbDownloadBtn.innerHTML;
        thumbDownloadBtn.innerHTML = '⏳';
        thumbDownloadBtn.disabled = true;

        try {
            const zip = new JSZip();
            const meta = getCleanMetadata(activeThumbnail);
            
            let zipFilename = '';
            if (isJapanese) {
                zipFilename = `(ニジエ) [${meta.author}] ${meta.title}.zip`;
            } else {
                zipFilename = `(Nijie) [${meta.author}] ${meta.title}.zip`;
            }

            const folder = zip.folder(`nijie_${currentPopupId}`);

            const promises = currentImages.map(async (url, index) => {
                try {
                    const response = await fetch(url);
                    const blob = await response.blob();
                    let ext = url.split('.').pop().split('?')[0] || 'jpg';
                    const filename = `${String(index + 1).padStart(3, '0')}.${ext}`;
                    folder.file(filename, blob);
                } catch (err) {
                    console.error(`Failed to fetch image: ${url}`, err);
                }
            });

            await Promise.all(promises);

            const content = await zip.generateAsync({ type: 'blob' });
            
            const link = document.createElement('a');
            link.href = URL.createObjectURL(content);
            link.download = zipFilename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);

        } catch (err) {
            console.error(err);
            alert(i18n.zipError);
        } finally {
            thumbDownloadBtn.innerHTML = originalHTML;
            thumbDownloadBtn.disabled = false;
        }
    });

    // --- Event Listeners ---
    
    document.addEventListener('mouseover', (e) => {
        if (thumbDownloadBtn.contains(e.target)) return;

        const a = e.target.closest('a[href*="view.php"]');
        if (a) {
            const url = new URL(a.href, window.location.origin);
            const id = url.searchParams.get('id');
            if (id && currentPopupId !== id) {
                showPopup(id, a);
            }
        }
    });

    document.addEventListener('mouseout', (e) => {
        const a = e.target.closest('a[href*="view.php"]');
        if (a && a === activeThumbnail) {
            if (e.relatedTarget && (a.contains(e.relatedTarget) || thumbDownloadBtn.contains(e.relatedTarget))) {
                return;
            }
            if (currentPopupId) {
                indexCache[currentPopupId] = currentIndex;
            }
            hidePopup();
        }
    });

    thumbDownloadBtn.addEventListener('mouseout', (e) => {
        if (activeThumbnail && e.relatedTarget && !activeThumbnail.contains(e.relatedTarget) && !thumbDownloadBtn.contains(e.relatedTarget)) {
            if (currentPopupId) {
                indexCache[currentPopupId] = currentIndex;
            }
            hidePopup();
        }
    });

    document.addEventListener('wheel', (e) => {
        if (!activeThumbnail) return;
        
        const targetA = e.target.closest('a[href*="view.php"]');
        if (!targetA || targetA !== activeThumbnail) return;
        
        if (currentImages.length <= 1) return;
        
        e.preventDefault();
        
        if (e.deltaY > 0) {
            currentIndex = (currentIndex + 1) % currentImages.length;
            renderImage();
        } else if (e.deltaY < 0) {
            currentIndex = (currentIndex - 1 + currentImages.length) % currentImages.length;
            renderImage();
        }
        
        if (currentPopupId) {
            indexCache[currentPopupId] = currentIndex;
        }
    }, { passive: false });

})();