#!/usr/bin/env node /** * ===================================================================== * Instagram Media & Reels Downloader (Pure Node.js) * High-performance direct extractor using native Instagram GraphQL doc_id * Supports: Reels, Videos, Photos, and Carousels (Sidecars) * * Base URL Discrape : https://www.instagram.com/graphql/query * Official Website : https://vamxapi.my.id * WhatsApp Channel : https://whatsapp.com/channel/0029Vb8n36OGE56uvRAq4y3y * Author : Vamz Spectre / Vamx * ===================================================================== */ const fs = require("fs"); const path = require("path"); const https = require("https"); const http = require("http"); const axios = require("axios"); let sessionCache = null; async function getInstagramSession() { const now = Date.now(); if (sessionCache && sessionCache.expiresAt > now && sessionCache.csrf) { return { csrf: sessionCache.csrf, cookies: sessionCache.cookies }; } const userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"; const homeRes = await axios.get("https://www.instagram.com/", { headers: { "User-Agent": userAgent, Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.8", }, timeout: 10000, validateStatus: () => true, maxRedirects: 0, }); const rawCookies = homeRes.headers["set-cookie"] || []; const cookieStr = rawCookies.map((c) => c.split(";")[0]).join("; "); const csrfMatch = cookieStr.match(/csrftoken=([^;]+)/); const csrf = csrfMatch ? csrfMatch[1] : ""; sessionCache = { csrf, cookies: cookieStr, expiresAt: now + 20 * 60 * 1000, }; return { csrf, cookies: cookieStr }; } function extractShortcode(url) { const match = url.match(/(?:p|reel|reels)\/([A-Za-z0-9_-]+)/); if (match) return match[1]; const parts = url.split("?")[0].replace(/\/+$/, "").split("/"); return parts[parts.length - 1] || null; } async function extractInstagramMedia(url) { try { const shortcode = extractShortcode(url); if (!shortcode) { return { status: false, message: "Shortcode Instagram tidak valid" }; } let { csrf, cookies } = await getInstagramSession(); const userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"; const fetchItem = async (currentCsrf, currentCookies) => { const payload = new URLSearchParams({ variables: JSON.stringify({ shortcode, __relay_internal__pv__PolarisAIGMMediaWebLabelEnabledrelayprovider: false, }), doc_id: "27128499623469141", server_timestamps: "true", }); return axios.post("https://www.instagram.com/graphql/query", payload.toString(), { headers: { "User-Agent": userAgent, Accept: "*/*", "Accept-Language": "en-US,en;q=0.8", "Content-Type": "application/x-www-form-urlencoded", "X-CSRFToken": currentCsrf, "X-IG-App-ID": "936619743392459", Cookie: currentCookies, Referer: `https://www.instagram.com/p/${shortcode}/`, }, timeout: 15000, validateStatus: () => true, }); }; let res = await fetchItem(csrf, cookies); if (res.status !== 200 || !res.data?.data) { sessionCache = null; const refreshed = await getInstagramSession(); csrf = refreshed.csrf; cookies = refreshed.cookies; res = await fetchItem(csrf, cookies); } const items = res.data?.data?.xdt_api__v1__media__shortcode__web_info?.items; if (!items || !items.length) { return { status: false, message: "Media tidak ditemukan atau akun privat." }; } const item = items[0]; const downloadUrls = []; // Carousel (Multiple Media) if (Array.isArray(item.carousel_media) && item.carousel_media.length > 0) { for (const sub of item.carousel_media) { if (sub.video_versions && sub.video_versions.length > 0) { downloadUrls.push(sub.video_versions[0].url); } else if (sub.image_versions2?.candidates?.[0]?.url) { downloadUrls.push(sub.image_versions2.candidates[0].url); } } } else { if (item.video_versions && item.video_versions.length > 0) { downloadUrls.push(item.video_versions[0].url); } else if (item.image_versions2?.candidates?.[0]?.url) { downloadUrls.push(item.image_versions2.candidates[0].url); } } const uniqueUrls = [...new Set(downloadUrls)]; if (uniqueUrls.length === 0) { return { status: false, message: "Link download media Instagram tidak ditemukan." }; } return { status: true, creator: "vamxapi", website: "https://vamxapi.my.id", channel: "https://whatsapp.com/channel/0029Vb8n36OGE56uvRAq4y3y", source: "instagram-native", metadata: { username: item.user?.username || "-", full_name: item.user?.full_name || "", caption: item.caption?.text || "", thumbnail: item.image_versions2?.candidates?.[0]?.url || null, likes: item.like_count ?? 0, comments: item.comment_count ?? 0, is_video: !!item.video_versions, }, downloadUrl: uniqueUrls, }; } catch (err) { return { status: false, message: err.message || "Gagal mengekstrak media Instagram.", }; } } function downloadFile(fileUrl, outputPath) { return new Promise((resolve, reject) => { const client = fileUrl.startsWith("https") ? https : http; const req = client.get( fileUrl, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", Referer: "https://www.instagram.com/", }, }, (res) => { if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { return downloadFile(res.headers.location, outputPath).then(resolve).catch(reject); } if (res.statusCode !== 200) { return reject(new Error(`Download gagal dengan status HTTP ${res.statusCode}`)); } const totalBytes = parseInt(res.headers["content-length"] || "0", 10); let downloadedBytes = 0; const fileStream = fs.createWriteStream(outputPath); res.on("data", (chunk) => { downloadedBytes += chunk.length; if (totalBytes > 0) { const pct = ((downloadedBytes / totalBytes) * 100).toFixed(1); process.stdout.write(`\ršŸ“„ Mengunduh: ${pct}% (${(downloadedBytes / 1024 / 1024).toFixed(2)} MB / ${(totalBytes / 1024 / 1024).toFixed(2)} MB)`); } }); res.pipe(fileStream); fileStream.on("finish", () => { fileStream.close(); console.log(`\nāœ… Media berhasil disimpan ke: ${outputPath}`); resolve({ path: outputPath, size: downloadedBytes }); }); fileStream.on("error", (err) => { fs.unlink(outputPath, () => {}); reject(err); }); } ); req.on("error", reject); }); } async function main() { const targetUrl = process.argv[2] || "https://www.instagram.com/reel/DdL4EZcu7Aw/"; console.log(`šŸ” Memproses Instagram URL: ${targetUrl}`); const data = await extractInstagramMedia(targetUrl); console.log("\n[Instagram Extractor] Result:", JSON.stringify(data, null, 2)); if (data.status && Array.isArray(data.downloadUrl) && data.downloadUrl.length > 0) { const firstUrl = data.downloadUrl[0]; const isVideo = data.metadata?.is_video !== false; const ext = isVideo ? "mp4" : "jpg"; const outputFile = path.join(process.cwd(), `instagram_${Date.now()}.${ext}`); console.log(`\nā³ Mengunduh file media (${ext.toUpperCase()})...`); try { await downloadFile(firstUrl, outputFile); } catch (err) { console.error("\nāŒ Gagal mengunduh file:", err.message); } } else { console.error("\nāŒ Tidak ada link download yang dapat diunduh."); } } if (require.main === module) { main(); } if (typeof module !== "undefined" && module.exports) { module.exports = { extractInstagramMedia, downloadFile, }; }