{"id":"4LXf4tPLpX","url":"https://pastebin.ca/4LXf4tPLpX","raw_url":"https://raw.anybin.ca/4LXf4tPLpX","visibility":"public","access":"public","created_at":1795882042989,"expires_at":1796486842989,"fetch_limit":null,"fetches_used":0,"reads_remaining":null,"size_bytes":19911,"syntax_hint":null,"title":null,"filename":null,"change_note":null,"cipher":null,"cipher_meta":null,"parent_id":null,"root_id":"4LXf4tPLpX","version":1,"owner_id":null,"recipient_id":null,"body":"// ==UserScript==\n// @name         OSHO World · Auto Paginate Downloader\n// @namespace    https://oshoworld.com/\n// @version      3.0\n// @description  Auto-download MP3s page by page. Clicks \"Next\" automatically until the last page.\n// @author       BROK\n// @match        https://oshoworld.com/*\n// @match        https://www.oshoworld.com/*\n// @grant        GM_download\n// @run-at       document-idle\n// ==/UserScript==\n\n(function () {\n    'use strict';\n\n    const CFG = {\n        autoScanDelay: 1000,\n        betweenPagesDelay: 4000,   // 下载触发后等多久再跳转\n        maxPages: 200,             // 安全上限\n        storageKey: 'osho_autopaginate_state'\n    };\n\n    // ============ STATE (跨页面) ============\n    function loadState() {\n        try {\n            const raw = sessionStorage.getItem(CFG.storageKey);\n            return raw ? JSON.parse(raw) : null;\n        } catch (e) { return null; }\n    }\n    function saveState(s) {\n        sessionStorage.setItem(CFG.storageKey, JSON.stringify(s));\n    }\n    function clearState() {\n        sessionStorage.removeItem(CFG.storageKey);\n    }\n\n    let state = loadState();   // null = 未启动；{active:true, page:1, downloaded:[], visited:[]}\n    let isRunning = false;\n    let mp3List = [];\n\n    // ============ HELPERS ============\n    const sleep = ms => new Promise(r => setTimeout(r, ms));\n    const esc = t => { const d = document.createElement('div'); d.appendChild(document.createTextNode(String(t))); return d.innerHTML; };\n\n    function filenameFromUrl(url) {\n        try {\n            const u = new URL(url, location.href);\n            return decodeURIComponent(u.pathname.split('/').pop() || 'audio.mp3');\n        } catch (e) { return 'audio.mp3'; }\n    }\n    function cleanName(f) {\n        return f.replace(/\\.mp3$/i, '').replace(/[_-]+/g, ' ').replace(/\\s+/g, ' ').trim();\n    }\n\n    // ============ SCAN ============\n    function scan() {\n        const found = new Set();\n        document.querySelectorAll('a[href]').forEach(a => {\n            const h = a.href;\n            if (/\\.mp3(\\?|$)/i.test(h)) found.add(h);\n        });\n        document.querySelectorAll('audio[src], audio source[src]').forEach(el => {\n            const s = el.src || el.getAttribute('src');\n            if (s && /\\.mp3(\\?|$)/i.test(s)) found.add(new URL(s, location.href).href);\n        });\n        // 裸 URL in HTML\n        const html = document.documentElement.innerHTML;\n        const re = /https?:\\/\\/[^\\s\"'<>()\\\\]+?\\.mp3(?:\\?[^\\s\"'<>()\\\\]*)?/gi;\n        let m;\n        while ((m = re.exec(html)) !== null) found.add(m[0].replace(/\\\\\\//g, '/'));\n        // 相对路径\n        const relRe = /[\"']([^\"']*?\\/wp-content\\/uploads\\/[^\"']*?\\.mp3)[\"']/gi;\n        while ((m = relRe.exec(html)) !== null) {\n            try { found.add(new URL(m[1], location.href).href); } catch (e) {}\n        }\n        mp3List = Array.from(found).sort().map(url => ({ url, name: filenameFromUrl(url) }));\n        return mp3List;\n    }\n\n    // ============ NEXT PAGE DETECTION ============\n    function findNextPage() {\n        // 多种策略，按优先级\n        const candidates = [\n            // rel=next\n            ...document.querySelectorAll('a[rel=\"next\"]'),\n            // 常见类名\n            ...document.querySelectorAll('a.next, a.next-page, a.pagination-next, .pagination a:last-child, .nav-next a'),\n            // 文字匹配\n            ...Array.from(document.querySelectorAll('a')).filter(a => {\n                const t = (a.textContent || '').trim().toLowerCase();\n                const t2 = (a.getAttribute('aria-label') || '').toLowerCase();\n                const t3 = (a.getAttribute('title') || '').toLowerCase();\n                return /^(next|next page|next →|→|›|»|下一页|下一頁)$/.test(t) ||\n                       /next/.test(t2) || /next/.test(t3);\n            })\n        ];\n\n        for (const a of candidates) {\n            const href = a.href;\n            if (!href) continue;\n            if (!href.startsWith(location.origin)) continue;      // 同站\n            if (href === location.href) continue;                 // 不是自己\n            if (/#/.test(href)) continue;                         // 跳过锚点\n            // 避免误判\"首页\"等导航链接\n            const path = new URL(href).pathname;\n            if (path === '/' || path === '') continue;\n            return href;\n        }\n        return null;\n    }\n\n    // ============ DOWNLOAD ============\n    function downloadOne(item) {\n        return new Promise(resolve => {\n            try {\n                if (typeof GM_download === 'function') {\n                    GM_download({\n                        url: item.url,\n                        name: item.name,\n                        onload: () => resolve(true),\n                        onerror: () => { fallbackAnchor(item); resolve(false); },\n                        ontimeout: () => { fallbackAnchor(item); resolve(false); }\n                    });\n                } else {\n                    fallbackAnchor(item);\n                    resolve(true);\n                }\n            } catch (e) { fallbackAnchor(item); resolve(false); }\n        });\n    }\n    function fallbackAnchor(item) {\n        const a = document.createElement('a');\n        a.href = item.url; a.download = item.name;\n        a.style.display = 'none';\n        document.body.appendChild(a); a.click();\n        setTimeout(() => a.remove(), 100);\n    }\n\n    // ============ AUTO PAGINATE ============\n    async function runAutoPaginate() {\n        if (!state) {\n            state = { active: true, page: 1, downloaded: [], visited: [location.href] };\n            saveState(state);\n            console.log('[AutoPaginate] started');\n        }\n        isRunning = true;\n        updateButtons();\n\n        const currentPage = state.page;\n        setStatus(`Page ${currentPage} · scanning...`, 'loading');\n\n        // 1. 扫描\n        await sleep(300);\n        scan();\n        renderList();\n        setStatus(`Page ${currentPage} · found ${mp3List.length} MP3`, 'loading');\n\n        // 2. 下载本页（跳过已下载的）\n        let newCount = 0;\n        for (const item of mp3List) {\n            if (state.downloaded.includes(item.url)) continue;\n            setStatus(`Page ${currentPage} · downloading ${cleanName(item.name)}`, 'loading');\n            await downloadOne(item);\n            state.downloaded.push(item.url);\n            saveState(state);\n            newCount++;\n            await sleep(800);\n        }\n        setStatus(`Page ${currentPage} · downloaded ${newCount} new MP3`, 'success');\n\n        // 3. 找下一页\n        await sleep(CFG.betweenPagesDelay);   // 给浏览器时间开始下载\n        const next = findNextPage();\n\n        if (!next) {\n            setStatus(`Done · last page reached. Total ${state.downloaded.length} MP3 downloaded.`, 'success');\n            state.active = false;\n            saveState(state);\n            isRunning = false;\n            updateButtons();\n            return;\n        }\n\n        if (state.visited.includes(next)) {\n            setStatus(`Stopped · next page already visited (loop detected).`, 'error');\n            state.active = false;\n            saveState(state);\n            isRunning = false;\n            updateButtons();\n            return;\n        }\n\n        if (state.page >= CFG.maxPages) {\n            setStatus(`Stopped · max pages (${CFG.maxPages}) reached.`, 'error');\n            state.active = false;\n            saveState(state);\n            return;\n        }\n\n        // 4. 跳转\n        state.page += 1;\n        state.visited.push(next);\n        saveState(state);\n        setStatus(`Page ${currentPage} done · going to page ${state.page}...`, 'loading');\n        await sleep(1000);\n        location.href = next;\n    }\n\n    // ============ UI ============\n    let panel, listEl, statusEl, countEl, btnAuto, btnStop, btnResume, btnClear;\n\n    function buildPanel() {\n        panel = document.createElement('div');\n        panel.id = 'osho-ap';\n        panel.innerHTML = `\n            <style>\n                #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}\n                #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}\n                #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)}\n                #osho-ap .ap-collapse{background:transparent;border:none;color:#6a5e48;font-size:16px;cursor:pointer;padding:0 4px;line-height:1}\n                #osho-ap .ap-collapse:hover{color:#c9a961}\n                #osho-ap .ap-body{padding:12px 14px;max-height:75vh;overflow-y:auto}\n                #osho-ap.ap-collapsed .ap-body{display:none}\n                #osho-ap .ap-row{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}\n                #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}\n                #osho-ap button:hover:not(:disabled){background:#c9a961;box-shadow:0 0 10px rgba(201,169,97,.4)}\n                #osho-ap button:disabled{opacity:.4;cursor:not-allowed}\n                #osho-ap button.ap-outline{background:transparent;border:1px solid #2a2418;color:#e0d8c8}\n                #osho-ap button.ap-outline:hover:not(:disabled){border-color:#c9a961;background:#1a1510;box-shadow:none}\n                #osho-ap button.ap-danger{background:#7a3030;color:#fff}\n                #osho-ap button.ap-danger:hover:not(:disabled){background:#c94e4e}\n                #osho-ap button.ap-green{background:#2e6b3e;color:#fff}\n                #osho-ap button.ap-green:hover:not(:disabled){background:#3d8a52}\n                #osho-ap .ap-status{font-size:11px;color:#6a5e48;margin-bottom:8px;min-height:16px;display:flex;align-items:center;gap:6px}\n                #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}\n                @keyframes ap-spin{to{transform:rotate(360deg)}}\n                #osho-ap .ap-status.success{color:#6fbf73}\n                #osho-ap .ap-status.error{color:#c94e4e}\n                #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}\n                #osho-ap .ap-list{max-height:280px;overflow-y:auto;background:#080604;border:1px solid #2a2418;border-radius:4px}\n                #osho-ap .ap-list::-webkit-scrollbar{width:5px}\n                #osho-ap .ap-list::-webkit-scrollbar-thumb{background:#2a2418;border-radius:3px}\n                #osho-ap .ap-item{display:flex;align-items:center;gap:8px;padding:6px 10px;border-bottom:1px solid #14110a;font-size:11px}\n                #osho-ap .ap-item:last-child{border-bottom:none}\n                #osho-ap .ap-item:hover{background:#0f0d08}\n                #osho-ap .ap-idx{color:#4a4238;font-size:10px;min-width:22px;text-align:right}\n                #osho-ap .ap-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#e0d8c8}\n                #osho-ap .ap-item button{padding:3px 8px;font-size:10px;font-weight:600}\n                #osho-ap .ap-empty{padding:20px;text-align:center;color:#6a5e48;font-size:11px}\n                #osho-ap .ap-info{margin-top:8px;font-size:10px;color:#6a5e48;line-height:1.6}\n                #osho-ap .ap-info b{color:#c9a961;font-weight:600}\n            </style>\n            <div class=\"ap-head\" id=\"ap-drag\">\n                <span class=\"ap-title\">OSHO · AUTO PAGINATE</span>\n                <button class=\"ap-collapse\" id=\"ap-collapse\">−</button>\n            </div>\n            <div class=\"ap-body\">\n                <div class=\"ap-status\" id=\"ap-status\">Ready</div>\n                <div class=\"ap-row\">\n                    <button id=\"ap-start\" class=\"ap-green\">▶ Start Auto Paginate</button>\n                    <button id=\"ap-stop\" class=\"ap-danger\" disabled>⏹ Stop</button>\n                </div>\n                <div class=\"ap-row\">\n                    <button id=\"ap-scan\" class=\"ap-outline\">🔄 Scan This Page</button>\n                    <button id=\"ap-copy\" class=\"ap-outline\">📋 Copy URLs</button>\n                    <button id=\"ap-reset\" class=\"ap-outline\">🗑 Reset State</button>\n                </div>\n                <div style=\"display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;\">\n                    <span style=\"font-size:10px;color:#6a5e48;text-transform:uppercase;letter-spacing:.08em;\">This page</span>\n                    <span class=\"ap-badge\" id=\"ap-count\">0</span>\n                </div>\n                <div class=\"ap-list\" id=\"ap-list\">\n                    <div class=\"ap-empty\">Click \"Scan This Page\" to extract MP3s.</div>\n                </div>\n                <div class=\"ap-info\" id=\"ap-info\"></div>\n            </div>\n        `;\n        document.body.appendChild(panel);\n\n        listEl = panel.querySelector('#ap-list');\n        statusEl = panel.querySelector('#ap-status');\n        countEl = panel.querySelector('#ap-count');\n        btnAuto = panel.querySelector('#ap-start');\n        btnStop = panel.querySelector('#ap-stop');\n        btnResume = panel.querySelector('#ap-start');\n        btnClear = panel.querySelector('#ap-reset');\n\n        // collapse\n        panel.querySelector('#ap-collapse').addEventListener('click', () => {\n            panel.classList.toggle('ap-collapsed');\n            panel.querySelector('#ap-collapse').textContent = panel.classList.contains('ap-collapsed') ? '+' : '−';\n        });\n\n        makeDraggable(panel, panel.querySelector('#ap-drag'));\n\n        btnAuto.addEventListener('click', () => {\n            if (!state || !state.active) {\n                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;\n                state = { active: true, page: 1, downloaded: [], visited: [location.href] };\n                saveState(state);\n            }\n            runAutoPaginate();\n        });\n\n        btnStop.addEventListener('click', () => {\n            isRunning = false;\n            if (state) { state.active = false; saveState(state); }\n            setStatus('Stopped by user', 'error');\n            updateButtons();\n        });\n\n        panel.querySelector('#ap-scan').addEventListener('click', () => {\n            scan();\n            renderList();\n            setStatus(`Scanned · ${mp3List.length} MP3 on this page`, mp3List.length ? 'success' : 'error');\n        });\n\n        panel.querySelector('#ap-copy').addEventListener('click', () => {\n            if (mp3List.length === 0) { setStatus('Nothing to copy', 'error'); return; }\n            const txt = mp3List.map(i => i.url).join('\\n');\n            navigator.clipboard.writeText(txt).then(() => setStatus(`Copied ${mp3List.length} URLs`, 'success'));\n        });\n\n        btnClear.addEventListener('click', () => {\n            if (!confirm('Reset state? Downloaded list and page counter will be cleared.')) return;\n            clearState();\n            state = null;\n            setStatus('State cleared', 'success');\n            updateInfo();\n        });\n\n        listEl.addEventListener('click', e => {\n            const btn = e.target.closest('button[data-act]');\n            if (!btn) return;\n            const idx = parseInt(btn.dataset.idx);\n            const item = mp3List[idx];\n            if (!item) return;\n            if (btn.dataset.act === 'dl') {\n                downloadOne(item).then(() => setStatus(`⬇ ${cleanName(item.name)}`, 'success'));\n            } else if (btn.dataset.act === 'copy') {\n                navigator.clipboard.writeText(item.url).then(() => {\n                    const o = btn.textContent; btn.textContent = '✓';\n                    setTimeout(() => btn.textContent = o, 1000);\n                });\n            }\n        });\n\n        updateInfo();\n    }\n\n    function renderList() {\n        countEl.textContent = mp3List.length;\n        if (mp3List.length === 0) {\n            listEl.innerHTML = '<div class=\"ap-empty\">No MP3 found on this page.</div>';\n            return;\n        }\n        const frag = document.createDocumentFragment();\n        mp3List.forEach((item, i) => {\n            const div = document.createElement('div');\n            div.className = 'ap-item';\n            div.innerHTML = `\n                <span class=\"ap-idx\">${String(i + 1).padStart(2, '0')}</span>\n                <span class=\"ap-name\" title=\"${esc(item.url)}\">${esc(cleanName(item.name))}</span>\n                <button data-act=\"copy\" data-idx=\"${i}\">Copy</button>\n                <button data-act=\"dl\" data-idx=\"${i}\">DL</button>\n            `;\n            frag.appendChild(div);\n        });\n        listEl.innerHTML = '';\n        listEl.appendChild(frag);\n    }\n\n    function setStatus(msg, type = '') {\n        statusEl.textContent = msg;\n        statusEl.className = 'ap-status ' + type;\n    }\n\n    function updateButtons() {\n        btnAuto.disabled = isRunning;\n        btnStop.disabled = !isRunning;\n    }\n\n    function updateInfo() {\n        const info = document.getElementById('ap-info');\n        if (!info) return;\n        if (!state) {\n            info.innerHTML = 'Auto-paginate: <b>not started</b>. Click \"Start Auto Paginate\".';\n            return;\n        }\n        if (state.active) {\n            info.innerHTML = `Auto-paginate: <b>active</b> · page <b>${state.page}</b> · <b>${state.downloaded.length}</b> MP3 downloaded so far.`;\n        } else {\n            info.innerHTML = `Auto-paginate: <b>finished</b> · ${state.page} pages · <b>${state.downloaded.length}</b> MP3 total. Click \"Reset State\" to start over.`;\n        }\n    }\n\n    function makeDraggable(el, handle) {\n        let sx = 0, sy = 0, ox = 0, oy = 0, d = false;\n        handle.addEventListener('mousedown', e => {\n            if (e.target.tagName === 'BUTTON') return;\n            d = true; sx = e.clientX; sy = e.clientY;\n            const r = el.getBoundingClientRect(); ox = r.left; oy = r.top;\n            e.preventDefault();\n        });\n        document.addEventListener('mousemove', e => {\n            if (!d) return;\n            el.style.left = (ox + e.clientX - sx) + 'px';\n            el.style.top = (oy + e.clientY - sy) + 'px';\n            el.style.right = 'auto';\n        });\n        document.addEventListener('mouseup', () => { d = false; });\n    }\n\n    // ============ INIT ============\n    function init() {\n        buildPanel();\n        updateInfo();\n\n        // 每次页面加载后自动扫描\n        setTimeout(() => {\n            scan();\n            renderList();\n\n            // 如果处于自动模式，继续跑\n            if (state && state.active) {\n                setStatus(`Resuming auto-paginate · page ${state.page}`, 'loading');\n                runAutoPaginate();\n            } else if (mp3List.length > 0) {\n                setStatus(`Found ${mp3List.length} MP3 on this page`, 'success');\n            } else {\n                setStatus('No MP3 on this page', 'error');\n            }\n        }, CFG.autoScanDelay);\n    }\n\n    if (document.readyState === 'loading') {\n        document.addEventListener('DOMContentLoaded', init);\n    } else {\n        init();\n    }\n\n})();"}