/**  * omdown Media Scraper & Downloader  * Target: https://www.omdown.site (All-in-One Downloader for 27 platforms)  * Engine: Node.js (v18+ native fetch, node:stream, node:fs / zero external npm dependencies)  */ const fs = require('node:fs'); const path = require('node:path'); const { pipeline } = require('node:stream/promises'); const { Readable } = require('node:stream'); // Service Endpoints & Action Constants const BASE_URL = 'https://www.omdown.site'; const ACTION_RESOLVE = '70bdf567b035b52eef5ff3bc5200fe2a46704cd1e2'; const ACTION_STATS = '00d321fb7b44573a9a7c1f02669fb9eb52a93b906c'; const DEPLOYMENT_ID = '7_h0WIF01Ag40WT7Ho6MK'; const ROUTER_TREE = JSON.stringify([   '',   {     children: [       ['locale', 'id', 'd', ['api']],       { children: ['__PAGE__', {}, '$undefined', '$undefined', 4096] },       '$undefined',       '$undefined',       4112     ]   },   '$undefined',   '$undefined',   4112 ]); // Browser Simulation Headers const DEFAULT_USER_AGENT =   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'; // 27 Platform Host Heuristics const PLATFORM_RULES = [   [/(?:^|\.)shortdrama\.tiktok\.com$/i, 'PineDrama'],   [/(?:^|\.)tiktok\.com$/i, 'TikTok'],   [/(?:^|\.)(?:douyin\.com|iesdouyin\.com)$/i, 'Douyin'],   [/(?:^|\.)(?:kuaishou\.com|kwai\.com)$/i, 'Kuaishou'],   [/(?:^|\.)(?:snackvideo\.com|sck\.io)$/i, 'SnackVideo'],   [/(?:^|\.)(?:xiaohongshu\.com|rednote\.com|xhslink\.com)$/i, 'RedNote'],   [/(?:^|\.)(?:youtu\.be|youtube\.com)$/i, 'YouTube'],   [/(?:^|\.)(?:instagram\.com|instagr\.am|ig\.me)$/i, 'Instagram'],   [/(?:^|\.)(?:twitter\.com|x\.com|t\.co)$/i, 'X'],   [/(?:^|\.)(?:facebook\.com|fb\.watch|fb\.com)$/i, 'Facebook'],   [/(?:^|\.)threads\.(?:net|com)$/i, 'Threads'],   [/(?:^|\.)(?:bsky\.app|bsky\.social)$/i, 'Bluesky'],   [/(?:^|\.)(?:reddit\.com|redd\.it)$/i, 'Reddit'],   [/(?:^|\.)capcut\.com$/i, 'CapCut'],   [/(?:^|\.)snapchat\.com$/i, 'Snapchat'],   [/(?:^|\.)twitch\.tv$/i, 'Twitch'],   [/(?:^|\.)(?:bilibili\.com|bilibili\.tv|b23\.tv|bili\.im)$/i, 'Bilibili'],   [/(?:^|\.)(?:dailymotion\.com|dai\.ly)$/i, 'Dailymotion'],   [/(?:^|\.)lahelu\.com$/i, 'Lahelu'],   [/(?:^|\.)(?:spotify\.com|spoti\.fi)$/i, 'Spotify'],   [/(?:^|\.)soundcloud\.com$/i, 'SoundCloud'],   [/(?:^|\.)(?:music\.apple\.com|apple\.co)$/i, 'Apple Music'],   [/(?:^|\.)(?:pinterest\.(?:com|co\.[a-z]{2}|[a-z]{2,3})|pin\.it)$/i, 'Pinterest'],   [/(?:^|\.)deviantart\.com$/i, 'DeviantArt'],   [/(?:^|\.)pixiv\.net$/i, 'Pixiv'],   [/(?:^|\.)mangadex\.org$/i, 'MangaDex'],   [/(?:^|\.)imgur\.com$/i, 'Imgur'] ]; /**  * Detects the target platform from a media URL.  * @param {string} inputUrl  * @returns {string} Platform name or 'Auto'  */ function detectPlatform(inputUrl) {   try {     const raw = inputUrl.trim();     const normalized = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;     const parsed = new URL(normalized);     for (const [pattern, name] of PLATFORM_RULES) {       if (pattern.test(parsed.hostname)) {         return name;       }     }   } catch {}   return 'Auto'; } /**  * Initializes a session and extracts the security cookies (om_sec, omdown_locale).  * @param {object} [options]  * @returns {Promise<{ cookieHeader: string, jar: Record }>}  */ async function initSession(options = {}) {   const ua = options.userAgent || DEFAULT_USER_AGENT;   const res = await fetch(`${BASE_URL}/id`, {     headers: {       'User-Agent': ua,       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',       'Accept-Language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7'     }   });   if (!res.ok) {     throw new Error(`Failed to initialize session: HTTP ${res.status} ${res.statusText}`);   }   const rawCookies = res.headers.getSetCookie ? res.headers.getSetCookie() : [res.headers.get('set-cookie')];   const jar = {};   for (const c of rawCookies) {     if (!c) continue;     const parts = c.split(',');     for (const p of parts) {       const match = p.trim().match(/^([^=;]+)=([^;]+)/);       if (match) {         const k = match[1].trim();         const v = match[2].trim();         const lower = k.toLowerCase();         if (!['path', 'expires', 'max-age', 'domain', 'samesite', 'secure', 'httponly'].includes(lower)) {           jar[k] = v;         }       }     }   }   if (!jar.om_sec) {     throw new Error('Missing om_sec security cookie from session handshake');   }   const cookieHeader = Object.entries(jar)     .map(([k, v]) => `${k}=${v}`)     .join('; ');   return { cookieHeader, jar }; } /**  * Parses React Flight (RSC) protocol chunks from the Server Action response.  * @param {string} text  * @returns {Record}  */ function parseFlightStream(text) {   const chunks = {};   let offset = 0;   while (offset < text.length) {     const colonIdx = text.indexOf(':', offset);     if (colonIdx === -1) break;     const id = text.slice(offset, colonIdx).trim();     // Check Flight chunk framing: T,     if (text[colonIdx + 1] === 'T') {       const commaIdx = text.indexOf(',', colonIdx + 2);       if (commaIdx === -1) break;       const hexLen = text.slice(colonIdx + 2, commaIdx);       const len = parseInt(hexLen, 16);       const dataStart = commaIdx + 1;       const data = text.slice(dataStart, dataStart + len);       chunks[id] = data;       offset = dataStart + len;       while (text[offset] === '\n' || text[offset] === '\r') offset++;     } else {       const newlineIdx = text.indexOf('\n', colonIdx + 1);       const data = newlineIdx === -1 ? text.slice(colonIdx + 1) : text.slice(colonIdx + 1, newlineIdx);       chunks[id] = data;       offset = newlineIdx === -1 ? text.length : newlineIdx + 1;     }   }   return chunks; } /**  * Fetches real-time download counter stats from omdown.  * @param {object} [options]  * @returns {Promise<{ success: boolean, totalDownloads: number }>}  */ async function getStats(options = {}) {   const { cookieHeader } = await initSession(options);   const ua = options.userAgent || DEFAULT_USER_AGENT;   const res = await fetch(`${BASE_URL}/id`, {     method: 'POST',     headers: {       'User-Agent': ua,       'Accept': 'text/x-component',       'Next-Action': ACTION_STATS,       'Content-Type': 'text/plain;charset=UTF-8',       'Cookie': cookieHeader,       'Origin': BASE_URL,       'Referer': `${BASE_URL}/id`,       'Next-Router-State-Tree': encodeURIComponent(ROUTER_TREE),       'x-deployment-id': DEPLOYMENT_ID,       'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',       'sec-ch-ua-mobile': '?0',       'sec-ch-ua-platform': '"Windows"',       'sec-fetch-dest': 'empty',       'sec-fetch-mode': 'cors',       'sec-fetch-site': 'same-origin'     },     body: JSON.stringify([])   });   const text = await res.text();   const chunks = parseFlightStream(text);   const resultJson = chunks['1'] || chunks['0'] || '{}';   try {     return JSON.parse(resultJson);   } catch {     return { success: false, raw: text };   } } /**  * Resolves media information, formats, and stream tokens for a given target URL.  * @param {string} targetUrl - URL of media (YouTube, TikTok, Instagram, X, Spotify, etc.)  * @param {object} [options]  * @param {string} [options.platform] - Target platform override  * @param {string} [options.locale='id'] - 'id' or 'en'  * @returns {Promise}  */ async function resolveMedia(targetUrl, options = {}) {   if (!targetUrl || typeof targetUrl !== 'string') {     throw new Error('Media URL cannot be empty');   }   const cleanUrl = targetUrl.trim();   const platform = options.platform || detectPlatform(cleanUrl);   const locale = options.locale || 'id';   const ua = options.userAgent || DEFAULT_USER_AGENT;   const { cookieHeader } = await initSession(options);   const res = await fetch(`${BASE_URL}/id`, {     method: 'POST',     headers: {       'User-Agent': ua,       'Accept': 'text/x-component',       'Next-Action': ACTION_RESOLVE,       'Content-Type': 'text/plain;charset=UTF-8',       'Cookie': cookieHeader,       'Origin': BASE_URL,       'Referer': `${BASE_URL}/${locale}`,       'Next-Router-State-Tree': encodeURIComponent(ROUTER_TREE),       'x-deployment-id': DEPLOYMENT_ID,       'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',       'sec-ch-ua-mobile': '?0',       'sec-ch-ua-platform': '"Windows"',       'sec-fetch-dest': 'empty',       'sec-fetch-mode': 'cors',       'sec-fetch-site': 'same-origin'     },     body: JSON.stringify([cleanUrl, platform, locale])   });   const rawFlight = await res.text();   // Handle immediate error payloads   if (rawFlight.includes('"success":false')) {     const errMatch = rawFlight.match(/"error":"([^"]+)"/);     throw new Error(errMatch ? errMatch[1] : 'Server returned resolution error');   }   const flightChunks = parseFlightStream(rawFlight);   // Extract core metadata via structured search   const titleMatch = rawFlight.match(/"title":"([^"]+)"/);   const authorMatch = rawFlight.match(/"author":"([^"]+)"/);   const durationMatch = rawFlight.match(/"duration":"([^"]+)"/);   const viewsMatch = rawFlight.match(/"views":"([^"]+)"/);   const likesMatch = rawFlight.match(/"likes":"([^"]+)"/);   const thumbMatch = rawFlight.match(/"thumbnailUrl":"([^"]+)"/);   // Extract formats array   const formatsMatch = rawFlight.match(/"formats":(\[.*?\]),"profile"/);   let rawFormats = [];   if (formatsMatch) {     try {       rawFormats = JSON.parse(formatsMatch[1]);     } catch {}   }   // Resolve indirect Flight references ($11, $12, etc.) to full stream paths   const formats = rawFormats.map(fmt => {     let streamPath = fmt.downloadUrl;     if (streamPath && streamPath.startsWith('$')) {       const refId = streamPath.slice(1);       streamPath = flightChunks[refId] || streamPath;     }     const absoluteStreamUrl =       streamPath && streamPath.startsWith('/') ? `${BASE_URL}${streamPath}` : streamPath;     return {       id: fmt.id,       label: fmt.label,       description: fmt.description,       kind: fmt.kind,       quality: fmt.quality || null,       ext: fmt.ext || (fmt.kind === 'audio' ? 'mp3' : 'mp4'),       hasWatermark: Boolean(fmt.hasWatermark),       jobKey: fmt.jobKey || null,       downloadUrl: absoluteStreamUrl     };   });   // Resolve cover thumbnail URL if available   let coverUrl = thumbMatch ? thumbMatch[1] : null;   if (coverUrl && coverUrl.startsWith('$')) {     const refId = coverUrl.slice(1);     coverUrl = flightChunks[refId] || coverUrl;   }   if (coverUrl && coverUrl.startsWith('/')) {     coverUrl = `${BASE_URL}${coverUrl}`;   }   return {     success: true,     platform,     targetUrl: cleanUrl,     title: titleMatch ? titleMatch[1] : '',     author: authorMatch ? authorMatch[1] : '',     duration: durationMatch ? durationMatch[1] : '',     views: viewsMatch ? viewsMatch[1] : '',     likes: likesMatch ? likesMatch[1] : '',     coverUrl,     formatsCount: formats.length,     formats,     _cookieHeader: cookieHeader   }; } /**  * Downloads a resolved stream URL directly to disk.  * Preserves the machine and session token required by omdown WAF.  * @param {string} streamUrl  * @param {string} destPath  * @param {object} [options]  * @param {string} [options.cookieHeader]  * @returns {Promise}  */ async function downloadMedia(streamUrl, destPath, options = {}) {   const ua = options.userAgent || DEFAULT_USER_AGENT;   const cookieHeader = options.cookieHeader || (await initSession(options)).cookieHeader;   const res = await fetch(streamUrl, {     headers: {       'User-Agent': ua,       'Referer': `${BASE_URL}/id`,       'Cookie': cookieHeader     }   });   if (!res.ok) {     const errText = await res.text().catch(() => '');     throw new Error(`Media download failed: HTTP ${res.status} ${res.statusText} (${errText.trim()})`);   }   const dir = path.dirname(destPath);   if (!fs.existsSync(dir)) {     fs.mkdirSync(dir, { recursive: true });   }   const dest = fs.createWriteStream(destPath);   await pipeline(Readable.fromWeb(res.body), dest);   return destPath; } // Module Exports module.exports = {   resolveMedia,   downloadMedia,   getStats,   initSession,   detectPlatform,   parseFlightStream,   PLATFORM_RULES,   BASE_URL }; // CLI Execution Handler if (require.main === module) {   const args = process.argv.slice(2);   const command = args[0];   if (!command || args.includes('--help') || args.includes('-h')) {     console.error('Usage: node omdown_scraper.js [options]');     console.error('\nCommands:');     console.error('                Resolve media details & download links for 27 platforms');     console.error('  stats              Fetch total download counter stats from omdown');     console.error('\nOptions:');     console.error('  --download         Download media to disk (defaults to highest quality format)');     console.error('  --format       Specify format ID to download (e.g., yt_137_1080p, yt_audio_mp3)');     console.error('  --out    Destination path or directory (default: current directory)');     console.error('  --platform   Explicit platform override (e.g. YouTube, TikTok, Instagram)');     console.error('  --json             Print JSON response only');     process.exit(1);   }   const isJson = args.includes('--json');   const shouldDownload = args.includes('--download');   const outIdx = args.indexOf('--out');   const outPath = outIdx !== -1 ? args[outIdx + 1] : process.cwd();   const formatIdx = args.indexOf('--format');   const targetFormatId = formatIdx !== -1 ? args[formatIdx + 1] : null;   const platformIdx = args.indexOf('--platform');   const platformOverride = platformIdx !== -1 ? args[platformIdx + 1] : undefined;   (async () => {     try {       // 1. Stats Command       if (command === 'stats') {         const stats = await getStats();         if (isJson) {           console.log(JSON.stringify(stats, null, 2));         } else {           console.log('\n=== omdown Global Stats ===');           console.log(`Total Completed Downloads: ${stats.totalDownloads || 0}`);         }         return;       }       // 2. Resolve & Download Flow       const media = await resolveMedia(command, { platform: platformOverride });       if (isJson && !shouldDownload) {         console.log(JSON.stringify(media, null, 2));         return;       }       console.log(`\n=== omdown Resolved Media [${media.platform}] ===`);       console.log(`Title    : ${media.title || '(no title)'}`);       if (media.author) console.log(`Author   : ${media.author}`);       if (media.duration) console.log(`Duration : ${media.duration}`);       if (media.views) console.log(`Views    : ${media.views}`);       if (media.likes) console.log(`Likes    : ${media.likes}`);       console.log(`Formats  : ${media.formatsCount} available`);       console.log('\nAvailable Streams:');       media.formats.forEach((fmt, i) => {         console.log(`  [${i + 1}] ID: ${fmt.id.padEnd(16)} | ${fmt.label} (${fmt.ext})`);       });       if (shouldDownload) {         let chosen = null;         if (targetFormatId) {           chosen = media.formats.find(f => f.id === targetFormatId);           if (!chosen) {             console.error(`\n[-] Format ID "${targetFormatId}" not found. Falling back to primary stream.`);           }         }         if (!chosen) {           // Prefer high quality video, else high quality audio           chosen =             media.formats.find(f => f.kind === 'video' && f.downloadUrl) ||             media.formats.find(f => f.kind === 'audio' && f.downloadUrl) ||             media.formats[0];         }         if (!chosen || !chosen.downloadUrl) {           throw new Error('No downloadable stream available for this item');         }         const safeTitle = (media.title || 'media').replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 50);         let dest = outPath;         if (!dest.includes('.') || fs.existsSync(dest) && fs.statSync(dest).isDirectory()) {           dest = path.join(dest, `${safeTitle}_${chosen.id}.${chosen.ext}`);         }         console.log(`\n[+] Downloading format "${chosen.label}" -> ${dest}`);         await downloadMedia(chosen.downloadUrl, dest, { cookieHeader: media._cookieHeader });         console.log(`[+] File saved successfully: ${dest}`);       } else {         console.log('\n(Add --download to save to disk, or --format --download to pick a format)');       }     } catch (err) {       console.error(`[-] Error: ${err.message}`);       process.exit(1);     }   })(); }