text paste
// ==UserScript==
// @name         OSHO World · Auto Paginate Downloader
// @namespace    https://oshoworld.com/
// @version      3.0
// @description  Auto-download MP3s page by page. Clicks "Next" automatically until the last page.
// @author       BROK
// @match        https://oshoworld.com/*
// @match        https://www.oshoworld.com/*
// @grant        GM_download
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';

    const CFG = {
        autoScanDelay: 1000,
        betweenPagesDelay: 4000,   // 下载触发后等多久再跳转
        maxPages: 200,             // 安全上限
        storageKey: 'osho_autopaginate_state'
    };

    // ============ STATE (跨页面) ============
    function loadState() {
        try {
            const raw = sessionStorage.getItem(CFG.storageKey);
            return raw ? JSON.parse(raw) : null;
        } catch (e) { return null; }
    }
    function saveState(s) {
        sessionStorage.setItem(CFG.storageKey, JSON.stringify(s));
    }
    function clearState() {
        sessionStorage.removeItem(CFG.storageKey);
    }

    let state = loadState();   // null = 未启动;{active:true, page:1, downloaded:[], visited:[]}
    let isRunning = false;
    let mp3List = [];

    // ============ HELPERS ============
    const sleep = ms => new Promise(r => setTimeout(r, ms));
    const esc = t => { const d = document.createElement('div'); d.appendChild(document.createTextNode(String(t))); return d.innerHTML; };

    function filenameFromUrl(url) {
        try {
            const u = new URL(url, location.href);
            return decodeURIComponent(u.pathname.split('/').pop() || 'audio.mp3');
        } catch (e) { return 'audio.mp3'; }
    }
    function cleanName(f) {
        return f.replace(/\.mp3$/i, '').replace(/[_-]+/g, ' ').replace(/\s+/g, ' ').trim();
    }

    // ============ SCAN ============
    function scan() {
        const found = new Set();
        document.querySelectorAll('a[href]').forEach(a => {
            const h = a.href;
            if (/\.mp3(\?|$)/i.test(h)) found.add(h);
        });
        document.querySelectorAll('audio[src], audio source[src]').forEach(el => {
            const s = el.src || el.getAttribute('src');
            if (s && /\.mp3(\?|$)/i.test(s)) found.add(new URL(s, location.href).href);
        });
        // 裸 URL in HTML
        const html = document.documentElement.innerHTML;
        const re = /https?:\/\/[^\s"'<>()\\]+?\.mp3(?:\?[^\s"'<>()\\]*)?/gi;
        let m;
        while ((m = re.exec(html)) !== null) found.add(m[0].replace(/\\\//g, '/'));
        // 相对路径
        const relRe = /["']([^"']*?\/wp-content\/uploads\/[^"']*?\.mp3)["']/gi;
        while ((m = relRe.exec(html)) !== null) {
            try { found.add(new URL(m[1], location.href).href); } catch (e) {}
        }
        mp3List = Array.from(found).sort().map(url => ({ url, name: filenameFromUrl(url) }));
        return mp3List;
    }

    // ============ NEXT PAGE DETECTION ============
    function findNextPage() {
        // 多种策略,按优先级
        const candidates = [
            // rel=next
            ...document.querySelectorAll('a[rel="next"]'),
            // 常见类名
            ...document.querySelectorAll('a.next, a.next-page, a.pagination-next, .pagination a:last-child, .nav-next a'),
            // 文字匹配
            ...Array.from(document.querySelectorAll('a')).filter(a => {
                const t = (a.textContent || '').trim().toLowerCase();
                const t2 = (a.getAttribute('aria-label') || '').toLowerCase();
                const t3 = (a.getAttribute('title') || '').toLowerCase();
                return /^(next|next page|next →|→|›|»|下一页|下一頁)$/.test(t) ||
                       /next/.test(t2) || /next/.test(t3);
            })
        ];

        for (const a of candidates) {
            const href = a.href;
            if (!href) continue;
            if (!href.startsWith(location.origin)) continue;      // 同站
            if (href === location.href) continue;                 // 不是自己
            if (/#/.test(href)) continue;                         // 跳过锚点
            // 避免误判"首页"等导航链接
            const path = new URL(href).pathname;
            if (path === '/' || path === '') continue;
            return href;
        }
        return null;
    }

    // ============ DOWNLOAD ============
    function downloadOne(item) {
        return new Promise(resolve => {
            try {
                if (typeof GM_download === 'function') {
                    GM_download({
                        url: item.url,
                        name: item.name,
                        onload: () => resolve(true),
                        onerror: () => { fallbackAnchor(item); resolve(false); },
                        ontimeout: () => { fallbackAnchor(item); resolve(false); }
                    });
                } else {
                    fallbackAnchor(item);
                    resolve(true);
                }
            } catch (e) { fallbackAnchor(item); resolve(false); }
        });
    }
    function fallbackAnchor(item) {
        const a = document.createElement('a');
        a.href = item.url; a.download = item.name;
        a.style.display = 'none';
        document.body.appendChild(a); a.click();
        setTimeout(() => a.remove(), 100);
    }

    // ============ AUTO PAGINATE ============
    async function runAutoPaginate() {
        if (!state) {
            state = { active: true, page: 1, downloaded: [], visited: [location.href] };
            saveState(state);
            console.log('[AutoPaginate] started');
        }
        isRunning = true;
        updateButtons();

        const currentPage = state.page;
        setStatus(`Page ${currentPage} · scanning...`, 'loading');

        // 1. 扫描
        await sleep(300);
        scan();
        renderList();
        setStatus(`Page ${currentPage} · found ${mp3List.length} MP3`, 'loading');

        // 2. 下载本页(跳过已下载的)
        let newCount = 0;
        for (const item of mp3List) {
            if (state.downloaded.includes(item.url)) continue;
            setStatus(`Page ${currentPage} · downloading ${cleanName(item.name)}`, 'loading');
            await downloadOne(item);
            state.downloaded.push(item.url);
            saveState(state);
            newCount++;
            await sleep(800);
        }
        setStatus(`Page ${currentPage} · downloaded ${newCount} new MP3`, 'success');

        // 3. 找下一页
        await sleep(CFG.betweenPagesDelay);   // 给浏览器时间开始下载
        const next = findNextPage();

        if (!next) {
            setStatus(`Done · last page reached. Total ${state.downloaded.length} MP3 downloaded.`, 'success');
            state.active = false;
            saveState(state);
            isRunning = false;
            updateButtons();
            return;
        }

        if (state.visited.includes(next)) {
            setStatus(`Stopped · next page already visited (loop detected).`, 'error');
            state.active = false;
            saveState(state);
            isRunning = false;
            updateButtons();
            return;
        }

        if (state.page >= CFG.maxPages) {
            setStatus(`Stopped · max pages (${CFG.maxPages}) reached.`, 'error');
            state.active = false;
            saveState(state);
            return;
        }

        // 4. 跳转
        state.page += 1;
        state.visited.push(next);
        saveState(state);
        setStatus(`Page ${currentPage} done · going to page ${state.page}...`, 'loading');
        await sleep(1000);
        location.href = next;
    }

    // ============ UI ============
    let panel, listEl, statusEl, countEl, btnAuto, btnStop, btnResume, btnClear;

    function buildPanel() {
        panel = document.createElement('div');
        panel.id = 'osho-ap';
        panel.innerHTML = `
            <style>
                #osho-ap{position:fixed;top:16px;right:16px;width:460px;max-width:calc(100vw - 32px);z-index:999999;font-family:'SF Mono','Fira Code',Consolas,monospace;font-size:12px;color:#e0d8c8;background:#12100c;border:1px solid #2a2418;border-radius:8px;box-shadow:0 8px 32px rgba(0,0,0,.7),0 0 0 1px rgba(201,169,97,.1);overflow:hidden}
                #osho-ap .ap-head{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;background:linear-gradient(180deg,#1a1510,#12100c);border-bottom:1px solid #2a2418;cursor:move;user-select:none}
                #osho-ap .ap-title{font-size:12px;font-weight:700;letter-spacing:.08em;color:#c9a961;text-shadow:0 0 8px rgba(201,169,97,.3)}
                #osho-ap .ap-collapse{background:transparent;border:none;color:#6a5e48;font-size:16px;cursor:pointer;padding:0 4px;line-height:1}
                #osho-ap .ap-collapse:hover{color:#c9a961}
                #osho-ap .ap-body{padding:12px 14px;max-height:75vh;overflow-y:auto}
                #osho-ap.ap-collapsed .ap-body{display:none}
                #osho-ap .ap-row{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}
                #osho-ap button{background:#8b6f3a;color:#0a0806;border:none;border-radius:4px;padding:6px 12px;font:inherit;font-size:11px;font-weight:700;cursor:pointer;letter-spacing:.04em;transition:.15s;white-space:nowrap}
                #osho-ap button:hover:not(:disabled){background:#c9a961;box-shadow:0 0 10px rgba(201,169,97,.4)}
                #osho-ap button:disabled{opacity:.4;cursor:not-allowed}
                #osho-ap button.ap-outline{background:transparent;border:1px solid #2a2418;color:#e0d8c8}
                #osho-ap button.ap-outline:hover:not(:disabled){border-color:#c9a961;background:#1a1510;box-shadow:none}
                #osho-ap button.ap-danger{background:#7a3030;color:#fff}
                #osho-ap button.ap-danger:hover:not(:disabled){background:#c94e4e}
                #osho-ap button.ap-green{background:#2e6b3e;color:#fff}
                #osho-ap button.ap-green:hover:not(:disabled){background:#3d8a52}
                #osho-ap .ap-status{font-size:11px;color:#6a5e48;margin-bottom:8px;min-height:16px;display:flex;align-items:center;gap:6px}
                #osho-ap .ap-status.loading::before{content:'';width:10px;height:10px;border:2px solid #2a2418;border-top-color:#c9a961;border-radius:50%;animation:ap-spin .7s linear infinite;flex-shrink:0}
                @keyframes ap-spin{to{transform:rotate(360deg)}}
                #osho-ap .ap-status.success{color:#6fbf73}
                #osho-ap .ap-status.error{color:#c94e4e}
                #osho-ap .ap-badge{display:inline-block;background:#2a2418;color:#c9a961;font-size:10px;font-weight:700;padding:2px 8px;border-radius:10px;margin-left:6px}
                #osho-ap .ap-list{max-height:280px;overflow-y:auto;background:#080604;border:1px solid #2a2418;border-radius:4px}
                #osho-ap .ap-list::-webkit-scrollbar{width:5px}
                #osho-ap .ap-list::-webkit-scrollbar-thumb{background:#2a2418;border-radius:3px}
                #osho-ap .ap-item{display:flex;align-items:center;gap:8px;padding:6px 10px;border-bottom:1px solid #14110a;font-size:11px}
                #osho-ap .ap-item:last-child{border-bottom:none}
                #osho-ap .ap-item:hover{background:#0f0d08}
                #osho-ap .ap-idx{color:#4a4238;font-size:10px;min-width:22px;text-align:right}
                #osho-ap .ap-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#e0d8c8}
                #osho-ap .ap-item button{padding:3px 8px;font-size:10px;font-weight:600}
                #osho-ap .ap-empty{padding:20px;text-align:center;color:#6a5e48;font-size:11px}
                #osho-ap .ap-info{margin-top:8px;font-size:10px;color:#6a5e48;line-height:1.6}
                #osho-ap .ap-info b{color:#c9a961;font-weight:600}
            </style>
            <div class="ap-head" id="ap-drag">
                <span class="ap-title">OSHO · AUTO PAGINATE</span>
                <button class="ap-collapse" id="ap-collapse">−</button>
            </div>
            <div class="ap-body">
                <div class="ap-status" id="ap-status">Ready</div>
                <div class="ap-row">
                    <button id="ap-start" class="ap-green">▶ Start Auto Paginate</button>
                    <button id="ap-stop" class="ap-danger" disabled>⏹ Stop</button>
                </div>
                <div class="ap-row">
                    <button id="ap-scan" class="ap-outline">🔄 Scan This Page</button>
                    <button id="ap-copy" class="ap-outline">📋 Copy URLs</button>
                    <button id="ap-reset" class="ap-outline">🗑 Reset State</button>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;">
                    <span style="font-size:10px;color:#6a5e48;text-transform:uppercase;letter-spacing:.08em;">This page</span>
                    <span class="ap-badge" id="ap-count">0</span>
                </div>
                <div class="ap-list" id="ap-list">
                    <div class="ap-empty">Click "Scan This Page" to extract MP3s.</div>
                </div>
                <div class="ap-info" id="ap-info"></div>
            </div>
        `;
        document.body.appendChild(panel);

        listEl = panel.querySelector('#ap-list');
        statusEl = panel.querySelector('#ap-status');
        countEl = panel.querySelector('#ap-count');
        btnAuto = panel.querySelector('#ap-start');
        btnStop = panel.querySelector('#ap-stop');
        btnResume = panel.querySelector('#ap-start');
        btnClear = panel.querySelector('#ap-reset');

        // collapse
        panel.querySelector('#ap-collapse').addEventListener('click', () => {
            panel.classList.toggle('ap-collapsed');
            panel.querySelector('#ap-collapse').textContent = panel.classList.contains('ap-collapsed') ? '+' : '−';
        });

        makeDraggable(panel, panel.querySelector('#ap-drag'));

        btnAuto.addEventListener('click', () => {
            if (!state || !state.active) {
                if (!confirm('Start auto-paginate?\n\nThis will:\n1. Download MP3s on this page\n2. Click "Next" automatically\n3. Repeat until last page\n\nBrowser may ask to allow multiple downloads.')) return;
                state = { active: true, page: 1, downloaded: [], visited: [location.href] };
                saveState(state);
            }
            runAutoPaginate();
        });

        btnStop.addEventListener('click', () => {
            isRunning = false;
            if (state) { state.active = false; saveState(state); }
            setStatus('Stopped by user', 'error');
            updateButtons();
        });

        panel.querySelector('#ap-scan').addEventListener('click', () => {
            scan();
            renderList();
            setStatus(`Scanned · ${mp3List.length} MP3 on this page`, mp3List.length ? 'success' : 'error');
        });

        panel.querySelector('#ap-copy').addEventListener('click', () => {
            if (mp3List.length === 0) { setStatus('Nothing to copy', 'error'); return; }
            const txt = mp3List.map(i => i.url).join('\n');
            navigator.clipboard.writeText(txt).then(() => setStatus(`Copied ${mp3List.length} URLs`, 'success'));
        });

        btnClear.addEventListener('click', () => {
            if (!confirm('Reset state? Downloaded list and page counter will be cleared.')) return;
            clearState();
            state = null;
            setStatus('State cleared', 'success');
            updateInfo();
        });

        listEl.addEventListener('click', e => {
            const btn = e.target.closest('button[data-act]');
            if (!btn) return;
            const idx = parseInt(btn.dataset.idx);
            const item = mp3List[idx];
            if (!item) return;
            if (btn.dataset.act === 'dl') {
                downloadOne(item).then(() => setStatus(`⬇ ${cleanName(item.name)}`, 'success'));
            } else if (btn.dataset.act === 'copy') {
                navigator.clipboard.writeText(item.url).then(() => {
                    const o = btn.textContent; btn.textContent = '✓';
                    setTimeout(() => btn.textContent = o, 1000);
                });
            }
        });

        updateInfo();
    }

    function renderList() {
        countEl.textContent = mp3List.length;
        if (mp3List.length === 0) {
            listEl.innerHTML = '<div class="ap-empty">No MP3 found on this page.</div>';
            return;
        }
        const frag = document.createDocumentFragment();
        mp3List.forEach((item, i) => {
            const div = document.createElement('div');
            div.className = 'ap-item';
            div.innerHTML = `
                <span class="ap-idx">${String(i + 1).padStart(2, '0')}</span>
                <span class="ap-name" title="${esc(item.url)}">${esc(cleanName(item.name))}</span>
                <button data-act="copy" data-idx="${i}">Copy</button>
                <button data-act="dl" data-idx="${i}">DL</button>
            `;
            frag.appendChild(div);
        });
        listEl.innerHTML = '';
        listEl.appendChild(frag);
    }

    function setStatus(msg, type = '') {
        statusEl.textContent = msg;
        statusEl.className = 'ap-status ' + type;
    }

    function updateButtons() {
        btnAuto.disabled = isRunning;
        btnStop.disabled = !isRunning;
    }

    function updateInfo() {
        const info = document.getElementById('ap-info');
        if (!info) return;
        if (!state) {
            info.innerHTML = 'Auto-paginate: <b>not started</b>. Click "Start Auto Paginate".';
            return;
        }
        if (state.active) {
            info.innerHTML = `Auto-paginate: <b>active</b> · page <b>${state.page}</b> · <b>${state.downloaded.length}</b> MP3 downloaded so far.`;
        } else {
            info.innerHTML = `Auto-paginate: <b>finished</b> · ${state.page} pages · <b>${state.downloaded.length}</b> MP3 total. Click "Reset State" to start over.`;
        }
    }

    function makeDraggable(el, handle) {
        let sx = 0, sy = 0, ox = 0, oy = 0, d = false;
        handle.addEventListener('mousedown', e => {
            if (e.target.tagName === 'BUTTON') return;
            d = true; sx = e.clientX; sy = e.clientY;
            const r = el.getBoundingClientRect(); ox = r.left; oy = r.top;
            e.preventDefault();
        });
        document.addEventListener('mousemove', e => {
            if (!d) return;
            el.style.left = (ox + e.clientX - sx) + 'px';
            el.style.top = (oy + e.clientY - sy) + 'px';
            el.style.right = 'auto';
        });
        document.addEventListener('mouseup', () => { d = false; });
    }

    // ============ INIT ============
    function init() {
        buildPanel();
        updateInfo();

        // 每次页面加载后自动扫描
        setTimeout(() => {
            scan();
            renderList();

            // 如果处于自动模式,继续跑
            if (state && state.active) {
                setStatus(`Resuming auto-paginate · page ${state.page}`, 'loading');
                runAutoPaginate();
            } else if (mp3List.length > 0) {
                setStatus(`Found ${mp3List.length} MP3 on this page`, 'success');
            } else {
                setStatus('No MP3 on this page', 'error');
            }
        }, CFG.autoScanDelay);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();