// ==UserScript==
// @name         Send to yt-dlp v2
// @namespace    http://tampermonkey.net/
// @version      9.6
// @description  Whitelisted video and image downloader with gallery page ranges
// @match        *://*/*
// @noframes
// @run-at       document-idle
// @grant        GM.xmlHttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @connect      127.0.0.1
// ==/UserScript==

(() => {
    'use strict';

    const SERVER = 'http://127.0.0.1:8000';
    const SITES_KEY = 'ytdlp_allowed_sites';
    const TOKEN_KEY = 'ytdlp_server_token';
    const DEFAULT_SITES = ['bilibili.com', 'aibooru.online'];
    const onDomain = (host, domain) => host === domain || host.endsWith(`.${domain}`);
    const isACG = ['acg-hentai.com', 'porn-comic.com']
        .some(domain => onDomain(location.hostname, domain));
    const isAibooru = onDomain(location.hostname, 'aibooru.online');
    const STREAM_RE = /\.(mp4|webm|m4v|mov|m3u8|mpd)$/i;
    const IMAGE_RE = /\.(jpe?g|png|gif|webp|avif|bmp|apng)$/i;
    const ACG_RE = /^\/(?:[a-z]{2}\/)?(gif|hentai|h|cos|western)\/(\d+)(?:-(\d+))?\.html$/i;
    const BOORU_RE = /^\/posts\/(\d+)\/?$/;
    const GALLERY_CHUNK = 20;

    function sites() {
        const saved = GM_getValue(SITES_KEY, DEFAULT_SITES);
        return Array.isArray(saved) ? saved : [...DEFAULT_SITES];
    }

    GM_registerMenuCommand('Set server token', () => {
        const value = prompt('Paste the Python server pairing token:', '');
        if (value?.trim()) {
            GM_setValue(TOKEN_KEY, value.trim());
            alert('Pairing token saved.');
        }
    });

    GM_registerMenuCommand('Allow this site', () => {
        const list = sites();
        if (!list.some(domain => onDomain(location.hostname, domain))) {
            GM_setValue(SITES_KEY, [...list, location.hostname]);
        }
        location.reload();
    });

    GM_registerMenuCommand('Edit allowed sites', () => {
        const value = prompt(
            'Domains separated by commas or new lines. Subdomains are included.',
            sites().join(', ')
        );
        if (value === null) return;
        const list = value.split(/[\n,]+/).map(part => part.trim().toLowerCase());
        GM_setValue(SITES_KEY, [...new Set(list.filter(Boolean))]);
        location.reload();
    });

    if (!sites().some(domain => onDomain(location.hostname, domain))) return;

    function request(path, payload) {
        return new Promise((resolve, reject) => {
            const token = GM_getValue(TOKEN_KEY, '');
            if (!token) {
                reject(new Error('Use Set server token in the Tampermonkey menu first.'));
                return;
            }

            GM.xmlHttpRequest({
                method: 'POST',
                url: SERVER + path,
                headers: {
                    'Content-Type': 'application/json',
                    'X-Bridge-Token': token
                },
                data: JSON.stringify(payload),
                timeout: 30000,
                onload(response) {
                    let result;
                    try {
                        result = JSON.parse(response.responseText);
                    } catch {
                        reject(new Error('The Python server returned an invalid response.'));
                        return;
                    }
                    if (response.status >= 200 && response.status < 300) {
                        resolve(result);
                    } else {
                        reject(new Error(result.error || `HTTP ${response.status}`));
                    }
                },
                onerror: () => reject(new Error('Cannot reach the Python server.')),
                ontimeout: () => reject(new Error('The Python server request timed out.'))
            });
        });
    }

    const el = (tag, text = '') => {
        const node = document.createElement(tag);
        node.textContent = text;
        return node;
    };

    const button = (text, action) => {
        const node = el('button', text);
        node.type = 'button';
        node.addEventListener('click', action);
        return node;
    };

    const host = el('div');
    host.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:2147483647';
    document.body.append(host);
    const root = host.attachShadow({ mode: 'closed' });
    const style = el('style', `
        :host { all: initial; }
        .box { font: 13px Arial,sans-serif; color: #222; background: #fff;
               border: 1px solid #777; border-radius: 7px; padding: 7px;
               box-shadow: 0 2px 10px #0004; }
        .panel { width: min(330px, calc(100vw - 42px)); }
        [hidden] { display: none !important; }
        button { font: inherit; color: #222; background: #f3f3f3; cursor: pointer;
                 margin: 3px; padding: 5px 8px; border: 1px solid #aaa;
                 border-radius: 4px; }
        button:disabled { opacity: .55; cursor: default; }
        .filters { display: flex; gap: 12px; margin: 6px 3px; }
        .media { max-height: 150px; overflow: auto; }
        .media label, .settings label { display: block; overflow-wrap: anywhere; }
        .settings input, .settings select { width: 100%; box-sizing: border-box;
                                           padding: 5px; margin: 4px 0 8px; }
        .status { margin: 6px 3px; white-space: pre-wrap; overflow-wrap: anywhere;
                  max-height: 140px; overflow: auto; }
    `);
    const box = el('div');
    box.className = 'box';
    const panel = el('div');
    panel.className = 'panel';
    panel.hidden = true;
    const status = el('div', 'Ready.');
    status.className = 'status';
    status.setAttribute('role', 'status');
    const say = message => { status.textContent = message; };
    root.append(style, box);
    box.append(button('DL', () => { panel.hidden = !panel.hidden; }), panel);

    let sending = false;

    function sendAction(label, action) {
        const control = button(label, async () => {
            if (sending) return;
            sending = true;
            control.disabled = true;
            try {
                await action();
            } catch (error) {
                say(error.message);
            } finally {
                sending = false;
                control.disabled = false;
            }
        });
        return control;
    }

    function asWebUrl(value, base) {
        if (typeof value !== 'string' || !value.trim()) return null;
        try {
            const url = new URL(value, base);
            return /^https?:$/.test(url.protocol) && !url.username && !url.password
                ? url : null;
        } catch {
            return null;
        }
    }

    function item(url, source = url, kind = 'video', filename = null, referer = location.href) {
        return {
            url, source_url: source, kind, filename, referer,
            user_agent: navigator.userAgent
        };
    }

    async function queueItems(items) {
        if (!items.length) throw new Error('Select at least one item first.');
        const result = await request('/', { items });
        return result.count;
    }

    async function readPage(url, type) {
        const target = asWebUrl(url, location.href);
        if (!target || target.origin !== location.origin) {
            throw new Error('The post link leaves the current site.');
        }

        const response = await fetch(target.href, {
            credentials: 'same-origin',
            redirect: 'error',
            signal: AbortSignal.timeout(25000)
        });
        if (!response.ok) throw new Error(`Post returned HTTP ${response.status}.`);

        if (type === 'json') {
            if (!(response.headers.get('content-type') || '').includes('json')) {
                throw new Error('The post returned a page instead of its metadata.');
            }
            return response.json();
        }

        const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
        if (/^just a moment/i.test(doc.title.trim()) || doc.querySelector('#challenge-error-text')) {
            throw new Error('The site returned an access check.');
        }
        return doc;
    }

    function fileKind(value) {
        if (typeof value !== 'string' || !value) return '';
        const path = asWebUrl(value, location.href)?.pathname || '';
        if (IMAGE_RE.test(path) || IMAGE_RE.test(`.${value}`)) return 'image';
        if (STREAM_RE.test(path) || STREAM_RE.test(`.${value}`)) return 'video';
        return '';
    }

    const booruMetadata = new Map();

    async function readBooru(url) {
        if (booruMetadata.has(url)) return booruMetadata.get(url);
        const endpoint = new URL(url);
        endpoint.pathname = endpoint.pathname.replace(/\/$/, '') + '.json';
        const data = await readPage(endpoint.href, 'json');
        const kind = fileKind(data.file_ext) || fileKind(data.file_url);
        if (!kind) throw new Error('Aibooru did not return a recognized file type.');
        const metadata = { kind, data };
        booruMetadata.set(url, metadata);
        return metadata;
    }

    function acgVideo(doc, page) {
        function findVideo(value) {
            if (!value || typeof value !== 'object') return null;
            if (Array.isArray(value)) {
                for (const entry of value) {
                    const found = findVideo(entry);
                    if (found) return found;
                }
                return null;
            }
            const types = [value['@type']].flat();
            if (types.includes('VideoObject') && typeof value.contentUrl === 'string') {
                return value;
            }
            return findVideo(value['@graph']);
        }

        for (const node of doc.querySelectorAll('script[type="application/ld+json"]')) {
            let metadata;
            try {
                metadata = findVideo(JSON.parse(node.textContent));
            } catch {
                continue;
            }
            if (!metadata) continue;
            const media = asWebUrl(metadata.contentUrl, page.href);
            if (!media || !STREAM_RE.test(media.pathname)) continue;
            const postId = page.pathname.match(ACG_RE)?.[2];
            const name = typeof metadata.name === 'string' && postId
                ? `${metadata.name}_${postId}` : null;
            return item(media.href, page.href, 'video', name, page.href);
        }
        throw new Error('This post did not provide a supported video URL.');
    }

    function bilibiliPage(url) {
        if (!onDomain(url.hostname, 'bilibili.com')) return url;
        if (url.pathname === '/player.html' || url.hostname === 'player.bilibili.com') {
            const bvid = url.searchParams.get('bvid') || '';
            const aid = url.searchParams.get('aid') || '';
            const part = url.searchParams.get('p') || url.searchParams.get('page') || '';
            const id = /^BV[0-9A-Za-z]+$/i.test(bvid) ? bvid
                : /^\d+$/.test(aid) ? `av${aid}` : '';
            if (id) {
                const video = new URL(`https://www.bilibili.com/video/${id}`);
                if (/^\d+$/.test(part) && part !== '1') video.searchParams.set('p', part);
                return video;
            }
        }
        url.pathname = url.pathname.replace(/^\/[a-z]{2}(?:-[a-z]{2})?\/video\//i, '/video/');
        return url;
    }

    function galleryPageUrl(page, number) {
        const url = new URL(page.href);
        url.pathname = url.pathname.replace(
            /(\d+)(?:-\d+)?\.html$/i, `$1${number === 1 ? '' : `-${number}`}.html`
        );
        url.search = '';
        url.hash = '';
        return url;
    }

    function galleryRange(doc, page, match) {
        const current = Number(match[3] || 1);
        let total = current;
        for (const link of doc.querySelectorAll('#pages a[href]')) {
            const target = asWebUrl(link.getAttribute('href'), page.href);
            const other = target?.pathname.match(ACG_RE);
            if (target?.origin !== page.origin || !other ||
                other[1] !== match[1] || other[2] !== match[2]) continue;
            const number = Number(other[3] || 1);
            if (Number.isSafeInteger(number)) total = Math.max(total, number);
        }

        const answer = prompt(
            `Gallery pages 1–${total}. Enter one page, a range such as 10-25, or all.`,
            String(current)
        );
        if (answer === null) return null;
        if (answer.trim().toLowerCase() === 'all') return [1, total];

        const range = answer.trim().match(/^(\d+)(?:\s*-\s*(\d+))?$/);
        const first = Number(range?.[1]);
        const last = Number(range?.[2] ?? range?.[1]);
        if (!range || first < 1 || last < first || last > total) {
            throw new Error(`Enter a page or an ascending range within 1–${total}.`);
        }
        return [first, last];
    }

    function galleryImage(doc, page, match, number) {
        const image = doc.querySelector('.acg-manga .manga-picture img');
        const media = asWebUrl(image?.getAttribute('src'), page.href);
        if (!media) throw new Error('The gallery page did not contain its main image.');
        const title = doc.querySelector('h1.title')?.textContent.trim() || 'Gallery';
        const name = `${title}_${match[2]}_p${String(number).padStart(4, '0')}`;
        return item(media.href, page.href, 'image', name, page.href);
    }

    async function queueGallery(page, doc) {
        const match = page.pathname.match(ACG_RE);
        const initialPage = Number(match[3] || 1);
        const range = galleryRange(doc, page, match);
        if (!range) return null;

        const [first, last] = range;
        let count = 0;
        let pending = [];

        async function flush() {
            if (pending.length) {
                count += await queueItems(pending);
                pending = [];
            }
        }

        for (let number = first; number <= last; number++) {
            const target = galleryPageUrl(page, number);
            say(`Reading gallery page ${number} of ${last}. Queued ${count}.`);
            let job;
            try {
                const pageDoc = number === initialPage ? doc : await readPage(target.href, 'html');
                job = galleryImage(pageDoc, target, match, number);
            } catch (error) {
                await flush();
                throw new Error(
                    `Queued ${count}. Stopped at gallery page ${number}. ${error.message}`
                );
            }
            pending.push(job);
            if (pending.length >= GALLERY_CHUNK) await flush();
        }
        await flush();
        return count;
    }

    async function queueBooruImage(url) {
        const { kind, data } = await readBooru(url);
        const media = asWebUrl(data.file_url, url);
        if (kind !== 'image' || !media) {
            throw new Error('Aibooru did not provide the original image URL.');
        }
        const id = new URL(url).pathname.match(BOORU_RE)[1];
        const artist = String(data.tag_string_artist || '').trim();
        const series = String(data.tag_string_copyright || '').trim();
        const name = [artist, series, `Aibooru_${id}`].filter(Boolean).join(' - ');
        return queueItems([item(media.href, url, 'image', name, url)]);
    }

    panel.append(sendAction('Send this page', async () => {
        const page = new URL(location.href);
        const acg = isACG && page.pathname.match(ACG_RE);

        let count;
        if (acg?.[1] === 'hentai') {
            count = await queueGallery(page, document);
        } else if (acg?.[1] === 'gif') {
            count = await queueItems([acgVideo(document, page)]);
        } else if (isAibooru && BOORU_RE.test(page.pathname)) {
            const url = page.origin + page.pathname.replace(/\/$/, '');
            const container = document.querySelector('#image-container');
            const kind = fileKind(container?.dataset.fileExt) ||
                fileKind(container?.dataset.fileUrl) ||
                (container?.querySelector('video') ? 'video' : '') ||
                (await readBooru(url)).kind;
            count = kind === 'image'
                ? await queueBooruImage(url)
                : await queueItems([item(url)]);
        } else {
            count = await queueItems([item(bilibiliPage(page).href)]);
        }
        say(count === null ? 'Gallery selection canceled.' : `Queued ${count} item(s).`);
    }));

    const mediaArea = el('div');
    mediaArea.className = 'media';

    panel.append(button('Find media', () => {
        const found = new Map();
        function add(value, imagesAllowed = false) {
            const url = asWebUrl(value, location.href);
            if (!url) return;
            const kind = fileKind(url.href);
            if (kind === 'video' || (kind === 'image' && imagesAllowed)) {
                found.set(url.href, kind);
            }
        }

        document.querySelectorAll('video, audio, source').forEach(node => {
            add(node.currentSrc);
            add(node.getAttribute('src'));
        });
        performance.getEntriesByType('resource').forEach(entry => add(entry.name));

        const mainImage = isACG
            ? document.querySelector('.acg-manga .manga-picture img')
            : isAibooru ? document.querySelector('#image-container img#image') : null;
        add(mainImage?.currentSrc, true);
        add(mainImage?.getAttribute('src'), true);

        if (isACG && location.pathname.match(ACG_RE)?.[1] === 'gif') {
            try { add(acgVideo(document, new URL(location.href)).url); } catch {}
        }

        mediaArea.replaceChildren();
        for (const [url, kind] of found) {
            const label = el('label');
            const check = el('input');
            check.type = 'checkbox';
            check.value = url;
            check.dataset.kind = kind;
            label.append(check, document.createTextNode(` ${kind}: ${url}`));
            mediaArea.append(label);
        }
        say(found.size
            ? `Found ${found.size} media URL(s).`
            : 'No media URLs found. For video, try starting playback.');
    }));

    panel.append(sendAction('Send selected media', async () => {
        const items = [...mediaArea.querySelectorAll('input:checked')]
            .map(node => item(node.value, node.value, node.dataset.kind));
        say(`Queued ${await queueItems(items)} item(s).`);
    }), mediaArea);

    if (isACG || isAibooru) {
        const selected = new Map();
        const marked = new Map();
        const pendingTypes = new Set();
        const filters = el('div');
        filters.className = 'filters';
        const enabled = {};
        let selecting = false;

        const selectionCount = () => {
            const images = [...selected.values()].filter(kind => kind === 'image').length;
            return `${selected.size - images} video(s), ${images} image post(s) selected.`;
        };

                function listRoot() {
            if (!isACG) return document;
            return document.querySelector('#list') || document.querySelector('.grid');
        }

        function describe(anchor) {
            const url = asWebUrl(anchor?.href, location.href);
            if (!url || url.origin !== location.origin) return null;

            if (isACG) {
                const match = url.pathname.match(ACG_RE);
                const root = listRoot();
                const card = anchor.closest('li, .grid-item');
                if (!match || !root || !card || !root.contains(card)) return null;
                return {
                    card, url: url.origin + url.pathname,
                    kind: match[1] === 'gif' ? 'video' : 'image'
                };
            }

            const match = url.pathname.match(BOORU_RE);
            const card = anchor.closest('article, .post-preview, li');
            if (!match || !card) return null;
            const canonical = `${url.origin}/posts/${match[1]}`;
            const kind = booruMetadata.get(canonical)?.kind ||
                fileKind(card.dataset.fileExt) || fileKind(card.dataset.fileUrl) ||
                fileKind(anchor.dataset.fileExt) || fileKind(anchor.dataset.fileUrl);
            return { card, url: canonical, kind };
        }

        function setStyle(card, name, value) {
            const old = [card.style.getPropertyValue(name), card.style.getPropertyPriority(name)];
            card.style.setProperty(name, value, 'important');
            return old;
        }

        function restoreStyle(card, name, [value, priority]) {
            if (value) card.style.setProperty(name, value, priority);
            else card.style.removeProperty(name);
        }

        function clearMarks() {
            for (const [card, entry] of marked) {
                entry.badge.remove();
                if (entry.adjustedPosition) card.style.position = entry.oldPosition;
                restoreStyle(card, 'outline', entry.oldOutline);
                restoreStyle(card, 'outline-offset', entry.oldOffset);
            }
            marked.clear();
        }

        function markNew() {
            if (!selecting || (!enabled.video.checked && !enabled.image.checked)) return;
            for (const link of listRoot()?.querySelectorAll('a[href]') || []) {
                const post = describe(link);
                if (!post || marked.has(post.card)) continue;
                const kind = selected.get(post.url) || post.kind;
                if (kind && !enabled[kind].checked) continue;

                const active = selected.has(post.url);
                const color = active ? (kind === 'image' ? '#1a73e8' : '#1e8e3e') : '#222';
                const label = kind ? `${active ? 'Selected' : 'Select'} ${kind}` : 'Check type';
                const badge = el('span', label);
                badge.style.cssText = `position:absolute;top:6px;left:6px;z-index:10;
                    width:auto;height:auto;margin:0;padding:4px 7px;background:${color};
                    color:#fff;font:bold 12px Arial,sans-serif;border-radius:4px;
                    pointer-events:none`;

                const card = post.card;
                const oldPosition = card.style.position;
                const adjustedPosition = getComputedStyle(card).position === 'static';
                if (adjustedPosition) card.style.position = 'relative';

                const oldOutline = setStyle(card, 'outline',
                    active ? `4px solid ${color}` : '2px dashed #999');
                const oldOffset = setStyle(card, 'outline-offset', active ? '-4px' : '-2px');

                card.append(badge);
                marked.set(card, {
                    badge, url: post.url, adjustedPosition, oldPosition, oldOutline, oldOffset
                });
            }
        }

        function refreshMarks() {
            clearMarks();
            markNew();
        }

        // Marks cards the site adds later, for example while scrolling.
        let markTimer = 0;
        new MutationObserver(() => {
            if (!selecting) return;
            clearTimeout(markTimer);
            markTimer = setTimeout(markNew, 300);
        }).observe(document.body, { childList: true, subtree: true });
        for (const [kind, text] of [['video', 'Select videos'], ['image', 'Select images']]) {
            const label = el('label');
            const check = el('input');
            check.type = 'checkbox';
            check.checked = true;
            enabled[kind] = check;
            check.addEventListener('change', () => {
                if (!check.checked) {
                    for (const [url, selectedKind] of selected) {
                        if (selectedKind === kind) selected.delete(url);
                    }
                }
                refreshMarks();
                say(selectionCount());
            });
            label.append(check, document.createTextNode(` ${text}`));
            filters.append(label);
        }

        const toggleSelection = button('Select posts', () => {
            selecting = !selecting;
            toggleSelection.textContent = selecting ? 'Stop selecting' : 'Select posts';
            refreshMarks();
            say(selecting ? 'Click a marked post to select it.' : selectionCount());
        });

        document.addEventListener('click', async event => {
            if (!selecting || sending || !(event.target instanceof Element)) return;
            const post = describe(event.target.closest('a[href]'));
            if (!post || marked.get(post.card)?.url !== post.url) return;

            event.preventDefault();
            event.stopPropagation();
            if (pendingTypes.has(post.url)) return;

            if (selected.delete(post.url)) {
                refreshMarks();
                say(selectionCount());
                return;
            }

            pendingTypes.add(post.url);
            try {
                const kind = post.kind || (await readBooru(post.url)).kind;
                if (!selecting || sending) return;
                if (enabled[kind].checked) selected.set(post.url, kind);
                refreshMarks();
                say(enabled[kind].checked ? selectionCount() : `${kind} posts are filtered out.`);
            } catch (error) {
                say(error.message);
            } finally {
                pendingTypes.delete(post.url);
            }
        }, true);

        panel.append(filters, toggleSelection, sendAction('Send selected posts', async () => {
            const posts = [...selected.entries()];
            if (!posts.length) throw new Error('Select at least one post first.');

            let queued = 0;
            let canceled = 0;
            const failures = [];
            for (const [url, kind] of posts) {
                if (selected.get(url) !== kind || !enabled[kind].checked) continue;
                let count;
                try {
                    if (isACG) {
                        const page = new URL(url);
                        const doc = await readPage(url, 'html');
                        count = kind === 'image'
                            ? await queueGallery(page, doc)
                            : await queueItems([acgVideo(doc, page)]);
                    } else {
                        count = kind === 'image'
                            ? await queueBooruImage(url)
                            : await queueItems([item(url)]);
                    }
                    if (count === null) {
                        canceled++;
                        continue;
                    }
                    queued += count;
                    selected.delete(url);
                } catch (error) {
                    failures.push(`${new URL(url).pathname}: ${error.message}`);
                }
            }
            refreshMarks();
            say([
                `Queued ${queued} item(s) from completed selections.`,
                canceled ? `${canceled} gallery selection(s) canceled.` : '',
                failures.length ? failures.join('\n') : ''
            ].filter(Boolean).join('\n'));
        }), button('Clear selection', () => {
            selected.clear();
            refreshMarks();
            say(selectionCount());
        }));
    }

    const settings = el('div');
    settings.className = 'settings';
    settings.hidden = true;
    const browser = el('select');
    const profile = el('input');
    profile.type = 'text';
    profile.placeholder = 'Optional absolute profile directory';
    const cookieMode = el('select');

    function option(value, text) {
        const node = el('option', text);
        node.value = value;
        return node;
    }

    function field(text, control) {
        const label = el('label', text);
        label.append(control);
        settings.append(label);
    }

    cookieMode.append(
        option('off', 'Off'),
        option('retry', 'Retry with cookies after an access error'),
        option('always', 'Always use browser cookies')
    );
    field('Browser', browser);
    field('Profile directory', profile);
    field('Cookie mode for yt-dlp', cookieMode);

    panel.append(button('Config', async () => {
        if (!settings.hidden) {
            settings.hidden = true;
            return;
        }
        try {
            const result = await request('/config/get', {});
            browser.replaceChildren(option('', 'Select a browser'));
            for (const name of result.browsers) browser.append(option(name, name));
            browser.value = result.config.browser;
            profile.value = result.config.profile;
            cookieMode.value = result.config.cookie_mode;
            settings.hidden = false;
        } catch (error) {
            say(error.message);
        }
    }));

    settings.append(button('Save config', async () => {
        try {
            await request('/config/save', {
                config: {
                    browser: browser.value,
                    profile: profile.value.trim(),
                    cookie_mode: cookieMode.value
                }
            });
            settings.hidden = true;
            say('Config saved for future downloads.');
        } catch (error) {
            say(error.message);
        }
    }));

    panel.append(settings, status);
})();