// ==UserScript== // @name OSHO World · Mass Media Grabber // @namespace https://oshoworld.com/ // @version 2.0 // @description Auto-scan MP3s, images and media on oshoworld.com. Batch download 1–100 files in one click. All-English UI. // @author BROK // @match https://oshoworld.com/* // @match https://www.oshoworld.com/* // @match http://oshoworld.com/* // @grant GM_download // @grant GM_xmlhttpRequest // @connect oshoworld.com // @connect www.oshoworld.com // @run-at document-idle // ==/UserScript== (function () { 'use strict'; // ============================================================ // CONFIG // ============================================================ const CONFIG = { batchDelayMin: 1200, batchDelayMax: 2800, autoScanDelay: 800, maxBatch: 100, minBatch: 1, reclassifyOnMutation: true }; // ============================================================ // STATE // ============================================================ let items = []; // {url, name, type} type: mp3 | img | audio | video | other let filteredItems = []; // filtered view let filterType = 'all'; let searchText = ''; let isDownloading = false; let stopFlag = false; let panelCollapsed = false; let nextIndex = 0; // ============================================================ // HELPERS // ============================================================ const sleep = ms => new Promise(r => setTimeout(r, ms)); const randInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; function 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); let f = u.pathname.split('/').pop() || ''; f = decodeURIComponent(f); return f || 'file.bin'; } catch (e) { return 'file.bin'; } } function cleanName(filename) { return filename .replace(/\.[a-z0-9]{2,5}$/i, '') .replace(/[_-]+/g, ' ') .replace(/\s+/g, ' ') .trim(); } function classify(url) { const lower = url.toLowerCase().split('?')[0]; if (/\.(mp3|m4a|ogg|wav|flac|aac)$/i.test(lower)) return 'mp3'; if (/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico|tiff?)$/i.test(lower)) return 'img'; if (/\.(mp4|webm|mov|m4v|ogv|avi|mkv)$/i.test(lower)) return 'video'; if (/\.(pdf|zip|rar|7z|docx?|xlsx?|epub|txt|csv)$/i.test(lower)) return 'other'; return 'other'; } function absolute(href, base) { try { return new URL(href, base || location.href).href; } catch (e) { return null; } } // ============================================================ // SCANNER // ============================================================ function scan() { const found = new Map(); // url -> type function add(url) { if (!url) return; if (!/^https?:/i.test(url)) return; if (url.startsWith('data:')) return; if (!found.has(url)) found.set(url, classify(url)); } // 1. Anchor hrefs document.querySelectorAll('a[href]').forEach(a => { add(absolute(a.getAttribute('href'), a.baseURI)); }); // 2. Media elements document.querySelectorAll('audio[src], audio source[src]').forEach(el => { add(absolute(el.getAttribute('src'), el.baseURI)); }); document.querySelectorAll('video[src], video source[src]').forEach(el => { add(absolute(el.getAttribute('src'), el.baseURI)); }); // 3. Images (skip tiny UI icons via data-src/srcset heuristic) document.querySelectorAll('img[src], img[data-src], img[data-original]').forEach(img => { const src = img.getAttribute('src') || img.getAttribute('data-src') || img.getAttribute('data-original'); if (!src) return; // Skip data: and svg placeholders if (src.startsWith('data:')) return; add(absolute(src, img.baseURI)); // srcset const srcset = img.getAttribute('srcset'); if (srcset) { srcset.split(',').forEach(part => { const u = part.trim().split(/\s+/)[0]; add(absolute(u, img.baseURI)); }); } }); // 4. Bare URLs inside HTML (script data, JSON, etc.) const html = document.documentElement.innerHTML; const mediaRe = /https?:\/\/[^\s"'<>()\\]+?\.(?:mp3|m4a|ogg|wav|flac|aac|jpg|jpeg|png|gif|webp|mp4|webm|mov)(?:\?[^\s"'<>()\\]*)?/gi; let m; while ((m = mediaRe.exec(html)) !== null) { add(m[0].replace(/\\\//g, '/')); } // 5. Relative /wp-content/uploads/ paths const relRe = /["']([^"']*?\/wp-content\/uploads\/[^"']+?\.(?:mp3|m4a|ogg|wav|flac|jpg|jpeg|png|gif|webp|mp4|webm|mov))["']/gi; while ((m = relRe.exec(html)) !== null) { add(absolute(m[1], location.href)); } // Build list items = Array.from(found.entries()) .map(([url, type]) => ({ url, name: filenameFromUrl(url), type })) .sort((a, b) => { const order = { mp3: 0, audio: 1, video: 2, img: 3, other: 4 }; const d = (order[a.type] || 9) - (order[b.type] || 9); if (d !== 0) return d; return a.name.localeCompare(b.name); }); return items; } // ============================================================ // DOWNLOAD // ============================================================ function downloadOne(item) { return new Promise(resolve => { try { // Prefer GM_download when available (handles redirects better) if (typeof GM_download === 'function') { GM_download({ url: item.url, name: item.name, onload: () => resolve(true), onerror: (err) => { console.warn('GM_download failed, falling back to ', item.url, err); 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.rel = 'noopener'; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(() => a.remove(), 100); } // ============================================================ // BATCH DOWNLOAD // ============================================================ async function batchDownload() { if (isDownloading) return; // Recompute filtered view in case user changed filters applyFilter(); if (filteredItems.length === 0) { setStatus('No items to download. Scan first or clear filters.', 'error'); return; } // Read batch count from input let requested = parseInt($('#omg-batch').value) || filteredItems.length; if (requested < CONFIG.minBatch) requested = CONFIG.minBatch; if (requested > CONFIG.maxBatch) requested = CONFIG.maxBatch; const toDownload = filteredItems.slice(0, requested); const ok = confirm( `Mass download\n\n` + `Files: ${toDownload.length}\n` + `Delay between files: ${CONFIG.batchDelayMin}–${CONFIG.batchDelayMax} ms\n\n` + `Your browser may ask "Allow multiple downloads?" — click Allow.\n\n` + `Start?` ); if (!ok) return; isDownloading = true; stopFlag = false; updateButtonState(); let succeeded = 0; let failed = 0; for (let i = 0; i < toDownload.length; i++) { if (stopFlag) break; const item = toDownload[i]; setStatus(`Downloading ${i + 1}/${toDownload.length} · ${cleanName(item.name)}`, 'loading'); updateProgress(i + 1, toDownload.length); const result = await downloadOne(item); if (result) succeeded++; else failed++; if (i < toDownload.length - 1 && !stopFlag) { await sleep(randInt(CONFIG.batchDelayMin, CONFIG.batchDelayMax)); } } isDownloading = false; updateProgress(0, 0); updateButtonState(); if (stopFlag) { setStatus(`Stopped · ${succeeded}/${toDownload.length} triggered`, 'error'); } else { setStatus(`Done · ${succeeded}/${toDownload.length} triggered${failed ? ' · ' + failed + ' failed' : ''}`, 'success'); } } // ============================================================ // UI // ============================================================ let $, listEl, statusEl, countEl, progressEl, progressBar, batchEl; function buildPanel() { const p = document.createElement('div'); p.id = 'osho-mg'; p.innerHTML = `
OSHO · MASS MEDIA GRABBER
Ready
Batch size: / max 100 Search:
Files 0
Click "Rescan" to extract media files.
`; document.body.appendChild(p); // Cache refs $ = sel => p.querySelector(sel); listEl = $('#omg-list'); statusEl = $('#omg-status'); countEl = $('#omg-count'); progressEl = $('#omg-progress'); progressBar = $('#omg-progress-bar'); batchEl = $('#omg-batch'); // Events $('#omg-collapse').addEventListener('click', () => { panelCollapsed = !panelCollapsed; p.classList.toggle('mg-collapsed', panelCollapsed); $('#omg-collapse').textContent = panelCollapsed ? '+' : '−'; }); makeDraggable(p, $('#omg-drag')); $('#omg-scan').addEventListener('click', () => { scan(); applyFilter(); setStatus(`Rescan complete · ${items.length} items found`, items.length ? 'success' : 'error'); }); $('#omg-download').addEventListener('click', batchDownload); $('#omg-stop').addEventListener('click', () => { stopFlag = true; setStatus('Stopping...', 'loading'); }); $('#omg-copy').addEventListener('click', copyUrls); $('#omg-selectall').addEventListener('click', () => { listEl.querySelectorAll('input[type=checkbox]').forEach(cb => cb.checked = true); }); $('#omg-deselect').addEventListener('click', () => { listEl.querySelectorAll('input[type=checkbox]').forEach(cb => cb.checked = false); }); // Filter tabs p.querySelectorAll('.mg-tab').forEach(tab => { tab.addEventListener('click', () => { p.querySelectorAll('.mg-tab').forEach(t => t.classList.remove('on')); tab.classList.add('on'); filterType = tab.dataset.type; applyFilter(); }); }); // Search $('#omg-search').addEventListener('input', e => { searchText = e.target.value.trim().toLowerCase(); applyFilter(); }); // Batch input clamp batchEl.addEventListener('change', () => { let v = parseInt(batchEl.value) || 20; if (v < 1) v = 1; if (v > 100) v = 100; batchEl.value = v; }); // List delegation listEl.addEventListener('click', e => { const btn = e.target.closest('button[data-act]'); if (!btn) return; const idx = parseInt(btn.dataset.idx); const item = filteredItems[idx]; if (!item) return; if (btn.dataset.act === 'dl') { setStatus(`⬇ ${cleanName(item.name)}`, 'loading'); downloadOne(item).then(() => { setStatus(`✅ ${cleanName(item.name)}`, 'success'); }); } else if (btn.dataset.act === 'copy') { navigator.clipboard.writeText(item.url).then(() => { const orig = btn.textContent; btn.textContent = '✓'; setTimeout(() => btn.textContent = orig, 1000); }); } }); } function applyFilter() { filteredItems = items.filter(it => { if (filterType !== 'all' && it.type !== filterType) return false; if (searchText && !it.name.toLowerCase().includes(searchText)) return false; return true; }); renderList(); renderStats(); } function renderList() { countEl.textContent = filteredItems.length; if (filteredItems.length === 0) { listEl.innerHTML = '
No items match your filter.
'; return; } const frag = document.createDocumentFragment(); filteredItems.forEach((item, i) => { const typeClass = { mp3: 'mg-type-mp3', audio: 'mg-type-audio', video: 'mg-type-video', img: 'mg-type-img', other: 'mg-type-other' }[item.type] || 'mg-type-other'; const row = document.createElement('div'); row.className = 'mg-item'; row.innerHTML = ` ${String(i + 1).padStart(2, '0')} ${item.type} ${esc(cleanName(item.name))} `; frag.appendChild(row); }); listEl.innerHTML = ''; listEl.appendChild(frag); } function renderStats() { const counts = { mp3: 0, img: 0, video: 0, other: 0 }; items.forEach(it => { const k = ['mp3', 'audio'].includes(it.type) ? 'mp3' : (it.type === 'img' ? 'img' : (it.type === 'video' ? 'video' : 'other')); counts[k]++; }); const el = document.getElementById('omg-stats'); if (el) el.textContent = `MP3:${counts.mp3} · IMG:${counts.img} · VID:${counts.video} · OTHER:${counts.other}`; } function setStatus(msg, type = '') { statusEl.textContent = msg; statusEl.className = 'mg-status ' + type; } function updateButtonState() { document.getElementById('omg-download').disabled = isDownloading; document.getElementById('omg-scan').disabled = isDownloading; document.getElementById('omg-stop').disabled = !isDownloading; } function updateProgress(current, total) { if (total === 0) { progressEl.classList.remove('active'); progressBar.style.width = '0%'; return; } progressEl.classList.add('active'); progressBar.style.width = Math.round((current / total) * 100) + '%'; } function copyUrls() { if (filteredItems.length === 0) { setStatus('No URLs to copy', 'error'); return; } const text = filteredItems.map(i => i.url).join('\n'); const done = () => setStatus(`Copied ${filteredItems.length} URLs`, 'success'); navigator.clipboard.writeText(text).then(done).catch(() => { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove(); done(); }); } function makeDraggable(el, handle) { let sx = 0, sy = 0, ox = 0, oy = 0, dragging = false; handle.addEventListener('mousedown', e => { if (e.target.tagName === 'BUTTON') return; dragging = true; sx = e.clientX; sy = e.clientY; const r = el.getBoundingClientRect(); ox = r.left; oy = r.top; el.style.transition = 'none'; e.preventDefault(); }); document.addEventListener('mousemove', e => { if (!dragging) return; el.style.left = (ox + e.clientX - sx) + 'px'; el.style.top = (oy + e.clientY - sy) + 'px'; el.style.right = 'auto'; }); document.addEventListener('mouseup', () => { dragging = false; el.style.transition = ''; }); } // ============================================================ // INIT // ============================================================ function init() { buildPanel(); setTimeout(() => { scan(); applyFilter(); if (items.length > 0) { setStatus(`Auto-scan · ${items.length} media items found`, 'success'); } else { setStatus('Auto-scan found nothing. Click Rescan after content loads.', 'error'); } }, CONFIG.autoScanDelay); // MutationObserver with debounce let timer = null; const obs = new MutationObserver(() => { if (!CONFIG.reclassifyOnMutation) return; if (timer) clearTimeout(timer); timer = setTimeout(() => { const before = items.length; scan(); if (items.length !== before) { applyFilter(); setStatus(`Content updated · ${items.length} items`, 'success'); } }, 1500); }); obs.observe(document.body, { childList: true, subtree: true }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();