downloaderjavascript380103
VidGap Multi-Platform Downloader (TikTok, Douyin, Lemon8)
Scraper downloader otomatis dengan Auto-Healing Next.js Server Action IDs & WebSocket support. Unduh video tanpa watermark, audio MP3, foto galeri slideshow, dan profil author.
Vamz Spectre29 Sep 2026756 baris kode
Jalankan via Terminal / CLI:
# 1. Download file script
curl -sL "https://code.vamxapi.my.id/snippet/raw/vidgap-downloader" -o vidgap-downloader.js
# 2. Jalankan script
node vidgap-downloader.js
Dependencies npm yang Dibutuhkan:
npm install socket.io-clientPanduan Penggunaan:
// Instalasi Dependencies:
npm install socket.io-client
// Penggunaan CLI:
node vidgap-downloader.js "https://vt.tiktok.com/ZSbh6Qp4j/"
// Penggunaan di Bot WhatsApp (Baileys):
const { downloadVidGap } = require(./vidgap-downloader);
const result = await downloadVidGap(url);
if (result.status) {
await sock.sendMessage(m.chat, { video: { url: result.result.media.video.noWatermarkHd } });
}vidgap-downloader.js(756 lines)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/**
* VidGap Scraper - Multi-Platform Downloader (TikTok, Douyin, Lemon8)
* Author: Vamz Spectre (VamxAPI)
* Target: vidgap.com Next.js App Router Server Actions + WebSocket Engine (socket.vidgap.com)
*
* Fitur:
* - Auto-Healing Dynamic Action IDs: Otomatis mendeteksi hash Server Action Next.js terbaru
* sehingga ANTI-404 bahkan saat VidGap melakukan deploy build baru!
* - Dynamic Page Session Management: Menangani autentikasi sesi JWT (vg_session) otomatis
* - Zero Configuration: Cukup input link/teks, semua dideteksi otomatis (Platform, Jenis Konten, Tab)
* - Dukungan penuh platform:
* - TikTok (Video, Foto/Slideshow, Audio/Musik, Story, Profil @user)
* - Douyin (抖音 - Video, Gambar, Musik, Profil)
* - Lemon8 (Postingan, Galeri Gambar)
* - Auto-clean & extraction link dari teks acak / hasil share WhatsApp, Telegram, Clipboard
* - Mengambil seluruh metadata dan media:
* - Video HD tanpa watermark (langsung CDN)
* - Video Standar (Non-watermark)
* - Video Watermark (jika ada)
* - Ukuran file terformat (MB/KB) & raw bytes
* - Audio / Musik MP3 lengkap (Judul, durasi, URL file)
* - Slideshow galeri gambar beresolusi tinggi lengkap
* - Thumbnail, Cover, Dynamic Animated Cover
* - Informasi Author/Kreator (Username, Nickname, Avatar HD, Profile URL, ID)
* - Statistik lengkap (Views, Likes, Comments, Shares) + angka terformat (1.2K, 3.4M)
* - Hashtag yang diekstrak dari caption
* - Support direct cache extraction & WebSocket live job queue (socket.vidgap.com)
* - Resolusi otomatis redirect token (/api/video/redirect/...) menjadi URL CDN langsung siap unduh
* - Siap digunakan via CLI (node vidgap.js <link>) maupun diimpor sebagai modul (CommonJS)
*/
const dns = require("dns");
if (dns && typeof dns.setDefaultResultOrder === "function") {
dns.setDefaultResultOrder("ipv4first");
}
const { io } = require("socket.io-client");
const VIDGAP_BASE_URL = "https://vidgap.com";
const VIDGAP_SOCKET_URL = "https://socket.vidgap.com";
const DEFAULT_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";
// Cache in-memory untuk Server Action IDs dengan fallback hash Next.js build saat ini
let cachedActionIds = {
findContent: "4091bfdbb5d988e317bc1807ecf621788a15b8b1e8",
updateToken: "400e140eaf0c4c29003d6051a6b2aaf271eb2eaf4a",
lastFetched: 0,
};
// Cache in-memory untuk page-session cookie (vg_session)
let cachedSessionCookie = null;
/**
* Mendapatkan dan me-refresh cookie session VidGap (vg_session)
* @param {boolean} forceRefresh
* @returns {Promise<string>}
*/
async function getPageSessionCookie(forceRefresh = false) {
if (!forceRefresh && cachedSessionCookie && cachedSessionCookie.expiresAt > Date.now()) {
return cachedSessionCookie.cookie;
}
try {
const res = await fetch(`${VIDGAP_BASE_URL}/api/page-session`, {
method: "POST",
headers: {
"User-Agent": DEFAULT_USER_AGENT,
Origin: VIDGAP_BASE_URL,
Referer: `${VIDGAP_BASE_URL}/`,
},
});
const setCookies =
typeof res.headers.getSetCookie === "function"
? res.headers.getSetCookie()
: [res.headers.get("set-cookie") || ""];
const vgSession = setCookies
.map((c) => (c ? c.split(";")[0].trim() : ""))
.find((c) => c && c.startsWith("vg_session="));
if (vgSession) {
cachedSessionCookie = {
cookie: vgSession,
expiresAt: Date.now() + 15 * 60 * 1000,
};
return vgSession;
}
} catch {}
return cachedSessionCookie?.cookie || "";
}
/**
* Mendapatkan Server Action ID terbaru secara dinamis dari bundle Next.js VidGap
* @param {boolean} forceRefresh
* @returns {Promise<{findContent: string, updateToken: string}>}
*/
async function getActionIds(forceRefresh = false) {
if (
!forceRefresh &&
cachedActionIds.findContent &&
cachedActionIds.updateToken &&
Date.now() - cachedActionIds.lastFetched < 3600000
) {
return cachedActionIds;
}
try {
const htmlRes = await fetch(`${VIDGAP_BASE_URL}/`, {
headers: { "User-Agent": DEFAULT_USER_AGENT },
});
const html = await htmlRes.text();
const chunkUrls = [...html.matchAll(/src="(\/_next\/static\/chunks\/[^"]+)"/g)].map((m) => m[1]);
let findContentId = null;
let updateTokenId = null;
for (const chunkPath of chunkUrls) {
try {
const chunkRes = await fetch(`${VIDGAP_BASE_URL}${chunkPath}`, {
headers: { "User-Agent": DEFAULT_USER_AGENT },
});
const chunkText = await chunkRes.text();
if (!findContentId && chunkText.includes("findContentActionsQueue")) {
const match = chunkText.match(/createServerReference\)\("([a-f0-9]+)"[^)]*"findContentActionsQueue"\)/);
if (match) findContentId = match[1];
}
if (!updateTokenId && chunkText.includes("updateDownloadToken")) {
const match = chunkText.match(/createServerReference\)\("([a-f0-9]+)"[^)]*"updateDownloadToken"\)/);
if (match) updateTokenId = match[1];
}
if (findContentId && updateTokenId) break;
} catch {}
}
if (findContentId) cachedActionIds.findContent = findContentId;
if (updateTokenId) cachedActionIds.updateToken = updateTokenId;
cachedActionIds.lastFetched = Date.now();
} catch {}
return cachedActionIds;
}
/**
* Ekstrak dan normalisasi URL dari input teks mentah (misal teks share WA/Telegram)
* @param {string} rawInput - Teks atau URL mentah
* @returns {string} Clean URL
*/
function extractAndNormalize(rawInput) {
if (!rawInput || typeof rawInput !== "string") {
throw new Error("Parameter link atau URL wajib diisi.");
}
const trimmed = rawInput.trim();
// 1. Ekstrak URL http/https dari teks
const urlRegex = /(https?:\/\/[^\s<>"{}|\\^~\[\]`]+)/i;
const match = trimmed.match(urlRegex);
let detectedUrl = match ? match[1] : null;
if (detectedUrl) {
// Bersihkan karakter tanda baca penutup yang sering menempel
detectedUrl = detectedUrl.replace(/[)\]}>,.;!]+$/, "");
return detectedUrl;
}
// 2. Jika bukan link http(s), cek format username atau ID
if (trimmed.startsWith("@")) {
return `https://www.tiktok.com/@${trimmed.slice(1).trim().toLowerCase()}`;
}
// Contoh: 19 digit angka (TikTok video ID murni)
if (/^\d{15,21}$/.test(trimmed)) {
return `https://www.tiktok.com/@user/video/${trimmed}`;
}
// Contoh: username biasa tanpa @ (misal: "tiktok")
if (/^[a-zA-Z0-9_.-]{3,30}$/.test(trimmed) && !trimmed.includes("/") && !trimmed.includes(".")) {
return `https://www.tiktok.com/@${trimmed.toLowerCase()}`;
}
return trimmed;
}
/**
* Mendeteksi platform target otomatis berdasarkan URL
* @param {string} url
* @returns {"douyin" | "lemon8" | "tiktok"}
*/
function detectPlatform(url) {
const lower = String(url || "").toLowerCase();
if (lower.includes("douyin.com") || lower.includes("iesdouyin.com")) {
return "douyin";
}
if (
lower.includes("lemon8-app.com") ||
lower.includes("lemon8.com") ||
lower.includes("s.lemon8-app.com")
) {
return "lemon8";
}
return "tiktok";
}
/**
* Mendeteksi tab / tipe konten secara otomatis berdasarkan pola link
* @param {string} url
* @returns {"all" | "audio" | "slideshow" | "profile" | "story"}
*/
function detectTab(url) {
const lower = String(url || "").toLowerCase();
if (lower.includes("/music/")) return "audio";
if (lower.includes("/photo/") || lower.includes("slideshow")) return "slideshow";
if (lower.includes("/story/")) return "story";
if (
/@[\w.-]+(?:\/?$|\?[^/]*$)/.test(lower) &&
!lower.includes("/video/") &&
!lower.includes("/photo/")
) {
return "profile";
}
return "all";
}
/**
* Helper format ukuran bytes ke format yang mudah dibaca (KB / MB / GB)
* @param {number} bytes
* @returns {string | undefined}
*/
function formatBytes(bytes) {
if (!bytes || isNaN(bytes) || bytes <= 0) return undefined;
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
}
/**
* Helper format angka statistik ke format ringkas (1.2K, 3.4M)
* @param {number} num
* @returns {string | undefined}
*/
function formatNumber(num) {
if (typeof num !== "number" || isNaN(num)) return undefined;
if (num >= 1000000000) return (num / 1000000000).toFixed(1).replace(/\.0$/, "") + "B";
if (num >= 1000000) return (num / 1000000).toFixed(1).replace(/\.0$/, "") + "M";
if (num >= 1000) return (num / 1000).toFixed(1).replace(/\.0$/, "") + "K";
return num.toString();
}
/**
* Helper format durasi detik ke MM:SS
* @param {number} sec
* @returns {string | undefined}
*/
function formatDuration(sec) {
if (typeof sec !== "number" || isNaN(sec) || sec < 0) return undefined;
const m = Math.floor(sec / 60);
const s = Math.floor(sec % 60);
return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}
/**
* Helper ekstrak hashtag dari teks judul / caption
* @param {string} text
* @returns {string[]}
*/
function extractHashtags(text) {
if (!text || typeof text !== "string") return [];
const matches = text.match(/#[\p{L}\p{N}_-]+/gu);
return matches ? [...new Set(matches)] : [];
}
/**
* Memanggil Server Action Next.js findContentActionsQueue dengan auto-healing & dynamic session
*/
async function callFindContentAction(url, platform = "tiktok", tab = "default", isRetry = false) {
const actionIds = await getActionIds(isRetry);
const vgSession = await getPageSessionCookie(isRetry);
const actionPayload = [
{
vLink: url,
agent: "Web",
tab: tab || "default",
amplified: false,
platform,
skipVgShareAccessIncrement: undefined,
},
];
const pagePath = platform === "tiktok" ? "" : platform;
const endpointUrl = `${VIDGAP_BASE_URL}/${pagePath}`;
const headers = {
"Next-Action": actionIds.findContent,
"Content-Type": "text/plain;charset=UTF-8",
"User-Agent": DEFAULT_USER_AGENT,
Origin: VIDGAP_BASE_URL,
Referer: endpointUrl,
Accept: "text/x-component",
};
if (vgSession) {
headers["Cookie"] = vgSession;
}
const res = await fetch(endpointUrl, {
method: "POST",
headers,
body: JSON.stringify(actionPayload),
});
if ((res.status === 404 || res.headers.get("x-nextjs-action-not-found")) && !isRetry) {
return callFindContentAction(url, platform, tab, true);
}
if (!res.ok) {
throw new Error(`VidGap Server Action HTTP ${res.status}: ${res.statusText}`);
}
const text = await res.text();
let sessionId = null;
let cachedData = null;
for (const line of text.split("\n")) {
const colonIdx = line.indexOf(":");
if (colonIdx === -1) continue;
const jsonStr = line.slice(colonIdx + 1).trim();
if (!jsonStr.startsWith("{") && !jsonStr.startsWith("[")) continue;
try {
const parsed = JSON.parse(jsonStr);
if (parsed?.reason === "no_page_session" && !isRetry) {
await getPageSessionCookie(true);
return callFindContentAction(url, platform, tab, true);
}
if (parsed?.sessionId) {
sessionId = parsed.sessionId;
}
if (parsed?.cached && parsed?.data) {
cachedData = parsed.data;
break;
}
if (parsed?.title && parsed?.title !== "#NO_CONTENT#") {
cachedData = parsed;
break;
}
} catch {}
}
return { sessionId, cachedData };
}
/**
* Menghubungkan ke WebSocket socket.vidgap.com untuk mengambil data jika antrean aktif
*/
async function waitForSocketData(sessionId, timeoutMs = 25000) {
return new Promise((resolve, reject) => {
let resolved = false;
const timer = setTimeout(() => {
if (resolved) return;
resolved = true;
socket.disconnect();
reject(new Error(`Timeout (${timeoutMs / 1000}s) saat menunggu data dari antrean VidGap socket.`));
}, timeoutMs);
const socket = io(VIDGAP_SOCKET_URL, {
transports: ["websocket"],
timeout: 10000,
forceNew: true,
reconnection: false,
extraHeaders: {
"User-Agent": DEFAULT_USER_AGENT,
Origin: VIDGAP_BASE_URL,
},
});
socket.on("connect", () => {
socket.emit("authenticate", sessionId);
});
socket.on("authenticate", (authRes) => {
if (authRes && authRes.status === "failed") {
clearTimeout(timer);
resolved = true;
socket.disconnect();
reject(new Error("Autentikasi sesi VidGap gagal: " + (authRes.message || "Unknown error")));
}
});
socket.on("retrieve-data", (rawData) => {
clearTimeout(timer);
if (resolved) return;
resolved = true;
socket.disconnect();
try {
const parsed = typeof rawData === "string" ? JSON.parse(rawData) : rawData;
if (!parsed) {
return reject(new Error("Data kosong diterima dari VidGap."));
}
if (parsed.errorMessage) {
return reject(new Error(parsed.errorMessage?.message || parsed.errorMessage?.type || "VidGap error"));
}
resolve(parsed.data || parsed);
} catch (err) {
reject(err);
}
});
socket.on("error", (err) => {
clearTimeout(timer);
if (resolved) return;
resolved = true;
socket.disconnect();
reject(new Error(`Koneksi socket error: ${err}`));
});
socket.on("connect_error", (err) => {
clearTimeout(timer);
if (resolved) return;
resolved = true;
socket.disconnect();
reject(new Error(`Koneksi socket connect_error: ${err?.message || err}`));
});
});
}
/**
* Mengambil cookies token unduhan dari Server Action updateDownloadToken dengan auto-healing
*/
async function obtainDownloadCookies(contentId, isRetry = false) {
if (!contentId) return "";
const actionIds = await getActionIds(isRetry);
const vgSession = await getPageSessionCookie(isRetry);
try {
const headers = {
"Next-Action": actionIds.updateToken,
"Content-Type": "text/plain;charset=UTF-8",
"User-Agent": DEFAULT_USER_AGENT,
Origin: VIDGAP_BASE_URL,
Referer: `${VIDGAP_BASE_URL}/`,
};
if (vgSession) {
headers["Cookie"] = vgSession;
}
const res = await fetch(`${VIDGAP_BASE_URL}/`, {
method: "POST",
headers,
body: JSON.stringify([String(contentId)]),
});
if ((res.status === 404 || res.headers.get("x-nextjs-action-not-found")) && !isRetry) {
return obtainDownloadCookies(contentId, true);
}
const setCookies =
typeof res.headers.getSetCookie === "function"
? res.headers.getSetCookie()
: [res.headers.get("set-cookie") || ""];
return setCookies
.filter(Boolean)
.map((c) => c.split(";")[0].trim())
.join("; ");
} catch {
return "";
}
}
/**
* Menyelesaikan URL redirect /api/video/redirect/... menjadi tautan file langsung
*/
async function resolveRedirectUrl(relativeOrFullUrl, cookieHeader) {
if (!relativeOrFullUrl || typeof relativeOrFullUrl !== "string") return undefined;
if (!relativeOrFullUrl.includes("/api/video/redirect/")) {
return relativeOrFullUrl;
}
const fullUrl = relativeOrFullUrl.startsWith("http")
? relativeOrFullUrl
: `${VIDGAP_BASE_URL}${relativeOrFullUrl.startsWith("/") ? "" : "/"}${relativeOrFullUrl}`;
try {
const res = await fetch(fullUrl, {
method: "GET",
redirect: "manual",
headers: {
Cookie: cookieHeader || "",
"User-Agent": DEFAULT_USER_AGENT,
Referer: `${VIDGAP_BASE_URL}/`,
},
});
const location = res.headers.get("location");
if (location && location.startsWith("http")) {
return location;
}
} catch {}
return fullUrl;
}
/**
* Scraper Utama VidGap (Cukup masukkan link, semua dideteksi otomatis)
* @param {string} input - Tautan, share text, atau ID TikTok/Douyin/Lemon8
* @param {object} [options] - Opsi tambahan (opsional)
* @param {"tiktok" | "douyin" | "lemon8"} [options.platform] - Override platform jika diperlukan
* @param {"all" | "video" | "audio" | "slideshow" | "story" | "profile"} [options.tab] - Override tab
* @param {number} [options.timeout] - Timeout socket dalam milidetik (default: 25000)
* @returns {Promise<object>} Objek data lengkap siap pakai
*/
async function scrapeVidgap(input, options = {}) {
// 1. Ekstrak & Normalisasi link otomatis
const cleanUrl = extractAndNormalize(input);
// 2. Deteksi otomatis platform dan tab
const platform = options.platform || detectPlatform(cleanUrl);
const tab = options.tab || detectTab(cleanUrl) || "default";
const timeoutMs = options.timeout || 25000;
// 3. Eksekusi Server Action
let { sessionId, cachedData } = await callFindContentAction(cleanUrl, platform, tab);
// Fallback ke tab "default" jika tab spesifik tidak menghasilkan sesi/cache
if (!cachedData && !sessionId && tab !== "default") {
const fallbackRes = await callFindContentAction(cleanUrl, platform, "default");
sessionId = fallbackRes.sessionId;
cachedData = fallbackRes.cachedData;
}
let rawData = cachedData;
if (!rawData && sessionId) {
rawData = await waitForSocketData(sessionId, timeoutMs);
}
if (!rawData) {
throw new Error("Gagal mengambil data dari VidGap (tidak ada respon valid dari server).");
}
if (rawData.title === "#NO_CONTENT#") {
throw new Error("Konten tidak ditemukan atau video/postingan bersifat privat/telah dihapus.");
}
// 4. Token Exchange untuk resolusi redirect download link
const contentId = rawData.contentId || rawData._id || "";
let cookieHeader = "";
if (contentId) {
cookieHeader = await obtainDownloadCookies(contentId);
}
// 5. Resolusi tautan video langsung (CDN)
const clientUrls = rawData.clientVideoURL || {};
let nonwmVideoUrl = clientUrls.nonwm || rawData.videoURL;
let hdVideoUrl = rawData.hdVideoURL || clientUrls.hd;
let wmVideoUrl = clientUrls.wm || rawData.wmURL;
if (nonwmVideoUrl && nonwmVideoUrl.includes("/api/video/redirect/")) {
nonwmVideoUrl = await resolveRedirectUrl(nonwmVideoUrl, cookieHeader);
}
if (hdVideoUrl && hdVideoUrl.includes("/api/video/redirect/")) {
hdVideoUrl = await resolveRedirectUrl(hdVideoUrl, cookieHeader);
}
if (wmVideoUrl && wmVideoUrl.includes("/api/video/redirect/")) {
wmVideoUrl = await resolveRedirectUrl(wmVideoUrl, cookieHeader);
}
const primaryVideoUrl = hdVideoUrl || nonwmVideoUrl || wmVideoUrl;
// 6. Resolusi galeri gambar / slideshow
let images = [];
if (Array.isArray(rawData.images) && rawData.images.length > 0) {
images = rawData.images.filter(Boolean);
} else if (Array.isArray(rawData.live_images) && rawData.live_images.length > 0) {
images = rawData.live_images.filter(Boolean);
}
// 7. Deteksi tipe konten akhir otomatis
const isProfile = rawData.videoCount !== undefined && !primaryVideoUrl && images.length === 0;
const isImageOrSlideshow =
rawData.data_type === "slideshow" ||
rawData.data_type === "image" ||
(images.length > 0 && !primaryVideoUrl);
let contentType = "video";
if (isProfile) {
contentType = "profile";
} else if (isImageOrSlideshow) {
contentType = images.length > 1 ? "slideshow" : "image";
} else if (rawData.data_type === "music" || (!primaryVideoUrl && rawData.musicURL)) {
contentType = "audio";
}
// 8. Susun struktur hasil yang super lengkap, rapi, dan siap pakai
const titleText = rawData.title || "";
const durationSec = rawData.duration || rawData.musicDuration || undefined;
const result = {
status: true,
platform: rawData.platform || platform,
contentType,
id: rawData.contentId || rawData._id || undefined,
title: titleText,
description: titleText,
hashtags: extractHashtags(titleText),
author: {
id: rawData.userId || undefined,
username: rawData.username || "",
nickname: rawData.nickname || rawData.username || "",
avatar: rawData.hdProfilePic || rawData.profilePic || undefined,
avatarThumb: rawData.profilePic || undefined,
profileUrl:
rawData.profileUrl ||
(rawData.username
? platform === "douyin"
? `https://www.douyin.com/user/${rawData.username}`
: platform === "lemon8"
? `https://www.lemon8-app.com/@${rawData.username}`
: `https://www.tiktok.com/@${rawData.username}`
: undefined),
},
stats: {
views: typeof rawData.views === "number" ? rawData.views : undefined,
likes: typeof rawData.like_count === "number" ? rawData.like_count : undefined,
comments: typeof rawData.comment_count === "number" ? rawData.comment_count : undefined,
shares: typeof rawData.share_count === "number" ? rawData.share_count : undefined,
videoCount: typeof rawData.videoCount === "number" ? rawData.videoCount : undefined,
formatted: {
views: formatNumber(rawData.views),
likes: formatNumber(rawData.like_count),
comments: formatNumber(rawData.comment_count),
shares: formatNumber(rawData.share_count),
videoCount: formatNumber(rawData.videoCount),
},
},
media: {
type: contentType,
duration: durationSec,
durationFormatted: formatDuration(durationSec),
video: primaryVideoUrl
? {
hd: hdVideoUrl || primaryVideoUrl,
nonwm: nonwmVideoUrl || primaryVideoUrl,
wm: wmVideoUrl || undefined,
sizes: {
hd: formatBytes(rawData.hdInfSize),
hdBytes: rawData.hdInfSize || undefined,
nonwm: formatBytes(rawData.infSize),
nonwmBytes: rawData.infSize || undefined,
wm: formatBytes(rawData.wmSize),
wmBytes: rawData.wmSize || undefined,
},
}
: undefined,
audio: rawData.musicURL
? {
id: rawData.musicId || undefined,
title: rawData.musicTitle ? decodeURIComponent(rawData.musicTitle) : "Original Sound",
duration: rawData.musicDuration || undefined,
durationFormatted: formatDuration(rawData.musicDuration),
url: rawData.musicURL,
}
: undefined,
images: images.length > 0 ? images : undefined,
totalImages: images.length > 0 ? images.length : undefined,
thumbnail: rawData.thumbnail || rawData.thumbnailOrigin || undefined,
cover: rawData.thumbnailOrigin || rawData.thumbnail || undefined,
dynamicCover: rawData.dynamicCover || undefined,
},
timestamps: {
timePosted: rawData.timePosted || undefined,
timePostedIso: rawData.timePosted ? new Date(rawData.timePosted).toISOString() : undefined,
fetchedAt: rawData.createdAt || new Date().toISOString(),
},
raw: {
contentId: rawData.contentId,
timePosted: rawData.timePosted,
region: rawData.region,
api: rawData.api,
processChains: rawData.processChains,
},
};
return result;
}
// Ekspor modul
if (typeof module !== "undefined" && module.exports) {
module.exports = {
scrapeVidgap,
getActionIds,
extractAndNormalize,
detectPlatform,
detectTab,
callFindContentAction,
waitForSocketData,
obtainDownloadCookies,
resolveRedirectUrl,
formatBytes,
formatNumber,
formatDuration,
extractHashtags,
};
}
// CLI Execution Handler
if (require.main === module) {
const inputArg = process.argv.slice(2).join(" ").trim();
if (!inputArg) {
console.log("==================================================================");
console.log(" VidGap Auto-Downloader (TikTok, Douyin, Lemon8)");
console.log(" Author: Vamz Spectre (VamxAPI)");
console.log("==================================================================");
console.log("Penggunaan:");
console.log(" node vidgap.js <link_atau_teks>\n");
console.log("Cukup masukkan tautan (semua dideteksi otomatis):");
console.log(' node vidgap.js "https://vt.tiktok.com/ZSxxxx/"');
console.log(' node vidgap.js "https://www.tiktok.com/@tiktok/video/7106594312292453675"');
console.log(' node vidgap.js "https://v.douyin.com/i8xxxx/"');
console.log(' node vidgap.js "https://s.lemon8-app.com/s/xxxx"');
console.log(' node vidgap.js "@tiktok"');
console.log(' node vidgap.js "Lihat ini https://vt.tiktok.com/ZSxxxx/ keren"\n');
process.exit(1);
}
scrapeVidgap(inputArg)
.then((result) => {
console.log(JSON.stringify(result, null, 2));
process.exit(0);
})
.catch((err) => {
console.error(
JSON.stringify(
{
status: false,
error: err.message || String(err),
},
null,
2
)
);
process.exit(1);
});
}