☰

Tampermonkey Video Filter v4.1

Filters posts with videos/GIFs using dynamic content detection. Extended video format support, GIF thumbnails, caching, performance optimizations, thumbnail retry, and new toggles: "Search revisions" + "Include GIFs" + "Error 429 fix".

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램을 먼저 설치해야 합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         Tampermonkey Video Filter v4.1
// @namespace    http://tampermonkey.net/
// @version      1.4.2
// @description  Filters posts with videos/GIFs using dynamic content detection. Extended video format support, GIF thumbnails, caching, performance optimizations, thumbnail retry, and new toggles: "Search revisions" + "Include GIFs" + "Error 429 fix".
// @author       harryangstrom, xdegeneratex, remuru, ImTrep, DeepSeek, Grok
// @match        https://*.coomer.party/*
// @match        https://*.coomer.su/*
// @match        https://*.coomer.st/*
// @match        https://*.kemono.su/*
// @match        https://*.kemono.party/*
// @match        https://*.kemono.cr/*
// @icon         https://i.imgur.com/7TPAb7F.png
// @grant        GM_setClipboard
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @run-at       document-idle
// @license      MIT
// @noframes
// @esversion  8
// ==/UserScript==

(function() {
    'use strict';

    // Expanded video extensions list
    const VIDEO_EXTENSIONS = new Set([
        'mp4', 'm4v', 'mov', 'webm', 'avi', 'mkv', 'wmv', 'flv', 'mpg', 'mpeg',
        'm2ts', 'mts', 'ogv', 'qt', 'rm', 'rmvb', 'vob', 'asf', '3gp', 'f4v',
        'mxf', 'swf', 'ts', 'm4a', 'm4b', 'm4p', 'm4r', 'm4v'
    ]);
    const GIF_EXTENSION = 'gif';
    const IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'bmp', 'webp', 'svg']);

    // Performance constants
    const POSTS_PER_PAGE = 50;
    const API_DELAY = 1500;
    const MAX_CONCURRENT_REQUESTS = 2;
    const SUBSTRING_TITLE_LENGTH = 100;
    const LS_COLLAPSE_KEY = 'videoFilterPanelCollapsed_v1';
    const LS_PAGES_KEY = 'videoFilterPageRange_v1';
    const LS_CACHE_KEY = 'videoFilterCache_v1';
    const CACHE_TTL = 5 * 60 * 1000; // 5 minutes for API data
    const THUMBNAIL_CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours for thumbnails
    const MAX_THUMBNAIL_RETRIES = 3;
    const THUMBNAIL_RETRY_DELAY = 1000;
    const VIDEO_LOAD_TIMEOUT = 10000;

    // GM storage keys (persistent, not affected by localStorage quota)
    const GM_REVISIONS_KEY = 'videoFilterIncludeRevisions';
    const GM_GIFS_KEY = 'videoFilterIncludeGifs';
    const GM_ERROR429_KEY = 'videoFilterError429Fix';

    let currentDomain = window.location.hostname;
    let revisionsSupported = currentDomain.includes('kemono');
    let allFoundVideoUrls = [];
    let videoIntersectionObserver = null;
    let isPanelCollapsed = false;
    let isFiltering = false;
    let activeRequests = 0;
    let requestQueue = [];
    const thumbnailRetryMap = new Map();
    const failedThumbnails = new Set();

    // Thumbnail loading progress
    let totalThumbnailsToLoad = 0;
    let thumbnailsLoadedCount = 0;
    let allMediaLoadedShown = false;
    let includeRevisions = false;
    let includeGifs = false;
    let error429FixEnabled = false;

    // UI container
    const uiContainer = document.createElement('div');
    uiContainer.id = 'video-filter-ui';
    Object.assign(uiContainer.style, {
        position: 'fixed',
        bottom: '10px',
        right: '10px',
        backgroundColor: '#2c2c2e',
        color: '#e0e0e0',
        border: '1px solid #444444',
        padding: '12px',
        zIndex: '9999',
        fontFamily: 'Arial, sans-serif',
        fontSize: '14px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.5)',
        borderRadius: '4px',
        transition: 'width 0.2s ease-in-out, height 0.2s ease-in-out, padding 0.2s ease-in-out'
    });

    // Collapse button
    const collapseButton = document.createElement('button');
    collapseButton.id = 'video-filter-collapse-button';
    collapseButton.innerHTML = '»';
    collapseButton.title = 'Collapse/Expand Panel';
    Object.assign(collapseButton.style, {
        position: 'absolute',
        top: '12px',
        bottom: '12px',
        left: '8px',
        width: '25px',
        height: 'auto',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '0',
        fontSize: '16px',
        backgroundColor: '#4a4a4c',
        color: '#f0f0f0',
        border: '1px solid #555555',
        borderRadius: '3px',
        cursor: 'pointer',
        zIndex: '1'
    });

    // Settings button
    const settingsButton = document.createElement('button');
    settingsButton.id = 'video-filter-settings-button';
    settingsButton.innerHTML = '⋮';
    settingsButton.title = 'Settings';
    Object.assign(settingsButton.style, {
        width: '25px',
        height: '25px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '0',
        fontSize: '18px',
        backgroundColor: 'transparent',
        color: '#f0f0f0',
        border: '1px solid #555555',
        borderRadius: '3px',
        cursor: 'pointer',
        flexShrink: '0'
    });

    const panelMainContent = document.createElement('div');
    panelMainContent.id = 'video-filter-main-content';
    panelMainContent.style.marginLeft = '30px';

    const pageRangeInput = document.createElement('input');
    pageRangeInput.type = 'text';
    pageRangeInput.id = 'video-filter-page-range';
    pageRangeInput.value = '1';
    pageRangeInput.placeholder = 'e.g., 1, 2-5, 7';
    Object.assign(pageRangeInput.style, {
        width: '100px',
        marginRight: '8px',
        padding: '6px 8px',
        backgroundColor: '#1e1e1e',
        color: '#e0e0e0',
        border: '1px solid #555555',
        borderRadius: '3px'
    });

    const filterButton = document.createElement('button');
    filterButton.id = 'video-filter-button';
    filterButton.textContent = 'Filter Videos/GIFs';

    const copyUrlsButton = document.createElement('button');
    copyUrlsButton.id = 'video-copy-urls-button';
    copyUrlsButton.textContent = 'Copy URLs';
    copyUrlsButton.disabled = true;

    const statusMessage = document.createElement('div');
    statusMessage.id = 'video-filter-status';
    Object.assign(statusMessage.style, {
        fontSize: '12px',
        minHeight: '15px',
        color: '#cccccc',
        flex: '1'
    });

    const baseButtonBg = '#3a3a3c';
    const hoverButtonBg = '#4a4a4c';
    const disabledButtonBg = '#303030';
    const disabledButtonColor = '#777777';

    function styleButton(button, disabled = false) {
        if (disabled) {
            button.style.backgroundColor = disabledButtonBg;
            button.style.color = disabledButtonColor;
            button.style.cursor = 'default';
        } else {
            button.style.backgroundColor = baseButtonBg;
            button.style.color = '#f0f0f0';
            button.style.cursor = 'pointer';
        }
        Object.assign(button.style, {
            marginRight: '8px',
            padding: '6px 12px',
            border: '1px solid #555555',
            borderRadius: '3px'
        });
    }

    [filterButton, copyUrlsButton].forEach(btn => {
        styleButton(btn, btn.disabled);
        btn.addEventListener('mouseenter', () => { if (!btn.disabled) btn.style.backgroundColor = hoverButtonBg; });
        btn.addEventListener('mouseleave', () => { if (!btn.disabled) btn.style.backgroundColor = baseButtonBg; });
    });

    collapseButton.addEventListener('mouseenter', () => collapseButton.style.backgroundColor = hoverButtonBg);
    collapseButton.addEventListener('mouseleave', () => collapseButton.style.backgroundColor = '#4a4a4c');
    settingsButton.addEventListener('mouseenter', () => settingsButton.style.backgroundColor = hoverButtonBg);
    settingsButton.addEventListener('mouseleave', () => settingsButton.style.backgroundColor = 'transparent');

    // Settings panel
    const settingsPanel = uiContainer.cloneNode(false);
    settingsPanel.id = 'video-filter-settings-panel';
    Object.assign(settingsPanel.style, {
        position: 'fixed',
        right: '10px',
        backgroundColor: '#2c2c2e',
        color: '#e0e0e0',
        border: '1px solid #444444',
        padding: '12px',
        zIndex: '10000',
        fontFamily: 'Arial, sans-serif',
        fontSize: '14px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.5)',
        borderRadius: '4px',
        transition: 'opacity 0.2s ease-in-out',
        display: 'none',
        width: '280px',
        height: 'auto',
        overflow: 'auto'
    });

    const settingsTitle = document.createElement('div');
    settingsTitle.textContent = 'Settings';
    settingsTitle.style.fontWeight = 'bold';
    settingsTitle.style.marginBottom = '12px';
    settingsTitle.style.borderBottom = '1px solid #555555';
    settingsTitle.style.paddingBottom = '8px';
    settingsTitle.style.fontSize = '15px';

    const revisionsLabel = document.createElement('label');
    revisionsLabel.style.display = 'flex';
    revisionsLabel.style.alignItems = 'center';
    revisionsLabel.style.gap = '10px';
    revisionsLabel.style.cursor = 'pointer';
    revisionsLabel.style.fontSize = '14px';
    const revisionsToggle = document.createElement('input');
    revisionsToggle.type = 'checkbox';
    revisionsToggle.id = 'search-revisions-toggle';
    const revisionsText = document.createTextNode('Search revisions (latest revision with media)');
    revisionsLabel.append(revisionsToggle, revisionsText);

    const gifsLabel = document.createElement('label');
    gifsLabel.style.display = 'flex';
    gifsLabel.style.alignItems = 'center';
    gifsLabel.style.gap = '10px';
    gifsLabel.style.cursor = 'pointer';
    gifsLabel.style.fontSize = '14px';
    const gifsToggle = document.createElement('input');
    gifsToggle.type = 'checkbox';
    gifsToggle.id = 'include-gifs-toggle';
    const gifsText = document.createTextNode('Include GIFs (in addition to videos)');
    gifsLabel.append(gifsToggle, gifsText);

    const error429Label = document.createElement('label');
    error429Label.style.display = 'flex';
    error429Label.style.alignItems = 'center';
    error429Label.style.gap = '10px';
    error429Label.style.cursor = 'pointer';
    error429Label.style.fontSize = '14px';
    const error429Toggle = document.createElement('input');
    error429Toggle.type = 'checkbox';
    error429Toggle.id = 'error-429-fix-toggle';
    const error429Text = document.createTextNode('Error 429 fix (retry up to 5x within 10s on rate limit)');
    error429Label.append(error429Toggle, error429Text);

    settingsPanel.appendChild(settingsTitle);
    settingsPanel.appendChild(revisionsLabel);
    settingsPanel.appendChild(gifsLabel);
    settingsPanel.appendChild(error429Label);

    if (!revisionsSupported) {
        revisionsToggle.disabled = true;
        revisionsLabel.style.opacity = '0.5';
        revisionsLabel.title = 'Revisions only supported on Kemono domains';
    }

    const statusRow = document.createElement('div');
    Object.assign(statusRow.style, {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginTop: '8px',
        gap: '8px'
    });

    panelMainContent.appendChild(document.createTextNode('Pages: '));
    panelMainContent.appendChild(pageRangeInput);
    panelMainContent.appendChild(filterButton);
    panelMainContent.appendChild(copyUrlsButton);
    statusRow.appendChild(statusMessage);
    statusRow.appendChild(settingsButton);
    panelMainContent.appendChild(statusRow);

    uiContainer.appendChild(collapseButton);
    uiContainer.appendChild(panelMainContent);
    document.body.appendChild(uiContainer);
    document.body.appendChild(settingsPanel);

    // Enhanced cache (localStorage only for API data – toggles now use GM storage)
    const cache = {
        get: function(key, customTtl = null) {
            try {
                const item = localStorage.getItem(`${LS_CACHE_KEY}_${key}`);
                if (!item) return null;
                const { data, timestamp, ttl } = JSON.parse(item);
                const effectiveTtl = ttl || customTtl || CACHE_TTL;
                if (Date.now() - timestamp > effectiveTtl) {
                    this.delete(key);
                    return null;
                }
                return data;
            } catch (e) {
                return null;
            }
        },
        set: function(key, data, customTtl = null) {
            try {
                const item = JSON.stringify({
                    data: data,
                    timestamp: Date.now(),
                    ttl: customTtl
                });
                localStorage.setItem(`${LS_CACHE_KEY}_${key}`, item);
            } catch (e) {
                if (e.name === 'QuotaExceededError') {
                    console.warn('Video Filter: localStorage quota exceeded – cache entry skipped. Consider clearing old cache manually.');
                } else {
                    console.warn('Video Filter: Cache set failed', e);
                }
            }
        },
        delete: function(key) {
            try {
                localStorage.removeItem(`${LS_CACHE_KEY}_${key}`);
            } catch (e) {
                console.warn('Video Filter: Cache delete failed', e);
            }
        }
    };

    function togglePanelCollapse() {
        isPanelCollapsed = !isPanelCollapsed;
        if (isPanelCollapsed) {
            panelMainContent.style.display = 'none';
            settingsPanel.style.display = 'none';
            collapseButton.innerHTML = '«';
            uiContainer.style.width = '41px';
            uiContainer.style.height = '80px';
            uiContainer.style.padding = '0';
        } else {
            panelMainContent.style.display = 'block';
            collapseButton.innerHTML = '»';
            uiContainer.style.width = '';
            uiContainer.style.height = '';
            uiContainer.style.padding = '12px';
        }
        localStorage.setItem(LS_COLLAPSE_KEY, isPanelCollapsed.toString());
    }

    function toggleSettingsPanel() {
        if (settingsPanel.style.display === 'block') {
            settingsPanel.style.display = 'none';
            return;
        }
        const uiRect = uiContainer.getBoundingClientRect();
        const gap = 6;
        settingsPanel.style.bottom = `${window.innerHeight - uiRect.top + gap}px`;
        settingsPanel.style.right = '10px';
        settingsPanel.style.display = 'block';
    }

    function getPostPreviewUrl(post) {
        if (!post || !post.id) return null;
        const cacheKey = `thumbnail_preview_${currentDomain}_${post.id}`;
        const cached = cache.get(cacheKey, THUMBNAIL_CACHE_TTL);
        if (cached !== null) return cached;
        let preview = null;
        if (post.file && post.file.path && isImageFile(post.file.path)) {
            preview = `https://${currentDomain}/data${post.file.path}`;
        } else if (post.attachments) {
            for (const att of post.attachments) {
                if (att.path && isImageFile(att.path)) {
                    preview = `https://${currentDomain}/data${att.path}`;
                    break;
                }
            }
        }
        if (preview) cache.set(cacheKey, preview, THUMBNAIL_CACHE_TTL);
        return preview;
    }

    function setupVideoIntersectionObserver() {
        if (videoIntersectionObserver) videoIntersectionObserver.disconnect();
        videoIntersectionObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const videoElement = entry.target;
                    const videoId = videoElement.dataset.videoId || Math.random().toString(36).substr(2, 9);
                    if (!thumbnailRetryMap.has(videoId)) thumbnailRetryMap.set(videoId, 0);
                    if (failedThumbnails.has(videoId)) {
                        videoIntersectionObserver.unobserve(videoElement);
                        return;
                    }
                    const sourceElement = videoElement.querySelector('source[data-src]');
                    if (sourceElement) {
                        const videoUrl = sourceElement.getAttribute('data-src');
                        setupVideoErrorHandling(videoElement, videoId, videoUrl);
                        const loadTimeout = setTimeout(() => {
                            if (!videoElement.hasAttribute('data-loaded')) handleVideoLoadError(videoElement, videoId, videoUrl, 'Timeout loading video');
                        }, VIDEO_LOAD_TIMEOUT);
                        videoElement.dataset.loadTimeout = loadTimeout;
                        sourceElement.setAttribute('src', videoUrl);
                        videoElement.load();
                        sourceElement.removeAttribute('data-src');
                        videoIntersectionObserver.unobserve(videoElement);
                    }
                }
            });
        }, { root: null, rootMargin: '200px 0px', threshold: 0.01 });
    }

    function setupVideoErrorHandling(videoElement, videoId, videoUrl) {
        videoElement.onerror = null;
        videoElement.onloadeddata = null;
        videoElement.onerror = function() { handleVideoLoadError(videoElement, videoId, videoUrl, videoElement.error ? videoElement.error.message : 'Unknown video error'); };
        videoElement.onloadeddata = function() {
            clearTimeout(videoElement.dataset.loadTimeout);
            videoElement.setAttribute('data-loaded', 'true');
            thumbnailsLoadedCount++;
            if (totalThumbnailsToLoad > 0) {
                showStatus(`Loading thumbnails: ${thumbnailsLoadedCount}/${totalThumbnailsToLoad}`, 'info');
            }
            if (!allMediaLoadedShown && totalThumbnailsToLoad > 0 && thumbnailsLoadedCount >= totalThumbnailsToLoad) {
                showAllMediaLoadedMessage();
            }
        };
    }

    function showAllMediaLoadedMessage() {
        if (allMediaLoadedShown) return;
        allMediaLoadedShown = true;
        showStatus('All media loaded successfully!', 'success');
    }

    function handleVideoLoadError(videoElement, videoId, videoUrl, errorDetails) {
        clearTimeout(videoElement.dataset.loadTimeout);
        const retryCount = thumbnailRetryMap.get(videoId) || 0;
        if (retryCount >= MAX_THUMBNAIL_RETRIES) {
            failedThumbnails.add(videoId);
            showThumbnailWarning(videoElement, videoUrl, `Failed after ${MAX_THUMBNAIL_RETRIES} retries: ${errorDetails}`);
            thumbnailsLoadedCount++;
            if (!allMediaLoadedShown && totalThumbnailsToLoad > 0 && thumbnailsLoadedCount >= totalThumbnailsToLoad) {
                showAllMediaLoadedMessage();
            }
            return;
        }
        thumbnailRetryMap.set(videoId, retryCount + 1);
        showStatus(`Retry ${retryCount + 1}/${MAX_THUMBNAIL_RETRIES} for thumbnail`, 'warning');
        setTimeout(() => {
            if (!failedThumbnails.has(videoId) && videoElement.isConnected) {
                const sourceElement = videoElement.querySelector('source');
                if (sourceElement) {
                    sourceElement.setAttribute('src', '');
                    sourceElement.setAttribute('src', videoUrl);
                    videoElement.load();
                    const newTimeout = setTimeout(() => {
                        if (!videoElement.hasAttribute('data-loaded')) handleVideoLoadError(videoElement, videoId, videoUrl, 'Retry timeout');
                    }, VIDEO_LOAD_TIMEOUT);
                    videoElement.dataset.loadTimeout = newTimeout;
                }
            }
        }, THUMBNAIL_RETRY_DELAY * (retryCount + 1));
    }

    function showThumbnailWarning(videoElement, videoUrl, message) {
        const warningOverlay = document.createElement('div');
        warningOverlay.className = 'thumbnail-warning-overlay';
        Object.assign(warningOverlay.style, {
            position: 'absolute', top: '0', left: '0', width: '100%', height: '100%',
            backgroundColor: 'rgba(0, 0, 0, 0.7)', color: '#ffcc00', display: 'flex',
            alignItems: 'center', justifyContent: 'center', textAlign: 'center',
            padding: '10px', fontSize: '12px', zIndex: '10', pointerEvents: 'none'
        });
        const retryButton = document.createElement('button');
        retryButton.textContent = 'Retry';
        Object.assign(retryButton.style, { backgroundColor: '#4a4a4c', color: '#f0f0f0', border: '1px solid #555555', borderRadius: '3px', padding: '4px 8px', marginTop: '8px', cursor: 'pointer', pointerEvents: 'auto' });
        retryButton.onclick = function(e) {
            e.stopPropagation();
            warningOverlay.remove();
            const videoId = videoElement.dataset.videoId || Math.random().toString(36).substr(2, 9);
            thumbnailRetryMap.delete(videoId);
            failedThumbnails.delete(videoId);
            videoElement.removeAttribute('data-loaded');
            const sourceElement = videoElement.querySelector('source');
            if (sourceElement) {
                sourceElement.setAttribute('src', '');
                sourceElement.setAttribute('src', videoUrl);
                videoElement.load();
                showStatus('Manual retry initiated', 'info');
            }
        };
        warningOverlay.innerHTML = `
            <div style="max-width: 100%;">
                <div style="color: #ff6b6b; margin-bottom: 5px; font-weight: bold;">Thumbnail Failed</div>
                <div style="font-size: 11px; margin-bottom: 10px; color: #cccccc;">${message}</div>
            </div>
        `;
        warningOverlay.querySelector('div').appendChild(retryButton);
        if (getComputedStyle(videoElement).position === 'static') videoElement.style.position = 'relative';
        videoElement.appendChild(warningOverlay);
    }

    function showStatus(message, type = 'info') {
        statusMessage.textContent = message;
        switch (type) {
            case 'error': statusMessage.style.color = '#ff6b6b'; break;
            case 'success': statusMessage.style.color = '#76c7c0'; break;
            case 'warning': statusMessage.style.color = '#ffcc00'; break;
            default: statusMessage.style.color = '#cccccc';
        }
        if (type === 'success' && message.includes("Copied")) {
            setTimeout(() => { if (statusMessage.textContent === message) { statusMessage.textContent = ''; statusMessage.style.color = '#cccccc'; } }, 3000);
        }
    }

    function parsePageRange(inputStr) {
        const pages = new Set();
        if (!inputStr || inputStr.trim() === '') { showStatus('Error: Page range cannot be empty.', 'error'); return null; }
        const parts = inputStr.split(',');
        for (const part of parts) {
            const trimmedPart = part.trim();
            if (trimmedPart.includes('-')) {
                const [startStr, endStr] = trimmedPart.split('-').map(s => s.trim());
                const start = parseInt(startStr, 10); const end = parseInt(endStr, 10);
                if (isNaN(start) || isNaN(end) || start <= 0 || end < start) { showStatus(`Error: Invalid range "${trimmedPart}".`, 'error'); return null; }
                for (let i = start; i <= end; i++) pages.add(i);
            } else {
                const page = parseInt(trimmedPart, 10);
                if (isNaN(page) || page <= 0) { showStatus(`Error: Invalid page number "${trimmedPart}".`, 'error'); return null; }
                pages.add(page);
            }
        }
        return pages.size === 0 ? null : Array.from(pages).sort((a, b) => a - b);
    }

    function determinePageContext() {
        const pathname = window.location.pathname;
        const searchParams = new URLSearchParams(window.location.search);
        const query = searchParams.get('q');
        const tag = searchParams.get('tag');
        const userProfileMatch = pathname.match(/^\/([^/]+)\/user\/([^/]+)$/);
        if (pathname === '/posts' && (query || tag)) {
            return { type: 'global_search', query, tag };
        }
        if (pathname === '/posts') {
            return { type: 'global_search', query: null, tag };
        }
        if (pathname === '/posts/popular') {
            return { type: 'popular_posts', date: searchParams.get('date') || 'none', period: searchParams.get('period') || 'recent', tag };
        }
        if (userProfileMatch && !query && !tag) {
            return { type: 'profile', service: userProfileMatch[1], userId: userProfileMatch[2] };
        }
        if (userProfileMatch && (query || tag)) {
            return { type: 'user_search', service: userProfileMatch[1], userId: userProfileMatch[2], query, tag };
        }
        return null;
    }

    function buildApiUrl(context, offset) {
        let baseApiUrl = `https://${currentDomain}/api/v1`;
        let queryParams = [`o=${offset}`];
        if (context.tag) {
            queryParams.push(`tag=${encodeURIComponent(context.tag)}`);
        }
        switch (context.type) {
            case 'profile':
                return `${baseApiUrl}/${context.service}/user/${context.userId}/posts?${queryParams.join('&')}`;
            case 'user_search':
                if (context.query) queryParams.push(`q=${encodeURIComponent(context.query)}`);
                return `${baseApiUrl}/${context.service}/user/${context.userId}/posts?${queryParams.join('&')}`;
            case 'global_search':
                if (context.query) queryParams.push(`q=${encodeURIComponent(context.query)}`);
                return `${baseApiUrl}/posts?${queryParams.join('&')}`;
            case 'popular_posts':
                if (context.date != 'none') queryParams.push(`date=${encodeURIComponent(context.date)}`);
                queryParams.push(`period=${encodeURIComponent(context.period)}`);
                return `${baseApiUrl}/posts/popular?${queryParams.join('&')}`;
            default:
                return null;
        }
    }

    function fetchData(apiUrl, useCache = true) {
        if (useCache) {
            const cachedData = cache.get(apiUrl);
            if (cachedData) return Promise.resolve(cachedData);
        }
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "GET", url: apiUrl,
                headers: { "Accept": "text/css", "Referer": window.location.href, "User-Agent": navigator.userAgent, "X-Requested-With": "XMLHttpRequest" },
                onload: resp => {
                    if (resp.status >= 200 && resp.status < 300) {
                        try {
                            const data = JSON.parse(resp.responseText);
                            cache.set(apiUrl, data);
                            resolve(data);
                        }
                        catch (e) { reject(`Error parsing JSON: ${e.message}`); }
                    } else reject(`API request failed: ${resp.status}`);
                },
                onerror: () => reject('Network error'),
                ontimeout: () => reject('Request timeout'),
                timeout: 30000
            });
        });
    }

    // 429-aware fetch with optional retries
    async function fetchPageData(apiUrl, pageNum) {
        const maxRetries = error429FixEnabled ? 5 : 0;
        let attempt = 0;
        while (attempt <= maxRetries) {
            try {
                if (attempt > 0) {
                    showStatus(`Refetching page ${pageNum} due to error 429 ${attempt}/${maxRetries}...`, 'warning');
                    await new Promise(resolve => setTimeout(resolve, 2000));
                }
                const response = await queueApiRequest(apiUrl, true);
                return response;
            } catch (error) {
                const errMsg = error && (error.message || error.toString() || '');
                if (!errMsg.includes('429')) {
                    throw error;
                }
                attempt++;
                if (attempt > maxRetries) {
                    throw error;
                }
            }
        }
        throw new Error('429 retry loop exited unexpectedly');
    }

    function processRequestQueue() {
        if (activeRequests >= MAX_CONCURRENT_REQUESTS || requestQueue.length === 0) return;
        const nextRequest = requestQueue.shift();
        activeRequests++;
        fetchData(nextRequest.apiUrl, nextRequest.useCache)
            .then(nextRequest.resolve).catch(nextRequest.reject)
            .finally(() => { activeRequests--; setTimeout(processRequestQueue, API_DELAY); });
    }

    function queueApiRequest(apiUrl, useCache = true) {
        return new Promise((resolve, reject) => {
            requestQueue.push({ apiUrl, useCache, resolve, reject });
            processRequestQueue();
        });
    }

    function isVideoFile(filenameOrPath) {
        if (!filenameOrPath) return false;
        const lowerName = filenameOrPath.toLowerCase();
        const extension = lowerName.split('.').pop();
        return VIDEO_EXTENSIONS.has(extension);
    }

    function isGifFile(filenameOrPath) {
        if (!filenameOrPath) return false;
        return filenameOrPath.toLowerCase().endsWith('.gif');
    }

    function isImageFile(filenameOrPath) {
        if (!filenameOrPath) return false;
        const lowerName = filenameOrPath.toLowerCase();
        const extension = lowerName.split('.').pop();
        return IMAGE_EXTENSIONS.has(extension);
    }

    function getBestMediaUrlFromPost(post, includeGifsParam) {
        const domain = `https://${currentDomain}/data`;
        if (post.file && isVideoFile(post.file.path)) return { type: 'video', url: domain + post.file.path };
        if (post.attachments) {
            for (const att of post.attachments) {
                if (isVideoFile(att.path)) return { type: 'video', url: domain + att.path };
            }
        }
        if (includeGifsParam) {
            if (post.file && isGifFile(post.file.path)) return { type: 'gif', url: domain + post.file.path };
            if (post.attachments) {
                for (const att of post.attachments) {
                    if (isGifFile(att.path)) return { type: 'gif', url: domain + att.path };
                }
            }
        }
        return null;
    }

    function buildRevisionsApiUrl(post) {
        if (!post || !post.service || !post.user || !post.id) return null;
        return `https://${currentDomain}/api/v1/${post.service}/user/${post.user}/post/${post.id}/revisions`;
    }

    async function getRevisionMediaData(post, includeGifsParam) {
        const revisionsUrl = buildRevisionsApiUrl(post);
        if (!revisionsUrl) return null;
        try {
            const revisionsData = await queueApiRequest(revisionsUrl, true);
            let revisionsList = Array.isArray(revisionsData) ? revisionsData : (revisionsData?.revisions || []);
            if (!Array.isArray(revisionsList)) return null;
            let candidates = [];
            for (const rev of revisionsList) {
                const revMedia = getBestMediaUrlFromPost(rev, includeGifsParam);
                if (revMedia) {
                    const revId = (typeof rev.revision_id !== 'undefined') ? rev.revision_id : (rev.id || 0);
                    const previewUrl = getPostPreviewUrl(rev);
                    candidates.push({ media: revMedia, revisionId: revId, previewUrl });
                }
            }
            if (candidates.length > 0) {
                candidates.sort((a, b) => (b.revisionId || 0) - (a.revisionId || 0));
                const best = candidates[0];
                console.log(`Video Filter: Found revision ${best.revisionId} with ${best.media.type} for post ${post.id}`);
                return { media: best.media, revisionId: best.revisionId, previewUrl: best.previewUrl };
            }
            return null;
        } catch (e) {
            console.warn(`Video Filter: Revisions fetch failed for post ${post.id}`, e);
            return null;
        }
    }

    function createPostCardHtml(post, mediaInfo, previewUrl, revisionId = null) {
        const postDate = new Date(post.published || post.added);
        const formattedDate = postDate.toLocaleString();
        const dateTimeAttr = postDate.toISOString();
        const attachmentCount = post.attachments ? post.attachments.length : 0;
        const attachmentText = attachmentCount === 1 ? "1 Attachment" : `${attachmentCount} Attachments`;
        let displayTitle = (post.title || '').trim();
        if (!displayTitle && post.content) {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = post.content;
            let contentForTitle = (tempDiv.textContent || "").trim();
            if (contentForTitle) displayTitle = contentForTitle.substring(0, SUBSTRING_TITLE_LENGTH) + (contentForTitle.length > SUBSTRING_TITLE_LENGTH ? '...' : '');
        }
        displayTitle = displayTitle || 'No Title';
        const postLink = revisionId !== null ? `/${post.service}/user/${post.user}/post/${post.id}/revision/${revisionId}` : `/${post.service}/user/${post.user}/post/${post.id}`;
        const videoId = `video_${post.id}_${Date.now()}`;
        let mediaHtml = '';
        if (mediaInfo.type === 'video') {
            const posterAttribute = previewUrl ? `poster="${previewUrl}"` : '';
            mediaHtml = `<div style="text-align: center; margin-bottom: 5px; background-color: #000; position: relative;"><video class="lazy-load-video" controls preload="none" width="100%" style="max-height: 300px; display: block;" ${posterAttribute} data-video-id="${videoId}"><source data-src="${mediaInfo.url}" type="video/mp4"></video></div>`;
        } else if (mediaInfo.type === 'gif') {
            mediaHtml = `<div style="text-align: center; margin-bottom: 5px; background-color: #000; display: flex; align-items: center; justifyContent: center; overflow: hidden; position: relative;"><img src="${mediaInfo.url}" alt="GIF" style="width: 100%; height: auto; max-height: 300px; object-fit: contain; display: block;"></div>`;
        }
        return `<article class="post-card post-card--preview"><a class="fancy-link fancy-link--kemono" href="${postLink}" target="_blank" rel="noopener noreferrer"><header class="post-card__header" title="${displayTitle.replace(/"/g, '&quot;')}">${displayTitle}</header>${mediaHtml}<footer class="post-card__footer"><div><div><time datetime="${dateTimeAttr}">${formattedDate}</time><div>${attachmentCount > 0 ? attachmentText : 'No Attachments'}</div></div></div></footer></a></article>`;
    }

    async function handleFilter() {
        if (isFiltering) { showStatus('Already filtering, please wait...', 'warning'); return; }
        showStatus('');
        isFiltering = true;
        filterButton.textContent = 'Filtering...';
        styleButton(filterButton, true);
        filterButton.disabled = true;
        styleButton(copyUrlsButton, true);
        copyUrlsButton.disabled = true;
        allFoundVideoUrls = [];
        requestQueue = [];
        activeRequests = 0;
        thumbnailRetryMap.clear();
        failedThumbnails.clear();
        totalThumbnailsToLoad = 0;
        thumbnailsLoadedCount = 0;
        allMediaLoadedShown = false;
        let failed429Pages = [];

        setupVideoIntersectionObserver();

        const pagesToFetch = parsePageRange(pageRangeInput.value);
        if (!pagesToFetch) { resetFilterButton(); return; }
        localStorage.setItem(LS_PAGES_KEY, pageRangeInput.value);

        const context = determinePageContext();
        if (!context) { showStatus('Error: Page context invalid for filtering.', 'error'); resetFilterButton(); return; }

        const postListContainer = document.querySelector('.card-list__items');
        if (!postListContainer) { showStatus('Error: Post container not found.', 'error'); resetFilterButton(); return; }

        postListContainer.style.setProperty('--card-size', '350px');
        postListContainer.innerHTML = '';
        document.querySelectorAll('.paginator menu, .content > menu.Paginator').forEach(menu => menu.style.display = 'none');
        const paginatorInfo = document.querySelector('.paginator > small, .content > div > small.subtle-text');
        if (paginatorInfo) paginatorInfo.textContent = `Filtering posts...`;

        let totalVideoPostsFound = 0;
        let totalGifPostsFound = 0;
        let errors = 0;
        const maxErrors = 3;
        const mediaTypeLabel = includeGifs ? 'Videos/GIFs' : 'Videos';

        for (let i = 0; i < pagesToFetch.length; i++) {
            if (errors >= maxErrors) break;
            const pageNum = pagesToFetch[i];
            const offset = (pageNum - 1) * POSTS_PER_PAGE;
            const apiUrl = buildApiUrl(context, offset);
            if (!apiUrl) { errors++; continue; }

            filterButton.textContent = `Filtering Page ${i + 1}/${pagesToFetch.length}...`;
            showStatus(`Fetching page ${pageNum}...`, 'info');

            try {
                const apiResponse = await fetchPageData(apiUrl, pageNum);

                let posts = Array.isArray(apiResponse) ? apiResponse : (apiResponse.results || apiResponse.posts || []);
                if (!Array.isArray(posts)) continue;

                const fragment = document.createDocumentFragment();
                let pageVideoCount = 0;
                let pageGifCount = 0;

                for (const post of posts) {
                    const mainMedia = getBestMediaUrlFromPost(post, includeGifs);
                    if (mainMedia) {
                        if (mainMedia.type === 'video') {
                            totalVideoPostsFound++;
                            pageVideoCount++;
                            totalThumbnailsToLoad++;
                        } else if (mainMedia.type === 'gif') {
                            totalGifPostsFound++;
                            pageGifCount++;
                        }
                        allFoundVideoUrls.push(mainMedia.url);
                        const previewUrl = getPostPreviewUrl(post);
                        const cardHtml = createPostCardHtml(post, mainMedia, previewUrl, null);
                        const tempDiv = document.createElement('div');
                        tempDiv.innerHTML = cardHtml;
                        fragment.appendChild(tempDiv.firstElementChild);
                    }
                }

                if (includeRevisions && revisionsSupported) {
                    const postsNeedingRevisions = posts.filter(post => !getBestMediaUrlFromPost(post, includeGifs));
                    if (postsNeedingRevisions.length > 0) {
                        showStatus(`Checking revisions for ${postsNeedingRevisions.length} posts...`, 'info');
                        let revisionFoundCount = 0;
                        for (let j = 0; j < postsNeedingRevisions.length; j++) {
                            const post = postsNeedingRevisions[j];
                            showStatus(`Fetching revision from post ${post.id}... (${j + 1}/${postsNeedingRevisions.length})`, 'info');
                            const mediaData = await getRevisionMediaData(post, includeGifs);
                            if (mediaData && mediaData.media) {
                                revisionFoundCount++;
                                const mediaInfo = mediaData.media;
                                const revisionId = mediaData.revisionId;
                                const previewUrl = mediaData.previewUrl;
                                if (mediaInfo.type === 'video') {
                                    totalVideoPostsFound++;
                                    pageVideoCount++;
                                    totalThumbnailsToLoad++;
                                } else if (mediaInfo.type === 'gif') {
                                    totalGifPostsFound++;
                                    pageGifCount++;
                                }
                                allFoundVideoUrls.push(mediaInfo.url);
                                const cardHtml = createPostCardHtml(post, mediaInfo, previewUrl, revisionId);
                                const tempDiv = document.createElement('div');
                                tempDiv.innerHTML = cardHtml;
                                fragment.appendChild(tempDiv.firstElementChild);
                            }
                        }
                        if (revisionFoundCount > 0) showStatus(`Added ${revisionFoundCount} revision media posts`, 'success');
                    }
                }

                if (fragment.children.length > 0) postListContainer.appendChild(fragment);

                const totalFound = totalVideoPostsFound + totalGifPostsFound;
                if (paginatorInfo) {
                    let typeText = '';
                    if (pageVideoCount > 0 && pageGifCount > 0) typeText = ` (+${pageVideoCount} videos, +${pageGifCount} GIFs)`;
                    else if (pageVideoCount > 0) typeText = ` (+${pageVideoCount} videos)`;
                    else if (pageGifCount > 0) typeText = ` (+${pageGifCount} GIFs)`;
                    paginatorInfo.textContent = `Showing ${totalFound} ${mediaTypeLabel} posts${typeText}.`;
                }
            } catch (error) {
                const errMsg = (error.message || error || '').toString();
                if (errMsg.includes('429')) {
                    failed429Pages.push(pageNum);
                    console.warn(`Video Filter: Page ${pageNum} failed due to error 429${error429FixEnabled ? ' (after 5 retries)' : ''}`);
                    showStatus(`Page ${pageNum} skipped (error 429)`, 'warning');
                } else {
                    console.error("Video Filter error:", error);
                    showStatus(`Error on page ${pageNum}: ${errMsg}`, 'error');
                    errors++;
                }
            }
        }

        // Final paginator – Showing... on first line, 429 failures on a new red line
        if (paginatorInfo) {
            const totalFound = totalVideoPostsFound + totalGifPostsFound;
            let typeText = '';
            if (totalVideoPostsFound > 0 && totalGifPostsFound > 0) typeText = ` (+${totalVideoPostsFound} videos, +${totalGifPostsFound} GIFs)`;
            else if (totalVideoPostsFound > 0) typeText = ` (+${totalVideoPostsFound} videos)`;
            else if (totalGifPostsFound > 0) typeText = ` (+${totalGifPostsFound} GIFs)`;

            const showingText = `Showing ${totalFound} ${mediaTypeLabel} posts${typeText}.`;
            paginatorInfo.textContent = showingText;

            if (failed429Pages.length > 0) {
                let failedListStr = failed429Pages.length === 1
                    ? failed429Pages[0]
                    : `${failed429Pages.slice(0, -1).join(', ')} and ${failed429Pages[failed429Pages.length - 1]}`;
                const failedText = `Pages ${failedListStr} failed due to error 429.`;
                paginatorInfo.innerHTML += `<br><span style="color: #ff6b6b;">${failedText}</span>`;
            }
        }

        if (totalThumbnailsToLoad > 0) {
            showStatus(`Loading thumbnails: 0/${totalThumbnailsToLoad}`, 'info');
        }
        postListContainer.querySelectorAll('video.lazy-load-video').forEach(videoEl => {
            if (videoEl.querySelector('source[data-src]')) videoIntersectionObserver.observe(videoEl);
        });
        if (totalThumbnailsToLoad === 0) showStatus('Filter complete. No videos to load.', 'info');

        finishFiltering(totalVideoPostsFound, totalGifPostsFound, mediaTypeLabel);
    }

    function resetFilterButton() {
        isFiltering = false;
        filterButton.textContent = 'Filter Videos/GIFs';
        styleButton(filterButton, false);
        filterButton.disabled = false;
    }

    function finishFiltering(videoCount, gifCount, mediaTypeLabel) {
        isFiltering = false;
        filterButton.textContent = 'Filter Videos/GIFs';
        styleButton(filterButton, false);
        filterButton.disabled = false;
        const totalFound = videoCount + gifCount;
        if (totalFound > 0) {
            let statusText = `Filter complete. Found ${totalFound} ${mediaTypeLabel} posts`;
            if (videoCount > 0 && gifCount > 0) statusText += ` (${videoCount} videos, ${gifCount} GIFs)`;
            else if (videoCount > 0) { statusText += ` (${videoCount} videos)`; }
            else if (gifCount > 0) { statusText += ` (${gifCount} GIFs)`; }
            statusText += '.';
            showStatus(statusText, 'success');
            styleButton(copyUrlsButton, false);
            copyUrlsButton.disabled = false;
        } else {
            showStatus(`Filter complete. No ${mediaTypeLabel} posts found.`, 'info');
            styleButton(copyUrlsButton, true);
            copyUrlsButton.disabled = true;
        }
    }

    function handleCopyUrls() {
        if (allFoundVideoUrls.length === 0) { showStatus("No URLs to copy.", 'error'); return; }
        const uniqueUrls = [...new Set(allFoundVideoUrls)];
        GM_setClipboard(uniqueUrls.join('\n'));
        copyUrlsButton.textContent = `Copied ${uniqueUrls.length} URLs!`;
        showStatus(`Copied ${uniqueUrls.length} unique media URLs!`, 'success');
        setTimeout(() => { copyUrlsButton.textContent = 'Copy URLs'; }, 3000);
    }

    function handleUrlChangeAndSetStatus() {
        console.log("Video Filter: URL change detected or initial load.");
        const currentContext = determinePageContext();
        allFoundVideoUrls = [];
        requestQueue = [];
        activeRequests = 0;
        thumbnailRetryMap.clear();
        failedThumbnails.clear();
        totalThumbnailsToLoad = 0;
        thumbnailsLoadedCount = 0;
        allMediaLoadedShown = false;
        styleButton(copyUrlsButton, true);
        copyUrlsButton.disabled = true;
        if (videoIntersectionObserver) videoIntersectionObserver.disconnect();
        if (currentContext) {
            showStatus("Filter ready.", 'info');
            styleButton(filterButton, false);
            filterButton.disabled = false;
        } else {
            showStatus("Page context not recognized. Filter disabled.", 'error');
            styleButton(filterButton, true);
            filterButton.disabled = true;
        }
    }

    function loadSettings() {
        const savedPages = localStorage.getItem(LS_PAGES_KEY);
        if (savedPages) pageRangeInput.value = savedPages;

        // Toggles now use GM storage (persistent even when localStorage quota is exceeded)
        includeRevisions = GM_getValue(GM_REVISIONS_KEY, false);
        revisionsToggle.checked = includeRevisions;

        includeGifs = GM_getValue(GM_GIFS_KEY, false);
        gifsToggle.checked = includeGifs;

        error429FixEnabled = GM_getValue(GM_ERROR429_KEY, false);
        error429Toggle.checked = error429FixEnabled;

        if (!revisionsSupported) includeRevisions = false;
    }

    // --- SCRIPT INITIALIZATION ---
    filterButton.addEventListener('click', handleFilter);
    copyUrlsButton.addEventListener('click', handleCopyUrls);
    collapseButton.addEventListener('click', togglePanelCollapse);
    settingsButton.addEventListener('click', (e) => { e.stopImmediatePropagation(); toggleSettingsPanel(); });

    revisionsToggle.addEventListener('change', () => {
        includeRevisions = revisionsToggle.checked;
        GM_setValue(GM_REVISIONS_KEY, includeRevisions);
    });
    gifsToggle.addEventListener('change', () => {
        includeGifs = gifsToggle.checked;
        GM_setValue(GM_GIFS_KEY, includeGifs);
    });
    error429Toggle.addEventListener('change', () => {
        error429FixEnabled = error429Toggle.checked;
        GM_setValue(GM_ERROR429_KEY, error429FixEnabled);
    });

    const originalPushState = history.pushState;
    const originalReplaceState = history.replaceState;
    history.pushState = function() { originalPushState.apply(this, arguments); window.dispatchEvent(new Event('custompushstate')); };
    history.replaceState = function() { originalReplaceState.apply(this, arguments); window.dispatchEvent(new Event('customreplacestate')); };

    window.addEventListener('popstate', handleUrlChangeAndSetStatus);
    window.addEventListener('custompushstate', handleUrlChangeAndSetStatus);
    window.addEventListener('customreplacestate', handleUrlChangeAndSetStatus);

    const initiallyCollapsed = localStorage.getItem(LS_COLLAPSE_KEY) === 'true';
    if (initiallyCollapsed) togglePanelCollapse();

    loadSettings();
    handleUrlChangeAndSetStatus();

    window.addEventListener('beforeunload', () => {
        if (videoIntersectionObserver) videoIntersectionObserver.disconnect();
        document.querySelectorAll('video.lazy-load-video').forEach(videoEl => {
            if (videoEl.dataset.loadTimeout) clearTimeout(videoEl.dataset.loadTimeout);
        });
    });
})();