/** * Scraper Facebook Video Downloader * Creator : @wilz * Sumber : https://whatsapp.com/channel/0029VbDzmSDGU3BEzv9qZA1U * Base : https://savefrom.co.id/ * * Instalasi: * npm i axios puppeteer puppeteer-extra puppeteer-extra-plugin-stealth * * CLI: * node scraper/fbdown.js "" * node scraper/fbdown.js "" --debug * node scraper/fbdown.js "" --puppeteer */ const crypto = require('crypto'); const axios = require('axios'); const querystring = require('querystring'); // ─── Konfigurasi ──────────────────────────────────────────────── const BASE_API_URL = 'https://api-wh.savefrom.co.id/api/convert'; const HOME_URL = 'https://savefrom.co.id/'; const TIMEOUT = 30000; const STATIC_TS = 1791197287300; const UA = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Mobile Safari/537.36'; const DEFAULT_HEADERS = { 'User-Agent': UA, Accept: 'application/json, text/plain, */*', 'Accept-Language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', Origin: 'https://savefrom.co.id', Referer: 'https://savefrom.co.id/', 'Sec-Ch-Ua': '"Chromium";v="139", "Not;A=Brand";v="99"', 'Sec-Ch-Ua-Mobile': '?1', 'Sec-Ch-Ua-Platform': '"Android"', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-site', }; const client = axios.create({ timeout: TIMEOUT, headers: DEFAULT_HEADERS, validateStatus: (s) => s >= 200 && s < 500, }); // ─── Helper: Sanitasi ─────────────────────────────────────────── function sanitizeUrl(input) { if (!input) return ''; let s = String(input).trim(); if (!/^https?:\/\//i.test(s)) s = 'https://' + s; return s; } function isFacebookUrl(url) { return /(facebook\.com|fb\.watch|fb\.me|m\.facebook\.com)/i.test(url); } // ─── Helper: Signature Generator (8 varian) ───────────────────── const SIG_FORMULAS = { 1: (u, ts) => `${u}${ts}`, 2: (u, ts) => `${u}|${ts}`, 3: (u, ts) => `${ts}${u}`, 4: (u, ts) => `${u}${ts}${STATIC_TS}0`, 5: (u, ts) => `${u}-${ts}`, 6: (u, ts) => `${ts}|${u}`, 7: (u, ts) => `savefrom${u}${ts}`, 8: (u, ts) => `${u}${ts}${STATIC_TS}`, }; function generateSignature(sfUrl, ts, mode = 1) { const fn = SIG_FORMULAS[mode] || SIG_FORMULAS[1]; return crypto.createHash('sha256').update(fn(sfUrl, ts)).digest('hex'); } // ─── Helper: Bangun Body ──────────────────────────────────────── function buildFormBody(sfUrl, ts, signature) { return querystring.stringify({ sf_url: sfUrl, ts, _ts: STATIC_TS, _tsc: 0, _s: signature, }); } // ─── Helper: Ekstrak Pesan Error (Deep) ───────────────────────── function extractErrorMessage(json, depth = 0) { if (!json || typeof json !== 'object' || depth > 4) return null; const fields = ['message', 'error', 'msg', 'errors', 'detail', 'reason']; for (const f of fields) { const v = json[f]; if (!v) continue; if (typeof v === 'string') return v; if (Array.isArray(v)) return v.join('; '); if (typeof v === 'object') { const nested = extractErrorMessage(v, depth + 1); if (nested) return nested; return JSON.stringify(v); } } // Cek di data / result if (json.data) { const nested = extractErrorMessage(json.data, depth + 1); if (nested) return nested; } return null; } // ─── Helper: Coba Satu Signature ──────────────────────────────── async function trySignature(sfUrl, ts, mode, debug) { const signature = generateSignature(sfUrl, ts, mode); const body = buildFormBody(sfUrl, ts, signature); let res; try { res = await client.post(BASE_API_URL, body); } catch (err) { return { ok: false, mode, error: `Network: ${err.message}`, status: null }; } const json = res.data; if (debug) { console.log(`\n[Debug] Mode ${mode} | sig=${signature.slice(0, 16)}… | HTTP ${res.status}`); console.log('[Debug] Body:', JSON.stringify(json).slice(0, 500)); } if (!json || typeof json !== 'object') { return { ok: false, mode, error: 'Respons bukan JSON', status: res.status }; } if (res.status !== 200) { return { ok: false, mode, error: `HTTP ${res.status}: ${extractErrorMessage(json) || 'unknown'}`, status: res.status, }; } // Server bisa balas 200 tapi ada field error const urlList = Array.isArray(json.url) ? json.url : []; if (!urlList.length) { const err = extractErrorMessage(json); return { ok: false, mode, error: err || 'URL list kosong di respons', status: res.status, raw: json, }; } return { ok: true, mode, data: json, status: res.status }; } // ─── Helper: Normalisasi Media ────────────────────────────────── function normalizeMedia(item) { if (!item || !item.url) return null; return { url: item.url, ext: item.ext || null, name: item.name || null, type: item.type || null, quality: item.subname || null, priority: item.priority ?? null, }; } function extractResult(json, sourceUrl) { const urlList = Array.isArray(json.url) ? json.url : []; const media = urlList.map(normalizeMedia).filter(Boolean); media.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0)); const sd = media.find((m) => /sd|normal|360|480/i.test(m.quality || '')) || media[0]; const hd = media.find((m) => /hd|720|1080/i.test(m.quality || '')) || (media.length > 1 ? media[media.length - 1] : null); const meta = json.meta || {}; return { success: true, source: sourceUrl, id: json.id || null, hosting: json.hosting || 'facebook.com', meta: { title: meta.title || null, source: meta.source || sourceUrl, duration: meta.duration || null, }, thumb: json.thumb || null, downloads: { sd: sd || null, hd: hd || null, all: media, }, fetchedAt: new Date().toISOString(), }; } // ─── Mode A: Axios — Auto-Try All Sig Modes ───────────────────── async function viaAxios(targetUrl, debug) { const ts = Date.now(); // Kalau user override, langsung pakai if (process.env.SAVEFROM_SIG_OVERRIDE) { const sig = process.env.SAVEFROM_SIG_OVERRIDE; const body = buildFormBody(targetUrl, ts, sig); const res = await client.post(BASE_API_URL, body); const json = res.data; if (res.status === 200 && Array.isArray(json?.url) && json.url.length) { console.log(`[Scraper] Override sig berhasil.`); return extractResult(json, targetUrl); } throw new Error( `Override sig gagal: ${ extractErrorMessage(json) || `HTTP ${res.status}` }` ); } // Kalau user pilih mode tertentu, coba itu saja if (process.env.SAVEFROM_SIG_MODE) { const m = Number(process.env.SAVEFROM_SIG_MODE); console.log(`[Scraper] Mencoba sig mode ${m}…`); const r = await trySignature(targetUrl, ts, m, debug); if (r.ok) { console.log(`[Scraper] Sig mode ${m} berhasil.`); return extractResult(r.data, targetUrl); } throw new Error(`Sig mode ${m} gagal: ${r.error}`); } // Auto-try semua mode const modes = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(`[Scraper] Auto-try ${modes.length} formula signature…`); const errors = []; for (const m of modes) { const r = await trySignature(targetUrl, ts, m, debug); if (r.ok) { console.log(`[Scraper] ✅ Sig mode ${m} berhasil.`); return extractResult(r.data, targetUrl); } errors.push(`mode ${m}: ${r.error}`); if (debug) console.log(`[Debug] mode ${m} gagal: ${r.error}`); } throw new Error( `Semua formula signature gagal.\n` + errors.map((e) => ` • ${e}`).join('\n') + `\n\nSolusi: jalankan dengan --puppeteer untuk capture signature asli dari browser.` ); } // ─── Mode B: Puppeteer — Capture Signature Asli ───────────────── async function viaPuppeteer(targetUrl, debug) { let puppeteer; try { puppeteer = require('puppeteer-extra'); puppeteer.use(require('puppeteer-extra-plugin-stealth')()); } catch { throw new Error( 'Puppeteer belum terpasang. Jalankan: npm i puppeteer-extra puppeteer-extra-plugin-stealth' ); } console.log('[Scraper] Membuka browser untuk capture signature…'); const browser = await puppeteer.launch({ headless: 'new', args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-blink-features=AutomationControlled', ], }); try { const page = await browser.newPage(); await page.setUserAgent(UA); await page.setViewport({ width: 412, height: 915, isMobile: true }); await page.evaluateOnNewDocument(() => { Object.defineProperty(navigator, 'webdriver', { get: () => false }); }); // Tangkap request ke /api/convert let capturedPayload = null; let capturedResponse = null; page.on('request', (req) => { if (req.url().includes('/api/convert') && req.method() === 'POST') { capturedPayload = req.postData(); if (debug) console.log('[Debug] Captured request payload:', capturedPayload); } }); page.on('response', async (res) => { if (res.url().includes('/api/convert')) { try { const ct = res.headers()['content-type'] || ''; if (ct.includes('application/json')) { capturedResponse = await res.json(); } } catch (_) {} } }); console.log('[Scraper] Membuka savefrom.co.id…'); await page.goto(HOME_URL, { waitUntil: 'networkidle2', timeout: 90000 }); await new Promise((r) => setTimeout(r, 3000)); // Isi input URL await page.evaluate((url) => { const inputs = Array.from(document.querySelectorAll('input')); const target = inputs.find( (i) => /url|link|paste|masuk/i.test(i.placeholder || '') || ['text', 'url', 'search'].includes(i.type) || !i.type ); if (target) { target.focus(); target.value = url; target.dispatchEvent(new Event('input', { bubbles: true })); target.dispatchEvent(new Event('change', { bubbles: true })); } }, targetUrl); // Klik tombol submit await page.evaluate(() => { const btns = Array.from( document.querySelectorAll('button, input[type="submit"], a[role="button"]') ); const btn = btns.find((b) => /download|unduh|convert|get|search|go/i.test( b.textContent || b.value || '' ) ); if (btn) btn.click(); else document.querySelector('form')?.requestSubmit?.(); }); // Tunggu response API const start = Date.now(); while (Date.now() - start < 30000 && !capturedResponse) { await new Promise((r) => setTimeout(r, 500)); } if (!capturedResponse) { throw new Error('Tidak dapat menangkap response /api/convert dari browser.'); } if (debug) { console.log('[Debug] Captured response:'); console.log(JSON.stringify(capturedResponse).slice(0, 800)); } if (!Array.isArray(capturedResponse.url) || !capturedResponse.url.length) { throw new Error( `Browser juga tidak menerima URL. Server: ${ extractErrorMessage(capturedResponse) || 'respons kosong' }` ); } return extractResult(capturedResponse, targetUrl); } finally { await browser.close().catch(() => {}); } } // ─── Fungsi Utama ─────────────────────────────────────────────── async function getVideo(rawUrl, opts = {}) { const targetUrl = sanitizeUrl(rawUrl); if (!targetUrl) throw new Error('URL Facebook wajib diisi.'); if (!isFacebookUrl(targetUrl)) { throw new Error( 'URL yang diberikan bukan dari Facebook (facebook.com / fb.watch).' ); } const mode = opts.mode || 'auto'; const debug = !!opts.debug; console.log(`[Scraper] URL : ${targetUrl}`); console.log(`[Scraper] Mode : ${mode}`); if (mode === 'puppeteer') return viaPuppeteer(targetUrl, debug); try { return await viaAxios(targetUrl, debug); } catch (err) { if (mode === 'axios') throw err; console.warn(`[Scraper] Axios gagal: ${err.message}`); console.log('[Scraper] Fallback ke puppeteer…'); return viaPuppeteer(targetUrl, debug); } } // ─── CLI ──────────────────────────────────────────────────────── if (require.main === module) { const args = process.argv.slice(2); const rawUrl = args.find((a) => !a.startsWith('--')); const debug = args.includes('--debug'); const mode = args.includes('--puppeteer') ? 'puppeteer' : args.includes('--axios') ? 'axios' : 'auto'; const sigArg = args.find((a) => a.startsWith('--sig=')); if (sigArg) process.env.SAVEFROM_SIG_MODE = sigArg.split('=')[1]; if (!rawUrl) { console.error( '❌ URL Facebook tidak ditemukan!\n\n' + 'Cara pakai:\n' + ' node scraper/savefrom.js "" [opsi]\n\n' + 'Opsi:\n' + ' --sig=1..8 Paksa formula signature tertentu\n' + ' --axios Paksa mode axios saja\n' + ' --puppeteer Paksa mode puppeteer\n' + ' --debug Log detail\n\n' + 'Contoh:\n' + ' node scraper/savefrom.js "https://www.facebook.com/share/v/1A27mMWnZv/"\n' + ' node scraper/savefrom.js "https://fb.watch/xxxx/" --puppeteer' ); process.exit(1); } (async () => { try { const result = await getVideo(rawUrl, { mode, debug }); console.log('\n✅ Hasil Scrape Berhasil & Divalidasi:'); console.log(JSON.stringify(result, null, 2)); } catch (err) { console.error('\n❌ Error:', err.message); process.exit(1); } })(); } module.exports = { getVideo, sanitizeUrl, generateSignature };