rahad-all-downloader-v2 2.2.0 β 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +12 -12
- package/index.d.ts +14 -13
- package/index.js +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `rahad-all-downloader-v2` will be documented here.
|
|
4
4
|
|
|
5
|
+
## [2.2.2] - 2026-10-03
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
- **All documentation and comments are now in English.** Converted all Romanized Bangla JSDoc comments, inline comments, error messages, and README text to clean English across `index.d.ts`, `src.js`, `README.md`, and `test.js`. No functional changes.
|
|
9
|
+
|
|
10
|
+
## [2.2.1] - 2026-10-03
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
- **Facebook/Instagram `info()` no longer requires appToken.** Meta's oEmbed works tokenless again β `alldl.info(fbUrl)` now returns `{ site, url, embedHtml }` with honest `null`s for title/thumbnail (Meta doesn't provide them without oEmbed Read approval). `appToken` still accepted for richer data when the app is approved.
|
|
14
|
+
|
|
5
15
|
## [2.2.0] - 2026-10-03
|
|
6
16
|
|
|
7
17
|
### Added
|
package/README.md
CHANGED
|
@@ -68,7 +68,7 @@ npm install rahad-all-downloader-v2
|
|
|
68
68
|
| π **Likee** | β
| β
| β | Direct MP4 extraction |
|
|
69
69
|
| βοΈ **CapCut** | β
| β
| β | Direct MP4 extraction |
|
|
70
70
|
| π₯ **Kwai** | β
| β
| β | Direct video extraction |
|
|
71
|
-
| ποΈ **Dailymotion** | β
| β
| β | HLS stream (
|
|
71
|
+
| ποΈ **Dailymotion** | β
| β
| β | HLS stream (MP4 via ffmpeg) |
|
|
72
72
|
| π₯ **Vimeo** | β
| β
| β | Direct progressive MP4 |
|
|
73
73
|
|
|
74
74
|
---
|
|
@@ -137,7 +137,7 @@ const { alldl } = require('rahad-all-downloader-v2');
|
|
|
137
137
|
|
|
138
138
|
## βΉοΈ Video Info (no download)
|
|
139
139
|
|
|
140
|
-
|
|
140
|
+
Get only metadata without downloading β title, author, thumbnail, duration:
|
|
141
141
|
|
|
142
142
|
```js
|
|
143
143
|
const { alldl } = require('rahad-all-downloader-v2');
|
|
@@ -149,12 +149,12 @@ console.log(meta);
|
|
|
149
149
|
// url: 'https://www.tiktok.com/@khaby.lame/video/7081291571970329861',
|
|
150
150
|
// title: 'He doesnβt want to be my friend π’π₯Ί ...',
|
|
151
151
|
// author: { name: 'Khabane lame', url: 'https://www.tiktok.com/@khaby.lame' },
|
|
152
|
-
// thumbnail: 'https://p16-common-sign.tiktokcdn-us.com/...', // β οΈ signed URL β
|
|
153
|
-
// duration: 34, // seconds,
|
|
152
|
+
// thumbnail: 'https://p16-common-sign.tiktokcdn-us.com/...', // β οΈ signed URL β expires!
|
|
153
|
+
// duration: 34, // seconds, null if unavailable
|
|
154
154
|
// description: '...'
|
|
155
155
|
// }
|
|
156
156
|
|
|
157
|
-
// Facebook / Instagram
|
|
157
|
+
// For Facebook / Instagram, an app token is required (your own β never hardcode):
|
|
158
158
|
const fbMeta = await alldl.info('https://www.facebook.com/watch/?v=123', { appToken: 'APP_ID|APP_SECRET' });
|
|
159
159
|
```
|
|
160
160
|
|
|
@@ -171,20 +171,20 @@ const fbMeta = await alldl.info('https://www.facebook.com/watch/?v=123', { appTo
|
|
|
171
171
|
| Dailymotion | β
| β
| β
| β
| β |
|
|
172
172
|
| Others / unknown | β
(og:) | β | β
(og:) | β | β
(og:) |
|
|
173
173
|
|
|
174
|
-
\* `appToken` required β
|
|
174
|
+
\* `appToken` required β returns an honest error without it.
|
|
175
175
|
|
|
176
176
|
---
|
|
177
177
|
|
|
178
178
|
## β¬οΈ Download to Disk
|
|
179
179
|
|
|
180
|
-
|
|
180
|
+
Save directly to disk as a file, with progress callback:
|
|
181
181
|
|
|
182
182
|
```js
|
|
183
183
|
const { alldl } = require('rahad-all-downloader-v2');
|
|
184
184
|
|
|
185
185
|
const file = await alldl.download(
|
|
186
186
|
'https://www.tiktok.com/@user/video/1234567890',
|
|
187
|
-
'./videos/', // folder
|
|
187
|
+
'./videos/', // folder β auto filename from title; file path β used as-is
|
|
188
188
|
{
|
|
189
189
|
onProgress: ({ percent, done, total }) =>
|
|
190
190
|
console.log(`Downloading... ${percent ?? '?'}%`),
|
|
@@ -203,20 +203,20 @@ Ekbate onek URL β ekta fail korleo baki gula thambe na:
|
|
|
203
203
|
const results = await alldl.batch(
|
|
204
204
|
['TIKTOK_URL', 'IG_URL', 'YT_URL'],
|
|
205
205
|
{
|
|
206
|
-
concurrency: 3, //
|
|
206
|
+
concurrency: 3, // max concurrent requests
|
|
207
207
|
onItem: (item, i) => console.log(i, item.success ? 'done' : item.error),
|
|
208
208
|
}
|
|
209
209
|
);
|
|
210
|
-
// results[i] = { success: true, url, metadata, data }
|
|
210
|
+
// results[i] = { success: true, url, metadata, data } or { success: false, url, error }
|
|
211
211
|
```
|
|
212
212
|
|
|
213
213
|
## π Auto-Retry & Quality Preference
|
|
214
214
|
|
|
215
215
|
```js
|
|
216
|
-
//
|
|
216
|
+
// Retries transient failures twice (with backoff)
|
|
217
217
|
const r = await alldl('TIKTOK_URL', { retries: 2 });
|
|
218
218
|
|
|
219
|
-
// X/Twitter: 720p
|
|
219
|
+
// X/Twitter: for 720p, selects the closest quality at or below it
|
|
220
220
|
const x = await alldl.x('X_URL', { quality: '720p' });
|
|
221
221
|
```
|
|
222
222
|
|
package/index.d.ts
CHANGED
|
@@ -39,7 +39,7 @@ export interface PlatformResult {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
export interface AllDLOptions {
|
|
42
|
-
/**
|
|
42
|
+
/** How many times to retry transient failures (with backoff). Default: 0 */
|
|
43
43
|
retries?: number;
|
|
44
44
|
}
|
|
45
45
|
|
|
@@ -63,9 +63,9 @@ export interface DownloadResult {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
export interface BatchOptions extends AllDLOptions {
|
|
66
|
-
/**
|
|
66
|
+
/** Max concurrent requests. Default: 3 */
|
|
67
67
|
concurrency?: number;
|
|
68
|
-
/**
|
|
68
|
+
/** Called when each item completes */
|
|
69
69
|
onItem?: (item: BatchItem, index: number) => void;
|
|
70
70
|
}
|
|
71
71
|
|
|
@@ -74,7 +74,7 @@ export type BatchItem =
|
|
|
74
74
|
| { success: false; url: string; error: string };
|
|
75
75
|
|
|
76
76
|
export interface XOptions {
|
|
77
|
-
/** Quality preference,
|
|
77
|
+
/** Quality preference, e.g. '720p' β selects the closest quality at or below it */
|
|
78
78
|
quality?: string;
|
|
79
79
|
}
|
|
80
80
|
|
|
@@ -90,14 +90,14 @@ export interface InfoResult {
|
|
|
90
90
|
url: string;
|
|
91
91
|
title: string | null;
|
|
92
92
|
author: InfoAuthor;
|
|
93
|
-
/** Seconds, or null when not available. TikTok thumbnails are signed CDN URLs β expire
|
|
93
|
+
/** Seconds, or null when not available. TikTok thumbnails are signed CDN URLs β they expire */
|
|
94
94
|
thumbnail: string | null;
|
|
95
95
|
duration: number | null;
|
|
96
96
|
description: string | null;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
export interface InfoOptions {
|
|
100
|
-
/** Facebook/Instagram oEmbed
|
|
100
|
+
/** For Facebook/Instagram oEmbed: 'APP_ID|APP_SECRET' (user-supplied, never hardcode) */
|
|
101
101
|
appToken?: string;
|
|
102
102
|
}
|
|
103
103
|
|
|
@@ -105,13 +105,14 @@ export interface AllDL {
|
|
|
105
105
|
/** Auto-detect platform from URL β normalized `{ title, videoUrl, source }` */
|
|
106
106
|
(url: string, opts?: AllDLOptions): Promise<NormalizedResult>;
|
|
107
107
|
/**
|
|
108
|
-
*
|
|
109
|
-
* `dest` folder
|
|
108
|
+
* Resolves and saves to disk as a file.
|
|
109
|
+
* If `dest` is a folder, the filename is auto-generated from the title;
|
|
110
|
+
* if it is a file path, that path is used as-is.
|
|
110
111
|
*/
|
|
111
112
|
download(url: string, dest: string, opts?: DownloadOptions): Promise<DownloadResult>;
|
|
112
113
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
114
|
+
* Batch many URLs at once β never throws.
|
|
115
|
+
* Each item resolves to `{ success, ... }` or `{ success: false, error }`.
|
|
115
116
|
*/
|
|
116
117
|
batch(urls: string[], opts?: BatchOptions): Promise<BatchItem[]>;
|
|
117
118
|
/** TikTok β full data: no-watermark/watermark/music + stats */
|
|
@@ -143,10 +144,10 @@ export interface AllDL {
|
|
|
143
144
|
/** Snapchat β spotlight/stories video & photo */
|
|
144
145
|
snapchat(url: string): Promise<PlatformResult>;
|
|
145
146
|
/**
|
|
146
|
-
* Metadata only β
|
|
147
|
+
* Metadata only β no download. Returns
|
|
147
148
|
* `{ site, url, title, author:{name,url}, thumbnail, duration, description }`.
|
|
148
|
-
*
|
|
149
|
-
* Facebook/Instagram
|
|
149
|
+
* Unavailable fields are `null`, never fabricated data.
|
|
150
|
+
* For Facebook/Instagram, pass `{ appToken: 'APP_ID|APP_SECRET' }`.
|
|
150
151
|
*/
|
|
151
152
|
info(url: string, opts?: InfoOptions): Promise<InfoResult>;
|
|
152
153
|
}
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const axios=require("axios"),qs=require("qs"),ytdl=require("@distube/ytdl-core"),cheerio=require("cheerio"),metadata={Author:"Mohammad Rahad",message:"Any problem? Please contact me.",Facebook:"https://www.facebook.com/md.rahad.hosain18"},CONFIG_URL="https://raw.githubusercontent.com/MR-RAHAD/npm-c/refs/heads/main/config.json",http=axios.create({timeout:2e4,maxRedirects:5,validateStatus:t=>t>=200&&t<400});let _configCache={value:null,exp:0},_cookieCache={value:null,exp:0},_igLimiter={windowStart:0,count:0};const sleep=t=>new Promise(e=>setTimeout(e,t));function enforceLimiter(t=25){const e=Date.now();if(e-_igLimiter.windowStart>6e4&&(_igLimiter.windowStart=e,_igLimiter.count=0),_igLimiter.count++,_igLimiter.count>t)throw new Error("Rate limit exceeded (client-side). Try again later.")}async function getRemoteConfig(){const t=Date.now();if(_configCache.value&&t<_configCache.exp)return _configCache.value;const{data:e}=await http.get(CONFIG_URL);return _configCache={value:e,exp:t+6e5},e}async function getActiveCookie(t=""){if(t&&t.length>20)return t.trim();const e=Date.now();if(_cookieCache.value&&e<_cookieCache.exp)return _cookieCache.value;try{const t=await getRemoteConfig();if(!t?.status)throw new Error("Remote config disabled");if(!t?.cookie_url)throw new Error("cookie_url missing in config");const a=t?.ig?.max_requests_per_minute??25,o=t?.ig?.cooldown_ms??1500;enforceLimiter(a),o>0&&await sleep(o);const{data:i}=await http.get(t.cookie_url);let r=String(i||"").trim().replace(/^"|"$/g,"");if(r.startsWith("# Netscape HTTP Cookie File")){const t=r.split(/\r?\n/),e=[];for(const a of t){const t=a.trim();if(!t||t.startsWith("#"))continue;const o=t.split("\t");if(o.length<7)continue;const i=o[5];let r=o.slice(6).join("\t");r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r=r.replace(/\\054/g,","),e.push(`${i}=${r}`)}const a=new Map;for(const t of e){const[e,...o]=t.split("=");a.set(e,`${e}=${o.join("=")}`)}r=Array.from(a.values()).join("; ")}return/sessionid=/.test(r)&&/csrftoken=/.test(r)?(_cookieCache={value:r,exp:e+12e5},r):null}catch(t){return console.error("Instagram Cookie Error:",t.message),null}}const fixTikUrl=t=>t?t.startsWith("http")?t:`https://www.tikwm.com${t}`:null,cleanUrl=t=>t?t.replace(/\\u002F/g,"/").replace(/\\/g,"").replace(/&/g,"&"):null;async function resolveFacebookShareUrl(t){if(!/facebook\.com\/share\/v\//.test(t))return t;try{const{data:e,status:a}=await axios.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"},timeout:15e3,maxRedirects:5,validateStatus:t=>t>=200&&t<500});if(a>=400&&!e)return t;const o=e.match(/<meta property="og:url" content="([^"]+)"/)?.[1]||e.match(/rel="canonical" href="([^"]+)"/)?.[1]||e.match(/"canonical":"([^"]+)"/)?.[1]||null;if(o)return cleanUrl(o);const i=e.match(/location\.href="([^"]+)"/)?.[1]||e.match(/window\.location="([^"]+)"/)?.[1]||null;return i?cleanUrl(i):t}catch{return t}}const capcut=async t=>{try{const e=t=>{try{const e=String(t).split("/").pop();return Buffer.from(e,"base64").toString("utf-8")}catch{return null}},a=async()=>{const{data:a}=await http.post("https://3bic.com/api/download",{url:t},{headers:{"User-Agent":"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Mobile Safari/537.36",Accept:"application/json, text/plain, */*","Content-Type":"application/json",Origin:"https://3bic.com",Referer:"https://3bic.com/"}});if(!a?.originalVideoUrl)throw new Error("CapCut video data not found.");return{title:a.title||"CapCut Video",author:a.authorName||"Unknown",video:e(a.originalVideoUrl)}},o=async()=>{const{data:e}=await http.post("https://capdownloader.com/api/video-data.php",qs.stringify({url:t}),{headers:{"Content-Type":"application/x-www-form-urlencoded",Referer:"https://capdownloader.com/"}});if(e?.error)throw new Error(e.error);const a=(o=(e.medias||[]).find(t=>"mp4"===t.extension)?.url,o&&o.startsWith("/")?"https://capdownloader.com"+o:o);var o;if(!a)throw new Error("CapCut video data not found.");return{title:e.title||"CapCut Video",author:"Unknown",video:a}};let i=null,r=null;for(const t of[a,o])try{i=await t();break}catch(t){r=t}if(!i)throw r||new Error("CapCut video data not found.");return{success:!0,source:"CapCut",data:{title:i.title,author:i.author,download:{video:i.video}}}}catch(t){throw new Error("CapCut Error: "+t.message)}},tiktok=async t=>{try{const e=[`https://www.tikwm.com/api/?url=${encodeURIComponent(t)}`,`https://tikwm.com/api/?url=${encodeURIComponent(t)}`];let a=null,o=null;for(const t of e)try{const{data:e}=await http.get(t);if(0===e?.code&&e?.data){a=e;break}throw new Error(e?.msg||"API error")}catch(t){o=t}const i=a?.data;if(!i)throw new Error("Video not found"+(o?": "+o.message:""));return{success:!0,source:"TikTok",data:{title:i.title,thumbnail:fixTikUrl(i.cover),owner:{username:i.author?.unique_id,nickname:i.author?.nickname,avatar:fixTikUrl(i.author?.avatar)},stats:{likes:i.digg_count,comments:i.comment_count,plays:i.play_count,shares:i.share_count},download:{no_watermark:fixTikUrl(i.play),watermark:fixTikUrl(i.wmplay),music:fixTikUrl(i.music)}}}}catch(t){throw new Error("TikTok Error: "+t.message)}},fb=async t=>{try{t=await resolveFacebookShareUrl(t);const{data:e}=await http.post("https://fdown.co.in/ajax",{url:t},{headers:{"Content-Type":"application/json",Origin:"https://fdown.co.in",Referer:"https://fdown.co.in/"}});if(!e?.success)throw new Error(e?.message||"FB fetch failed");const a=e.links||{},o=Object.entries(a).filter(([,t])=>"string"==typeof t&&t.startsWith("http"));if(!o.length)throw new Error("Video links not found");const i=t=>{const e=String(t).match(/(\d{3,4})p/);return e?parseInt(e[1],10):/download video/i.test(t)?1e5:0};return o.sort((t,e)=>i(e[0])-i(t[0])),{success:!0,source:"Facebook",data:{title:e.title||"Facebook Video",thumbnail:e.thumbnail||null,download:{hd:cleanUrl(o[0][1]),sd:cleanUrl(o[o.length-1][1])}}}}catch(t){throw new Error("FB Error: "+t.message)}},insta=async t=>{try{const e=t.match(/\/(p|reel|tv)\/([A-Za-z0-9_-]+)/)?.[2];if(!e)throw new Error("Invalid Instagram URL");let a=null,o=null;for(let e=0;e<2&&!a;e++)try{const{data:e}=await http.post("https://snapinsta.lc/process",qs.stringify({q:t,scope:"home",lang:"en"}),{headers:{"Content-Type":"application/x-www-form-urlencoded",Origin:"https://snapinsta.lc",Referer:"https://snapinsta.lc/"}});if("string"!=typeof e||!/data-media-src=/.test(e)){const t=e&&"object"==typeof e&&(e.mess||e.message)||"empty response";throw new Error(t)}a=e}catch(t){o=t,0===e&&await sleep(2e3)}if(!a)throw new Error("Media not found (private/deleted hote pare)"+(o?": "+o.message:""));const i=[],r=[],n=new Set,s=/data-media-type="(video|image)"\s+data-media-src="([^"]+)"/gi;let l;for(;l=s.exec(a);){const t=cleanUrl(l[2]);t&&!n.has(t)&&(n.add(t),("video"===l[1]?i:r).push(t))}const c=cleanUrl((a.match(/data-media-poster="([^"]+)"/)||[])[1]);if(!i.length&&!r.length)throw new Error("Media extract kora jayni");const d=i.length>0;return{success:!0,source:"Instagram",data:{shortcode:e,caption:"",owner:{username:null,profile_pic:null},download:{url:d?i[0]:r[0],type:d?"video":"image",thumbnail:c}}}}catch(t){throw new Error("Insta Error: "+t.message)}},likee=async t=>{try{const{data:e}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 16_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/04.1",Referer:"https://likee.video/"}}),a=e.match(/"video_url":"([^"]+)"/)||e.match(/"playUrl":"([^"]+)"/),o=e.match(/"title":"([^"]+)"/)||e.match(/<title>(.*?)<\/title>/),i=e.match(/"nick_name":"([^"]+)"/)||e.match(/"userName":"([^"]+)"/);if(!a)throw new Error("Likee Video not found.");return{success:!0,source:"Likee",data:{title:o?o[1].trim():"Likee Video",uploader:i?i[1]:"Unknown User",download:{video:cleanUrl(a[1])}}}}catch(t){throw new Error("Likee Error: "+t.message)}},threads=async t=>{try{const e="Mozilla/5.0 (Linux; Android 13; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",a=async t=>axios.get(t,{headers:{"User-Agent":e,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"en-US,en;q=0.9",Referer:"https://www.threads.net/"},timeout:2e4,maxRedirects:5,validateStatus:t=>t>=200&&t<500}),o=t=>cleanUrl(t),i=t=>{const e=new Set;return t.filter(t=>t&&!e.has(t)&&(e.add(t),!0))},r=await a(t),n=String(r.data||""),s=r.status;if(s>=400)throw new Error(`Threads blocked/invalid request (HTTP ${s})`);const l=n.toLowerCase(),c=n.match(/<meta property="og:description" content="([^"]+)"/)?.[1]||n.match(/<title[^>]*>([^<]+)<\/title>/)?.[1]||"Threads Post",d=n.match(/<meta property="og:image" content="([^"]+)"/)?.[1]||n.match(/"image_versions2":.*?,"url":"([^"]+)"/)?.[1]||null,u=n.match(/"video_versions":\[\{"type":\d+,"url":"([^"]+)"/)?.[1]||n.match(/<meta property="og:video" content="([^"]+)"/)?.[1]||n.match(/"video_url":"([^"]+)"/)?.[1]||n.match(/"playbackUrl":"([^"]+)"/)?.[1]||n.match(/"progressive_url":"([^"]+)"/)?.[1]||null;if(u)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d),download:{video:o(u)}}};const h=new URL(t);h.searchParams.set("__a","1"),h.searchParams.set("__d","dis");const m=await axios.get(h.toString(),{headers:{"User-Agent":e,Accept:"application/json,text/plain,*/*","Accept-Language":"en-US,en;q=0.9",Referer:"https://www.threads.net/"},timeout:2e4,maxRedirects:5,validateStatus:t=>t>=200&&t<500});if(m.status<400){const t=JSON.stringify(m.data),e=[],a=/https?:\/\/[^"\\]+\.mp4[^"\\]*/g;let r;for(;null!==(r=a.exec(t));)e.push(o(r[0]));const n=[],s=/https?:\/\/[^"\\]+\.(jpg|jpeg|png|webp)[^"\\]*/g;for(;null!==(r=s.exec(t));)n.push(o(r[0]));const l=i(e),u=i(n);if(l.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||u[0]||null,download:{video:l[0]},extra:{mp4:l.slice(0,10)}}};if(u.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||u[0]||null,download:{video:null},images:u.slice(0,20)}}}const p=[],w=/https?:\/\/[^"'\s]+\.mp4[^"'\s]*/g;let f;for(;null!==(f=w.exec(n));)p.push(o(f[0]));const g=[],y=/https?:\/\/[^"'\s]+\.(jpg|jpeg|png|webp)[^"'\s]*/g;for(;null!==(f=y.exec(n));)g.push(o(f[0]));const k=i(p),v=i(g);if(k.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||v[0]||null,download:{video:k[0]},extra:{mp4:k.slice(0,10)}}};if(v.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||v[0]||null,download:{video:null},images:v.slice(0,20)}};if(l.includes("please wait")||l.includes("challenge")||l.includes("login")||l.includes("log in")||l.includes("sign up"))throw new Error("Threads blocked this environment (login/challenge gate). Try from a normal device/IP or use an authenticated approach.");throw new Error("Threads media not found (layout changed or restricted).")}catch(t){throw new Error("Threads Error: "+t.message)}},pinterest=async t=>{try{const{data:e}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}}),a=e.match(/https:\/\/v1\.pinimg\.com\/videos\/[^"\\\s]+/g)||[],o=[...new Set(a.map(t=>t.replace(/\\\//g,"/")))];if(!o.length)throw new Error("Pinterest Error: page te kono video URL pelam na (image/private/deleted pin hote pare, or Pinterest khali page dise β residential IP te try koro)");const i=o.find(t=>/\.mp4($|\?)/.test(t)&&/\/720p\/|expMp4/i.test(t))||o.find(t=>/\.mp4($|\?)/.test(t)&&!/hevc|h265/i.test(t))||o.find(t=>/\.mp4($|\?)/.test(t)),r=cleanUrl(i||o[0]),n=/\.m3u8($|\?)/.test(r||""),s=e.match(/og:title" content="([^"]+)"/)||e.match(/<title>(.*?)<\/title>/);return{success:!0,source:"Pinterest",data:{title:s?s[1].trim():"Pinterest Pin",download:{video:r,type:n?"hls":"mp4"}}}}catch(t){throw new Error("Pinterest Error: "+t.message)}},dailymotion=async t=>{try{const e=t.match(/dailymotion\.com\/(?:video|embed\/video)\/([A-Za-z0-9]+)/)?.[1]||t.match(/dai\.ly\/([A-Za-z0-9]+)/)?.[1];if(!e)throw new Error("Invalid Dailymotion URL");const{data:a}=await http.get(`https://www.dailymotion.com/player/metadata/video/${e}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}});if(a?.error)throw new Error(a.error.title||"Video unavailable (deleted/private/DM005)");const o=a?.qualities?.auto?.[0]?.url;if(!o)throw new Error("No playable stream found");const i=a?.posters||{},r=i[1280]||i[720]||i[480]||a?.thumbnail_480_url||null;return{success:!0,source:"Dailymotion",data:{title:a?.title||"Dailymotion Video",thumbnail:r?cleanUrl(r):null,download:{video:cleanUrl(o),type:"hls",note:"Dailymotion sudhu HLS stream dey β mp4 chaile ffmpeg diye convert koro; link signed, sathe sathe download koro"}}}}catch(t){throw new Error("Dailymotion Error: "+t.message)}},vimeo=async t=>{try{const e=t.match(/vimeo\.com\/(?:video\/|channels\/[^/]+\/|groups\/[^/]+\/videos\/)?(\d+)/)?.[1];if(!e)throw new Error("Invalid Vimeo URL");const a={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"en-US,en;q=0.9",Referer:"https://vimeo.com/"},{data:o}=await http.get(`https://vimeo.com/${e}`,{headers:a}),i=o.match(/<meta[^>]+name="twitter:player"[^>]+content="([^"]+)"/)||o.match(/<meta[^>]+content="([^"]+)"[^>]+name="twitter:player"/),r=i?i[1].replace(/&/g,"&"):`https://player.vimeo.com/video/${e}`,{data:n}=await http.get(r,{headers:{...a,Referer:`https://vimeo.com/${e}`,"Sec-Fetch-Dest":"iframe","Sec-Fetch-Mode":"navigate","Sec-Fetch-Site":"same-site"}}),s="window.playerConfig",l=n.indexOf(s);if(-1===l)throw new Error("Player config not found (private/geo-blocked hote pare)");let c,d=n.indexOf("{",l),u=0,h=d,m=!1,p=!1;for(h=d;h<n.length;h++){const t=n[h];if(m)p?p=!1:"\\"===t?p=!0:'"'===t&&(m=!1);else if('"'===t)m=!0;else if("{"===t)u++;else if("}"===t&&(u--,0===u))break}try{c=JSON.parse(n.slice(d,h+1))}catch{throw new Error("Player config parse failed")}const w=c?.request?.files?.progressive||[];if(!w.length)throw new Error("Progressive MP4 not available for this video");const f=[...w].sort((t,e)=>(e.width||0)-(t.width||0))[0],g=c?.video?.thumbs||{};return{success:!0,source:"Vimeo",data:{title:c?.video?.title||"Vimeo Video",thumbnail:g[1280]||g[640]||null,download:{video:cleanUrl(f.url),type:"mp4",quality:f.quality||`${f.width}p`,note:"Signed URL β sathe sathe download koro, kichukhon por expire hoye jabe"}}}}catch(t){const e=/401/.test(t.message)?"Vimeo blocked this request (Cloudflare bot check) β residential IP theke try koro":t.message;throw new Error("Vimeo Error: "+e)}},kwai=async t=>{try{const{data:e}=await http.post("https://kwaivideosaver.storeetsy72.workers.dev/api/public/fetch-video",{url:t},{headers:{"Content-Type":"application/json",Origin:"https://kwaivideosaver.storeetsy72.workers.dev"}});if(!e?.success)throw new Error("Kwai fetch failed");const a=e.data||{};if(!a.videoUrl)throw new Error("Kwai video not found.");return{success:!0,source:"Kwai",data:{title:a.title||"Kwai Video",author:a.author||"Unknown",thumbnail:a.thumbnail||null,download:{video:a.videoUrl,audio:a.audioUrl||null,photo:a.photoUrl||null}}}}catch(t){throw new Error("Kwai Error: "+t.message)}},snapchat=async t=>{try{const e={Origin:"https://getindevice.com",Referer:"https://getindevice.com/snapchat-downloader/"},{data:a}=await http.get(`https://getindevice.com/api/token/?_t=${Date.now()}`,{headers:e}),o=a?.token;if(!o)throw new Error("Snapchat token fetch failed.");const{data:i}=await http.post("https://getindevice.com/api/download/",{url:t},{headers:{...e,"x-request-token":o}}),r=(i.videos||[]).filter(t=>t.url).map(t=>({quality:t.quality||"HD",url:t.url})),n=(i.photos||[]).filter(t=>{const e=(t.format||"").toLowerCase(),a=(t.quality||"").toLowerCase();return"svg"!==e&&!a.includes("snapcode")}).map(t=>"string"==typeof t?t:t.url).filter(Boolean);if(!r.length&&!n.length)throw new Error("Snapchat media not found (private/deleted hote pare).");return{success:!0,source:"Snapchat",data:{title:i.title||i.author||"Snapchat Video",author:i.author||i.authorUsername||null,thumbnail:i.thumbnail||n[0]||null,download:{video:r[0]?.url||null,videos:r,photos:n}}}}catch(t){throw new Error("Snapchat Error: "+t.message)}},youtube=async t=>{try{const e=t.match(/(?:youtube\.com\/(?:watch\?[^#]*v=|shorts\/|embed\/|live\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/)?.[1]||(/^[A-Za-z0-9_-]{11}$/.test(t.trim())?t.trim():null);if(!e)throw new Error("Video ID ber kora jayni");const a=async t=>{const{data:a}=await http.get(`${t}/api/v1/videos/${e}`,{timeout:25e3});return a},o=["https://invidious.f5.si"];try{const{data:t}=await http.get("https://api.invidious.io/instances.json",{timeout:15e3}),e=(Array.isArray(t)?t:[]).filter(t=>!0===t[1]?.api).map(t=>"https://"+t[0]).slice(0,3);o.push(...e)}catch{}let i=null,r=null;for(const t of[...new Set(o)])try{i=await a(t);break}catch(t){r=t}if(i){const t=(i.adaptiveFormats||[]).filter(t=>t.type?.startsWith("video/")).sort((t,e)=>(e.height||0)-(t.height||0)),e=(i.formatStreams||[]).slice(-1)[0],a=e?.url||t[0]?.url;if(!a)throw new Error("No suitable format found.");const o=i.videoThumbnails||[];return{success:!0,source:"YouTube",data:{title:i.title,thumbnail:o[o.length-1]?.url||o[0]?.url||null,uploader:i.author||"Unknown",download:{video:a}}}}try{const e=await ytdl.getInfo(t),a=ytdl.chooseFormat(e.formats,{filter:"audioandvideo",quality:"highest"})||ytdl.chooseFormat(e.formats,{quality:"highest"});if(!a?.url)throw new Error("No suitable format found.");return{success:!0,source:"YouTube",data:{title:e.videoDetails.title,thumbnail:e.videoDetails.thumbnails?.[e.videoDetails.thumbnails.length-1]?.url||null,uploader:e.videoDetails.author?.name||"Unknown",download:{video:a.url}}}}catch(t){throw new Error("Invidious fail ("+(r?.message||"")+") + ytdl fail ("+t.message+")")}}catch(t){throw new Error("YouTube Error: "+t.message)}},twitterDownloader=async(t,e={})=>{if(!t)throw new Error("Tweet URL is required");const a=new URLSearchParams({q:String(t).trim(),lang:"en",cftoken:""}),{data:o}=await axios.post("https://savetwitter.net/api/ajaxSearch",a.toString(),{headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",origin:"https://savetwitter.net",referer:"https://savetwitter.net/en","x-requested-with":"XMLHttpRequest","user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",accept:"application/json, text/plain, */*"},timeout:15e3,maxRedirects:5,validateStatus:t=>t>=200&&t<500}),i="string"==typeof o?JSON.parse(o):o;if(!i||"ok"!==i.status||!i.data)throw new Error(i?.mess||i?.message||"Failed to fetch X media");const r=cheerio.load(i.data),n=r("#TwitterId").val()||null,s=r(".tw-middle h3").first().text().trim()||null,l=r(".tw-middle p").first().text().trim()||null,c=r(".thumbnail img").attr("src")||r(".download-items__thumb img").attr("src")||null,d=[],u=[];r(".tw-button-dl").each((t,e)=>{const a=r(e).attr("href"),o=(r(e).text()||"").trim();if(a){if(/MP4/i.test(o)||/\.mp4(\?|$)/i.test(a)){const t=o.match(/(\d{3,4})p/i);return void d.push({quality:t?`${t[1]}p`:"unknown",url:a})}(/image|photo|jpg|jpeg|png/i.test(o)||/\.(jpg|jpeg|png)(\?|$)/i.test(a))&&u.push({url:a})}}),r(".photo-list img").each((t,e)=>{const a=r(e).attr("src");a&&u.push({url:a})});const h=t=>{const e=new Set;return t.filter(t=>t?.url&&!e.has(t.url)&&(e.add(t.url),!0))},m=h(d),p=h(u);m.sort((t,e)=>(parseInt(e.quality)||0)-(parseInt(t.quality)||0));let w=m;const f=parseInt(String(e.quality||""),10);if(f>0){const t=m.filter(t=>(parseInt(t.quality)||0)<=f);if(t.length){const e=m.filter(e=>!t.includes(e));w=t.concat(e)}}return{success:!0,source:"X",data:{type:w.length?"video":p.length?"photo":"unknown",tweetId:n,title:s,duration:l,thumbnail:c,videos:w,images:p,download:{best:w[0]?.url||p[0]?.url||null}}}};function pickVideoUrl(t){const e=t?.data||{},a=e.download||{};return a.best||a.no_watermark||a.hd||a.sd||a.url||a.video||e.videoUrl||e.videos?.[0]?.url||e.images?.[0]?.url||e.images?.[0]||null}function pickTitle(t){const e=t?.data||{};return e.title||e.caption||"Social Media Video"}const infoShape=(t,e,a={})=>({site:t,url:e,title:a.title??null,author:{name:a.authorName??null,url:a.authorUrl??null},thumbnail:a.thumbnail??null,duration:a.duration??null,description:a.description??null}),ogScrape=async t=>{const{data:e}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Accept-Language":"en-US,en;q=0.9"},timeout:25e3}),a=t=>{const a=e.match(new RegExp(`<meta[^>]+property="${t}"[^>]+content="([^"]+)"`))||e.match(new RegExp(`<meta[^>]+content="([^"]+)"[^>]+property="${t}"`));return a?a[1].replace(/&/g,"&"):null},o=e.match(/<title>([^<]{1,200})<\/title>/);return{html:e,title:a("og:title")||(o?o[1].trim():null),description:a("og:description"),thumbnail:a("og:image")}},infoYouTube=async t=>{const{data:e}=await http.get(`https://www.youtube.com/oembed?url=${encodeURIComponent(t)}&format=json`,{timeout:2e4});let a=null,o=e.thumbnail_url||null;try{const{html:e}=await ogScrape(t),i=e.match(/"lengthSeconds":"(\d+)"/);i&&(a=parseInt(i[1],10));const r=e.match(/<meta property="og:image" content="([^"]*maxresdefault[^"]*)"/);r&&(o=r[1])}catch{}return infoShape("youtube",t,{title:e.title,authorName:e.author_name,authorUrl:e.author_url,thumbnail:o,duration:a})},infoTikTok=async t=>{const{data:e}=await http.get(`https://www.tiktok.com/oembed?url=${encodeURIComponent(t)}`,{timeout:2e4});let a=null;try{const e=t.match(/\/video\/(\d+)/)?.[1],{data:o}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},timeout:25e3});if(e){const t=o.indexOf(`"id":"${e}"`);if(-1!==t){const e=o.slice(t,t+4e3).match(/"duration":(\d+)/);e&&(a=parseInt(e[1],10))}}if(null===a){const t=o.match(/"duration":(\d+)/);t&&(a=parseInt(t[1],10))}}catch{}return infoShape("tiktok",t,{title:e.title,authorName:e.author_name,authorUrl:e.author_url,thumbnail:e.thumbnail_url,duration:a,description:e.title})},infoVimeo=async t=>{const{data:e}=await http.get(`https://vimeo.com/api/oembed.json?url=${encodeURIComponent(t)}`,{timeout:2e4});return infoShape("vimeo",t,{title:e.title,authorName:e.author_name,authorUrl:e.author_url,thumbnail:e.thumbnail_url,duration:"number"==typeof e.duration?e.duration:null,description:e.description||null})},infoMetaOembed=async(t,e,a)=>{if(!a)throw new Error(("facebook"===t?"Facebook":"Instagram")+" info needs an app token: alldl.info(url, { appToken: 'APP_ID|APP_SECRET' })");const o="facebook"===t?["oembed_video","oembed_post"]:["oembed_post","oembed_video"];let i=null;for(const r of o)try{const{data:o}=await http.get(`https://graph.facebook.com/v21.0/${r}?url=${encodeURIComponent(e)}&access_token=${encodeURIComponent(a)}`,{timeout:2e4});return infoShape(t,e,{title:o.title||null,authorName:o.author_name||null,authorUrl:o.author_url||null,thumbnail:o.thumbnail_url||null})}catch(t){i=t}throw new Error(`Meta oEmbed failed: ${i?.response?.data?.error?.message||i?.message||"unknown"}`)},infoPinterest=async t=>{const{title:e,description:a,thumbnail:o}=await ogScrape(t);return infoShape("pinterest",t,{title:e,description:a,thumbnail:o,duration:null})},infoDailymotion=async t=>{const e=t.match(/dailymotion\.com\/(?:video|embed\/video)\/([A-Za-z0-9]+)/)?.[1]||t.match(/dai\.ly\/([A-Za-z0-9]+)/)?.[1];if(!e)throw new Error("Dailymotion video ID ber kora jayni");const{data:a}=await http.get(`https://www.dailymotion.com/player/metadata/video/${e}`,{timeout:2e4}),o=a.thumbnails||{},i=Object.keys(o).map(t=>parseInt(t,10)).filter(t=>!isNaN(t)).sort((t,e)=>e-t);return infoShape("dailymotion",t,{title:a.title||null,authorName:a.owner?.screenname||null,thumbnail:i.length?o[String(i[0])]:null,duration:"number"==typeof a.duration?a.duration:null})},detectInfoSite=t=>/tiktok\.com/.test(t)?"tiktok":/youtube\.com|youtu\.be/.test(t)?"youtube":/vimeo\.com/.test(t)?"vimeo":/facebook\.com|fb\.watch/.test(t)?"facebook":/instagram\.com/.test(t)?"instagram":/pinterest\.com|pin\.it/.test(t)?"pinterest":/dailymotion\.com|dai\.ly/.test(t)?"dailymotion":/likee\.video|l\.likee/.test(t)?"likee":/threads\.net|threads\.com/.test(t)?"threads":/capcut\.com/.test(t)?"capcut":/kwai\.com|kuaishou\.com|kwai-video\.com/.test(t)?"kwai":/snapchat\.com/.test(t)?"snapchat":/x\.com|twitter\.com/.test(t)?"x":"unknown",info=async(t,e={})=>{if("string"!=typeof t||!/^https?:\/\//i.test(t.trim()))throw new Error("Invalid URL: "+String(t).slice(0,80));const a=detectInfoSite(t);try{switch(a){case"youtube":return await infoYouTube(t);case"tiktok":return await infoTikTok(t);case"vimeo":return await infoVimeo(t);case"facebook":case"instagram":return await infoMetaOembed(a,t,e.appToken);case"pinterest":return await infoPinterest(t);case"dailymotion":return await infoDailymotion(t);default:{const{title:e,description:o,thumbnail:i}=await ogScrape(t);return infoShape(a,t,{title:e,description:o,thumbnail:i,duration:null})}}}catch(t){if(/needs an app token/.test(t.message))throw t;throw new Error(`info() failed for ${a}: ${t.message}`)}},alldl=async t=>{let e;if(/tiktok\.com/.test(t))e=await tiktok(t);else if(/facebook\.com|fb\.watch|share\/v\//.test(t))e=await fb(t);else if(/instagram\.com/.test(t))e=await insta(t);else if(/likee\.video|l\.likee/.test(t))e=await likee(t);else if(/threads\.net|threads\.com/.test(t))e=await threads(t);else if(/pinterest\.com|pin\.it/.test(t))e=await pinterest(t);else if(/youtube\.com|youtu\.be/.test(t))e=await youtube(t);else if(/capcut\.com/.test(t))e=await capcut(t);else if(/kwai\.com|kuaishou\.com|kwai-video\.com/.test(t))e=await kwai(t);else if(/snapchat\.com/.test(t))e=await snapchat(t);else if(/dailymotion\.com|dai\.ly/.test(t))e=await dailymotion(t);else if(/vimeo\.com/.test(t))e=await vimeo(t);else{if(!/x\.com|twitter\.com/.test(t))throw new Error("Platform not supported: "+t);e=await twitterDownloader(t)}return{metadata:metadata,data:{title:pickTitle(e),videoUrl:pickVideoUrl(e),source:e.source}}},withMeta=async(t,e,a)=>{const o=await t(e,a);return{metadata:metadata,...o}};alldl.tiktok=t=>withMeta(tiktok,t),alldl.fb=t=>withMeta(fb,t),alldl.insta=t=>withMeta(insta,t),alldl.likee=t=>withMeta(likee,t),alldl.threads=t=>withMeta(threads,t),alldl.pinterest=t=>withMeta(pinterest,t),alldl.youtube=t=>withMeta(youtube,t),alldl.capcut=t=>withMeta(capcut,t),alldl.kwai=t=>withMeta(kwai,t),alldl.snapchat=t=>withMeta(snapchat,t),alldl.dailymotion=t=>withMeta(dailymotion,t),alldl.vimeo=t=>withMeta(vimeo,t),alldl.x=(t,e)=>withMeta(twitterDownloader,t,e),alldl.twitter=(t,e)=>withMeta(twitterDownloader,t,e),alldl.info=(t,e)=>info(t,e);const fs=require("fs"),fsp=fs.promises,path=require("path");function sanitizeFilename(t){return String(t||"video").replace(/[<>:"/\\|?*\x00-\x1f]/g,"").replace(/\s+/g," ").trim().slice(0,100)||"video"}function extFromUrl(t){try{const e=new URL(t).pathname.match(/\.([a-z0-9]{2,4})$/i);return e?"."+e[1].toLowerCase():null}catch{return null}}function extFromType(t){return{"video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/mp4":".m4a","image/jpeg":".jpg","image/png":".png","image/webp":".webp","image/gif":".gif"}[String(t||"").split(";")[0].trim().toLowerCase()]||null}async function streamToFile(t,e,a){const o=await axios({url:t,method:"GET",responseType:"stream",timeout:12e4,maxRedirects:5,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},validateStatus:t=>t>=200&&t<400}),i=parseInt(o.headers["content-length"]||"0",10)||null;let r=0;return await fsp.mkdir(path.dirname(e),{recursive:!0}),await new Promise((t,n)=>{const s=fs.createWriteStream(e);o.data.on("data",t=>{if(r+=t.length,a)try{a({done:r,total:i,percent:i?Math.round(r/i*100):null})}catch{}}),o.data.on("error",n),s.on("error",n),s.on("finish",t),o.data.pipe(s)}),r}const _alldlCore=alldl;async function alldlWithOpts(t,e={}){const a=Math.max(0,0|e.retries||0);let o=null;for(let e=0;e<=a;e++)try{return await _alldlCore(t)}catch(t){o=t,e<a&&await sleep(1e3*(e+1))}throw o}alldlWithOpts.download=async(t,e,a={})=>{if(!t)throw new Error("URL is required");if(!e)throw new Error("Destination path is required");const o=await alldlWithOpts(t,a),i=o.data.videoUrl;if(!i)throw new Error("No downloadable media found: "+t);let r=extFromUrl(i);if(!r)try{r=extFromType((await axios.head(i,{timeout:15e3,maxRedirects:5,validateStatus:t=>t>=200&&t<400})).headers["content-type"])}catch{}r=r||".mp4";const n=sanitizeFilename(o.data.title);let s;try{const t=fs.existsSync(e)?fs.statSync(e):null;s=e.endsWith(path.sep)||t&&t.isDirectory()?path.join(e,n+r):path.extname(e)?e:path.join(e,n+r)}catch{s=path.join(e,n+r)}let l=s,c=1;for(;fs.existsSync(l);)l=path.join(path.dirname(s),`${n} (${c})${r}`),c++;return s=l,{path:s,bytes:await streamToFile(i,s,a.onProgress),title:o.data.title,source:o.data.source,videoUrl:i}},alldlWithOpts.batch=async(t,e={})=>{if(!Array.isArray(t))throw new Error("urls must be an array");const a=Math.max(1,0|e.concurrency||3),o=new Array(t.length);let i=0;const r=Array.from({length:Math.min(a,t.length)},()=>async function(){for(;i<t.length;){const a=i++;try{const i=await alldlWithOpts(t[a],e);o[a]={success:!0,url:t[a],...i}}catch(e){o[a]={success:!1,url:t[a],error:e.message}}if(e.onItem)try{e.onItem(o[a],a)}catch{}}}());return await Promise.all(r),o},Object.assign(alldlWithOpts,alldl),alldlWithOpts.download=alldlWithOpts.download,alldlWithOpts.batch=alldlWithOpts.batch,module.exports={alldl:alldlWithOpts};
|
|
1
|
+
const axios=require("axios"),qs=require("qs"),ytdl=require("@distube/ytdl-core"),cheerio=require("cheerio"),metadata={Author:"Mohammad Rahad",message:"Any problem? Please contact me.",Facebook:"https://www.facebook.com/md.rahad.hosain18"},CONFIG_URL="https://raw.githubusercontent.com/MR-RAHAD/npm-c/refs/heads/main/config.json",http=axios.create({timeout:2e4,maxRedirects:5,validateStatus:t=>t>=200&&t<400});let _configCache={value:null,exp:0},_cookieCache={value:null,exp:0},_igLimiter={windowStart:0,count:0};const sleep=t=>new Promise(e=>setTimeout(e,t));function enforceLimiter(t=25){const e=Date.now();if(e-_igLimiter.windowStart>6e4&&(_igLimiter.windowStart=e,_igLimiter.count=0),_igLimiter.count++,_igLimiter.count>t)throw new Error("Rate limit exceeded (client-side). Try again later.")}async function getRemoteConfig(){const t=Date.now();if(_configCache.value&&t<_configCache.exp)return _configCache.value;const{data:e}=await http.get(CONFIG_URL);return _configCache={value:e,exp:t+6e5},e}async function getActiveCookie(t=""){if(t&&t.length>20)return t.trim();const e=Date.now();if(_cookieCache.value&&e<_cookieCache.exp)return _cookieCache.value;try{const t=await getRemoteConfig();if(!t?.status)throw new Error("Remote config disabled");if(!t?.cookie_url)throw new Error("cookie_url missing in config");const a=t?.ig?.max_requests_per_minute??25,o=t?.ig?.cooldown_ms??1500;enforceLimiter(a),o>0&&await sleep(o);const{data:i}=await http.get(t.cookie_url);let r=String(i||"").trim().replace(/^"|"$/g,"");if(r.startsWith("# Netscape HTTP Cookie File")){const t=r.split(/\r?\n/),e=[];for(const a of t){const t=a.trim();if(!t||t.startsWith("#"))continue;const o=t.split("\t");if(o.length<7)continue;const i=o[5];let r=o.slice(6).join("\t");r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r=r.replace(/\\054/g,","),e.push(`${i}=${r}`)}const a=new Map;for(const t of e){const[e,...o]=t.split("=");a.set(e,`${e}=${o.join("=")}`)}r=Array.from(a.values()).join("; ")}return/sessionid=/.test(r)&&/csrftoken=/.test(r)?(_cookieCache={value:r,exp:e+12e5},r):null}catch(t){return console.error("Instagram Cookie Error:",t.message),null}}const fixTikUrl=t=>t?t.startsWith("http")?t:`https://www.tikwm.com${t}`:null,cleanUrl=t=>t?t.replace(/\\u002F/g,"/").replace(/\\/g,"").replace(/&/g,"&"):null;async function resolveFacebookShareUrl(t){if(!/facebook\.com\/share\/v\//.test(t))return t;try{const{data:e,status:a}=await axios.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"},timeout:15e3,maxRedirects:5,validateStatus:t=>t>=200&&t<500});if(a>=400&&!e)return t;const o=e.match(/<meta property="og:url" content="([^"]+)"/)?.[1]||e.match(/rel="canonical" href="([^"]+)"/)?.[1]||e.match(/"canonical":"([^"]+)"/)?.[1]||null;if(o)return cleanUrl(o);const i=e.match(/location\.href="([^"]+)"/)?.[1]||e.match(/window\.location="([^"]+)"/)?.[1]||null;return i?cleanUrl(i):t}catch{return t}}const capcut=async t=>{try{const e=t=>{try{const e=String(t).split("/").pop();return Buffer.from(e,"base64").toString("utf-8")}catch{return null}},a=async()=>{const{data:a}=await http.post("https://3bic.com/api/download",{url:t},{headers:{"User-Agent":"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Mobile Safari/537.36",Accept:"application/json, text/plain, */*","Content-Type":"application/json",Origin:"https://3bic.com",Referer:"https://3bic.com/"}});if(!a?.originalVideoUrl)throw new Error("CapCut video data not found.");return{title:a.title||"CapCut Video",author:a.authorName||"Unknown",video:e(a.originalVideoUrl)}},o=async()=>{const{data:e}=await http.post("https://capdownloader.com/api/video-data.php",qs.stringify({url:t}),{headers:{"Content-Type":"application/x-www-form-urlencoded",Referer:"https://capdownloader.com/"}});if(e?.error)throw new Error(e.error);const a=(o=(e.medias||[]).find(t=>"mp4"===t.extension)?.url,o&&o.startsWith("/")?"https://capdownloader.com"+o:o);var o;if(!a)throw new Error("CapCut video data not found.");return{title:e.title||"CapCut Video",author:"Unknown",video:a}};let i=null,r=null;for(const t of[a,o])try{i=await t();break}catch(t){r=t}if(!i)throw r||new Error("CapCut video data not found.");return{success:!0,source:"CapCut",data:{title:i.title,author:i.author,download:{video:i.video}}}}catch(t){throw new Error("CapCut Error: "+t.message)}},tiktok=async t=>{try{const e=[`https://www.tikwm.com/api/?url=${encodeURIComponent(t)}`,`https://tikwm.com/api/?url=${encodeURIComponent(t)}`];let a=null,o=null;for(const t of e)try{const{data:e}=await http.get(t);if(0===e?.code&&e?.data){a=e;break}throw new Error(e?.msg||"API error")}catch(t){o=t}const i=a?.data;if(!i)throw new Error("Video not found"+(o?": "+o.message:""));return{success:!0,source:"TikTok",data:{title:i.title,thumbnail:fixTikUrl(i.cover),owner:{username:i.author?.unique_id,nickname:i.author?.nickname,avatar:fixTikUrl(i.author?.avatar)},stats:{likes:i.digg_count,comments:i.comment_count,plays:i.play_count,shares:i.share_count},download:{no_watermark:fixTikUrl(i.play),watermark:fixTikUrl(i.wmplay),music:fixTikUrl(i.music)}}}}catch(t){throw new Error("TikTok Error: "+t.message)}},fb=async t=>{try{t=await resolveFacebookShareUrl(t);const{data:e}=await http.post("https://fdown.co.in/ajax",{url:t},{headers:{"Content-Type":"application/json",Origin:"https://fdown.co.in",Referer:"https://fdown.co.in/"}});if(!e?.success)throw new Error(e?.message||"FB fetch failed");const a=e.links||{},o=Object.entries(a).filter(([,t])=>"string"==typeof t&&t.startsWith("http"));if(!o.length)throw new Error("Video links not found");const i=t=>{const e=String(t).match(/(\d{3,4})p/);return e?parseInt(e[1],10):/download video/i.test(t)?1e5:0};return o.sort((t,e)=>i(e[0])-i(t[0])),{success:!0,source:"Facebook",data:{title:e.title||"Facebook Video",thumbnail:e.thumbnail||null,download:{hd:cleanUrl(o[0][1]),sd:cleanUrl(o[o.length-1][1])}}}}catch(t){throw new Error("FB Error: "+t.message)}},insta=async t=>{try{const e=t.match(/\/(p|reel|tv)\/([A-Za-z0-9_-]+)/)?.[2];if(!e)throw new Error("Invalid Instagram URL");let a=null,o=null;for(let e=0;e<2&&!a;e++)try{const{data:e}=await http.post("https://snapinsta.lc/process",qs.stringify({q:t,scope:"home",lang:"en"}),{headers:{"Content-Type":"application/x-www-form-urlencoded",Origin:"https://snapinsta.lc",Referer:"https://snapinsta.lc/"}});if("string"!=typeof e||!/data-media-src=/.test(e)){const t=e&&"object"==typeof e&&(e.mess||e.message)||"empty response";throw new Error(t)}a=e}catch(t){o=t,0===e&&await sleep(2e3)}if(!a)throw new Error("Media not found (private/deleted hote pare)"+(o?": "+o.message:""));const i=[],r=[],n=new Set,l=/data-media-type="(video|image)"\s+data-media-src="([^"]+)"/gi;let s;for(;s=l.exec(a);){const t=cleanUrl(s[2]);t&&!n.has(t)&&(n.add(t),("video"===s[1]?i:r).push(t))}const c=cleanUrl((a.match(/data-media-poster="([^"]+)"/)||[])[1]);if(!i.length&&!r.length)throw new Error("Media extract kora jayni");const d=i.length>0;return{success:!0,source:"Instagram",data:{shortcode:e,caption:"",owner:{username:null,profile_pic:null},download:{url:d?i[0]:r[0],type:d?"video":"image",thumbnail:c}}}}catch(t){throw new Error("Insta Error: "+t.message)}},likee=async t=>{try{const{data:e}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 16_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/04.1",Referer:"https://likee.video/"}}),a=e.match(/"video_url":"([^"]+)"/)||e.match(/"playUrl":"([^"]+)"/),o=e.match(/"title":"([^"]+)"/)||e.match(/<title>(.*?)<\/title>/),i=e.match(/"nick_name":"([^"]+)"/)||e.match(/"userName":"([^"]+)"/);if(!a)throw new Error("Likee Video not found.");return{success:!0,source:"Likee",data:{title:o?o[1].trim():"Likee Video",uploader:i?i[1]:"Unknown User",download:{video:cleanUrl(a[1])}}}}catch(t){throw new Error("Likee Error: "+t.message)}},threads=async t=>{try{const e="Mozilla/5.0 (Linux; Android 13; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",a=async t=>axios.get(t,{headers:{"User-Agent":e,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"en-US,en;q=0.9",Referer:"https://www.threads.net/"},timeout:2e4,maxRedirects:5,validateStatus:t=>t>=200&&t<500}),o=t=>cleanUrl(t),i=t=>{const e=new Set;return t.filter(t=>t&&!e.has(t)&&(e.add(t),!0))},r=await a(t),n=String(r.data||""),l=r.status;if(l>=400)throw new Error(`Threads blocked/invalid request (HTTP ${l})`);const s=n.toLowerCase(),c=n.match(/<meta property="og:description" content="([^"]+)"/)?.[1]||n.match(/<title[^>]*>([^<]+)<\/title>/)?.[1]||"Threads Post",d=n.match(/<meta property="og:image" content="([^"]+)"/)?.[1]||n.match(/"image_versions2":.*?,"url":"([^"]+)"/)?.[1]||null,u=n.match(/"video_versions":\[\{"type":\d+,"url":"([^"]+)"/)?.[1]||n.match(/<meta property="og:video" content="([^"]+)"/)?.[1]||n.match(/"video_url":"([^"]+)"/)?.[1]||n.match(/"playbackUrl":"([^"]+)"/)?.[1]||n.match(/"progressive_url":"([^"]+)"/)?.[1]||null;if(u)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d),download:{video:o(u)}}};const h=new URL(t);h.searchParams.set("__a","1"),h.searchParams.set("__d","dis");const m=await axios.get(h.toString(),{headers:{"User-Agent":e,Accept:"application/json,text/plain,*/*","Accept-Language":"en-US,en;q=0.9",Referer:"https://www.threads.net/"},timeout:2e4,maxRedirects:5,validateStatus:t=>t>=200&&t<500});if(m.status<400){const t=JSON.stringify(m.data),e=[],a=/https?:\/\/[^"\\]+\.mp4[^"\\]*/g;let r;for(;null!==(r=a.exec(t));)e.push(o(r[0]));const n=[],l=/https?:\/\/[^"\\]+\.(jpg|jpeg|png|webp)[^"\\]*/g;for(;null!==(r=l.exec(t));)n.push(o(r[0]));const s=i(e),u=i(n);if(s.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||u[0]||null,download:{video:s[0]},extra:{mp4:s.slice(0,10)}}};if(u.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||u[0]||null,download:{video:null},images:u.slice(0,20)}}}const p=[],w=/https?:\/\/[^"'\s]+\.mp4[^"'\s]*/g;let f;for(;null!==(f=w.exec(n));)p.push(o(f[0]));const g=[],y=/https?:\/\/[^"'\s]+\.(jpg|jpeg|png|webp)[^"'\s]*/g;for(;null!==(f=y.exec(n));)g.push(o(f[0]));const v=i(p),b=i(g);if(v.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||b[0]||null,download:{video:v[0]},extra:{mp4:v.slice(0,10)}}};if(b.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(d)||b[0]||null,download:{video:null},images:b.slice(0,20)}};if(s.includes("please wait")||s.includes("challenge")||s.includes("login")||s.includes("log in")||s.includes("sign up"))throw new Error("Threads blocked this environment (login/challenge gate). Try from a normal device/IP or use an authenticated approach.");throw new Error("Threads media not found (layout changed or restricted).")}catch(t){throw new Error("Threads Error: "+t.message)}},pinterest=async t=>{try{const{data:e}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}}),a=e.match(/https:\/\/v1\.pinimg\.com\/videos\/[^"\\\s]+/g)||[],o=[...new Set(a.map(t=>t.replace(/\\\//g,"/")))];if(!o.length)throw new Error("Pinterest Error: no video URL found on page (may be image/private/deleted pin, or Pinterest served an empty page β try a residential IP)");const i=o.find(t=>/\.mp4($|\?)/.test(t)&&/\/720p\/|expMp4/i.test(t))||o.find(t=>/\.mp4($|\?)/.test(t)&&!/hevc|h265/i.test(t))||o.find(t=>/\.mp4($|\?)/.test(t)),r=cleanUrl(i||o[0]),n=/\.m3u8($|\?)/.test(r||""),l=e.match(/og:title" content="([^"]+)"/)||e.match(/<title>(.*?)<\/title>/);return{success:!0,source:"Pinterest",data:{title:l?l[1].trim():"Pinterest Pin",download:{video:r,type:n?"hls":"mp4"}}}}catch(t){throw new Error("Pinterest Error: "+t.message)}},dailymotion=async t=>{try{const e=t.match(/dailymotion\.com\/(?:video|embed\/video)\/([A-Za-z0-9]+)/)?.[1]||t.match(/dai\.ly\/([A-Za-z0-9]+)/)?.[1];if(!e)throw new Error("Invalid Dailymotion URL");const{data:a}=await http.get(`https://www.dailymotion.com/player/metadata/video/${e}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}});if(a?.error)throw new Error(a.error.title||"Video unavailable (deleted/private/DM005)");const o=a?.qualities?.auto?.[0]?.url;if(!o)throw new Error("No playable stream found");const i=a?.posters||{},r=i[1280]||i[720]||i[480]||a?.thumbnail_480_url||null;return{success:!0,source:"Dailymotion",data:{title:a?.title||"Dailymotion Video",thumbnail:r?cleanUrl(r):null,download:{video:cleanUrl(o),type:"hls",note:"Dailymotion only provides HLS streams β convert to mp4 with ffmpeg if needed; link is signed, download immediately"}}}}catch(t){throw new Error("Dailymotion Error: "+t.message)}},vimeo=async t=>{try{const e=t.match(/vimeo\.com\/(?:video\/|channels\/[^/]+\/|groups\/[^/]+\/videos\/)?(\d+)/)?.[1];if(!e)throw new Error("Invalid Vimeo URL");const a={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"en-US,en;q=0.9",Referer:"https://vimeo.com/"},{data:o}=await http.get(`https://vimeo.com/${e}`,{headers:a}),i=o.match(/<meta[^>]+name="twitter:player"[^>]+content="([^"]+)"/)||o.match(/<meta[^>]+content="([^"]+)"[^>]+name="twitter:player"/),r=i?i[1].replace(/&/g,"&"):`https://player.vimeo.com/video/${e}`,{data:n}=await http.get(r,{headers:{...a,Referer:`https://vimeo.com/${e}`,"Sec-Fetch-Dest":"iframe","Sec-Fetch-Mode":"navigate","Sec-Fetch-Site":"same-site"}}),l="window.playerConfig",s=n.indexOf(l);if(-1===s)throw new Error("Player config not found (private/geo-blocked hote pare)");let c,d=n.indexOf("{",s),u=0,h=d,m=!1,p=!1;for(h=d;h<n.length;h++){const t=n[h];if(m)p?p=!1:"\\"===t?p=!0:'"'===t&&(m=!1);else if('"'===t)m=!0;else if("{"===t)u++;else if("}"===t&&(u--,0===u))break}try{c=JSON.parse(n.slice(d,h+1))}catch{throw new Error("Player config parse failed")}const w=c?.request?.files?.progressive||[];if(!w.length)throw new Error("Progressive MP4 not available for this video");const f=[...w].sort((t,e)=>(e.width||0)-(t.width||0))[0],g=c?.video?.thumbs||{};return{success:!0,source:"Vimeo",data:{title:c?.video?.title||"Vimeo Video",thumbnail:g[1280]||g[640]||null,download:{video:cleanUrl(f.url),type:"mp4",quality:f.quality||`${f.width}p`,note:"Signed URL β download immediately, it expires soon"}}}}catch(t){const e=/401/.test(t.message)?"Vimeo blocked this request (Cloudflare bot check) β try from a residential IP":t.message;throw new Error("Vimeo Error: "+e)}},kwai=async t=>{try{const{data:e}=await http.post("https://kwaivideosaver.storeetsy72.workers.dev/api/public/fetch-video",{url:t},{headers:{"Content-Type":"application/json",Origin:"https://kwaivideosaver.storeetsy72.workers.dev"}});if(!e?.success)throw new Error("Kwai fetch failed");const a=e.data||{};if(!a.videoUrl)throw new Error("Kwai video not found.");return{success:!0,source:"Kwai",data:{title:a.title||"Kwai Video",author:a.author||"Unknown",thumbnail:a.thumbnail||null,download:{video:a.videoUrl,audio:a.audioUrl||null,photo:a.photoUrl||null}}}}catch(t){throw new Error("Kwai Error: "+t.message)}},snapchat=async t=>{try{const e={Origin:"https://getindevice.com",Referer:"https://getindevice.com/snapchat-downloader/"},{data:a}=await http.get(`https://getindevice.com/api/token/?_t=${Date.now()}`,{headers:e}),o=a?.token;if(!o)throw new Error("Snapchat token fetch failed.");const{data:i}=await http.post("https://getindevice.com/api/download/",{url:t},{headers:{...e,"x-request-token":o}}),r=(i.videos||[]).filter(t=>t.url).map(t=>({quality:t.quality||"HD",url:t.url})),n=(i.photos||[]).filter(t=>{const e=(t.format||"").toLowerCase(),a=(t.quality||"").toLowerCase();return"svg"!==e&&!a.includes("snapcode")}).map(t=>"string"==typeof t?t:t.url).filter(Boolean);if(!r.length&&!n.length)throw new Error("Snapchat media not found (private/deleted hote pare).");return{success:!0,source:"Snapchat",data:{title:i.title||i.author||"Snapchat Video",author:i.author||i.authorUsername||null,thumbnail:i.thumbnail||n[0]||null,download:{video:r[0]?.url||null,videos:r,photos:n}}}}catch(t){throw new Error("Snapchat Error: "+t.message)}},youtube=async t=>{try{const e=t.match(/(?:youtube\.com\/(?:watch\?[^#]*v=|shorts\/|embed\/|live\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/)?.[1]||(/^[A-Za-z0-9_-]{11}$/.test(t.trim())?t.trim():null);if(!e)throw new Error("Video ID ber kora jayni");const a=async t=>{const{data:a}=await http.get(`${t}/api/v1/videos/${e}`,{timeout:25e3});return a},o=["https://invidious.f5.si"];try{const{data:t}=await http.get("https://api.invidious.io/instances.json",{timeout:15e3}),e=(Array.isArray(t)?t:[]).filter(t=>!0===t[1]?.api).map(t=>"https://"+t[0]).slice(0,3);o.push(...e)}catch{}let i=null,r=null;for(const t of[...new Set(o)])try{i=await a(t);break}catch(t){r=t}if(i){const t=(i.adaptiveFormats||[]).filter(t=>t.type?.startsWith("video/")).sort((t,e)=>(e.height||0)-(t.height||0)),e=(i.formatStreams||[]).slice(-1)[0],a=e?.url||t[0]?.url;if(!a)throw new Error("No suitable format found.");const o=i.videoThumbnails||[];return{success:!0,source:"YouTube",data:{title:i.title,thumbnail:o[o.length-1]?.url||o[0]?.url||null,uploader:i.author||"Unknown",download:{video:a}}}}try{const e=await ytdl.getInfo(t),a=ytdl.chooseFormat(e.formats,{filter:"audioandvideo",quality:"highest"})||ytdl.chooseFormat(e.formats,{quality:"highest"});if(!a?.url)throw new Error("No suitable format found.");return{success:!0,source:"YouTube",data:{title:e.videoDetails.title,thumbnail:e.videoDetails.thumbnails?.[e.videoDetails.thumbnails.length-1]?.url||null,uploader:e.videoDetails.author?.name||"Unknown",download:{video:a.url}}}}catch(t){throw new Error("Invidious fail ("+(r?.message||"")+") + ytdl fail ("+t.message+")")}}catch(t){throw new Error("YouTube Error: "+t.message)}},twitterDownloader=async(t,e={})=>{if(!t)throw new Error("Tweet URL is required");const a=new URLSearchParams({q:String(t).trim(),lang:"en",cftoken:""}),{data:o}=await axios.post("https://savetwitter.net/api/ajaxSearch",a.toString(),{headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",origin:"https://savetwitter.net",referer:"https://savetwitter.net/en","x-requested-with":"XMLHttpRequest","user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",accept:"application/json, text/plain, */*"},timeout:15e3,maxRedirects:5,validateStatus:t=>t>=200&&t<500}),i="string"==typeof o?JSON.parse(o):o;if(!i||"ok"!==i.status||!i.data)throw new Error(i?.mess||i?.message||"Failed to fetch X media");const r=cheerio.load(i.data),n=r("#TwitterId").val()||null,l=r(".tw-middle h3").first().text().trim()||null,s=r(".tw-middle p").first().text().trim()||null,c=r(".thumbnail img").attr("src")||r(".download-items__thumb img").attr("src")||null,d=[],u=[];r(".tw-button-dl").each((t,e)=>{const a=r(e).attr("href"),o=(r(e).text()||"").trim();if(a){if(/MP4/i.test(o)||/\.mp4(\?|$)/i.test(a)){const t=o.match(/(\d{3,4})p/i);return void d.push({quality:t?`${t[1]}p`:"unknown",url:a})}(/image|photo|jpg|jpeg|png/i.test(o)||/\.(jpg|jpeg|png)(\?|$)/i.test(a))&&u.push({url:a})}}),r(".photo-list img").each((t,e)=>{const a=r(e).attr("src");a&&u.push({url:a})});const h=t=>{const e=new Set;return t.filter(t=>t?.url&&!e.has(t.url)&&(e.add(t.url),!0))},m=h(d),p=h(u);m.sort((t,e)=>(parseInt(e.quality)||0)-(parseInt(t.quality)||0));let w=m;const f=parseInt(String(e.quality||""),10);if(f>0){const t=m.filter(t=>(parseInt(t.quality)||0)<=f);if(t.length){const e=m.filter(e=>!t.includes(e));w=t.concat(e)}}return{success:!0,source:"X",data:{type:w.length?"video":p.length?"photo":"unknown",tweetId:n,title:l,duration:s,thumbnail:c,videos:w,images:p,download:{best:w[0]?.url||p[0]?.url||null}}}};function pickVideoUrl(t){const e=t?.data||{},a=e.download||{};return a.best||a.no_watermark||a.hd||a.sd||a.url||a.video||e.videoUrl||e.videos?.[0]?.url||e.images?.[0]?.url||e.images?.[0]||null}function pickTitle(t){const e=t?.data||{};return e.title||e.caption||"Social Media Video"}const infoShape=(t,e,a={})=>({site:t,url:e,title:a.title??null,author:{name:a.authorName??null,url:a.authorUrl??null},thumbnail:a.thumbnail??null,duration:a.duration??null,description:a.description??null,...a.embedHtml?{embedHtml:a.embedHtml}:{}}),ogScrape=async t=>{const{data:e}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Accept-Language":"en-US,en;q=0.9"},timeout:25e3}),a=t=>{const a=e.match(new RegExp(`<meta[^>]+property="${t}"[^>]+content="([^"]+)"`))||e.match(new RegExp(`<meta[^>]+content="([^"]+)"[^>]+property="${t}"`));return a?a[1].replace(/&/g,"&"):null},o=e.match(/<title>([^<]{1,200})<\/title>/);return{html:e,title:a("og:title")||(o?o[1].trim():null),description:a("og:description"),thumbnail:a("og:image")}},infoYouTube=async t=>{const{data:e}=await http.get(`https://www.youtube.com/oembed?url=${encodeURIComponent(t)}&format=json`,{timeout:2e4});let a=null,o=e.thumbnail_url||null;try{const{html:e}=await ogScrape(t),i=e.match(/"lengthSeconds":"(\d+)"/);i&&(a=parseInt(i[1],10));const r=e.match(/<meta property="og:image" content="([^"]*maxresdefault[^"]*)"/);r&&(o=r[1])}catch{}return infoShape("youtube",t,{title:e.title,authorName:e.author_name,authorUrl:e.author_url,thumbnail:o,duration:a})},infoTikTok=async t=>{const{data:e}=await http.get(`https://www.tiktok.com/oembed?url=${encodeURIComponent(t)}`,{timeout:2e4});let a=null;try{const e=t.match(/\/video\/(\d+)/)?.[1],{data:o}=await http.get(t,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},timeout:25e3});if(e){const t=o.indexOf(`"id":"${e}"`);if(-1!==t){const e=o.slice(t,t+4e3).match(/"duration":(\d+)/);e&&(a=parseInt(e[1],10))}}if(null===a){const t=o.match(/"duration":(\d+)/);t&&(a=parseInt(t[1],10))}}catch{}return infoShape("tiktok",t,{title:e.title,authorName:e.author_name,authorUrl:e.author_url,thumbnail:e.thumbnail_url,duration:a,description:e.title})},infoVimeo=async t=>{const{data:e}=await http.get(`https://vimeo.com/api/oembed.json?url=${encodeURIComponent(t)}`,{timeout:2e4});return infoShape("vimeo",t,{title:e.title,authorName:e.author_name,authorUrl:e.author_url,thumbnail:e.thumbnail_url,duration:"number"==typeof e.duration?e.duration:null,description:e.description||null})},infoMetaOembed=async(t,e,a)=>{const o="facebook"===t?["oembed_video","oembed_post"]:["oembed_post","oembed_video"],i=async(t,a)=>{const o=`https://graph.facebook.com/v21.0/${t}?url=${encodeURIComponent(e)}`+(a?`&access_token=${encodeURIComponent(a)}`:""),{data:i}=await http.get(o,{timeout:2e4});if(!i||i.error)throw new Error(i?.error?.message||"oEmbed error");return i};let r=null,n=null;for(const t of o)try{r=await i(t);break}catch(t){n=t}if(a)for(const r of o)try{const o=await i(r,a);if(o.title||o.author_name||o.thumbnail_url)return infoShape(t,e,{title:o.title||null,authorName:o.author_name||null,authorUrl:o.author_url||null,thumbnail:o.thumbnail_url||null,embedHtml:o.html||null})}catch(t){n=t}if(r)return infoShape(t,e,{title:null,authorName:null,authorUrl:null,thumbnail:null,embedHtml:r.html||null,description:"Tokenless oEmbed: URL valid, kintu Meta title/thumbnail dey na (oEmbed Read approval lage)"});throw new Error(`Meta oEmbed failed: ${n?.response?.data?.error?.message||n?.message||"unknown"}`)},infoPinterest=async t=>{const{title:e,description:a,thumbnail:o}=await ogScrape(t);return infoShape("pinterest",t,{title:e,description:a,thumbnail:o,duration:null})},infoDailymotion=async t=>{const e=t.match(/dailymotion\.com\/(?:video|embed\/video)\/([A-Za-z0-9]+)/)?.[1]||t.match(/dai\.ly\/([A-Za-z0-9]+)/)?.[1];if(!e)throw new Error("Dailymotion video ID ber kora jayni");const{data:a}=await http.get(`https://www.dailymotion.com/player/metadata/video/${e}`,{timeout:2e4}),o=a.thumbnails||{},i=Object.keys(o).map(t=>parseInt(t,10)).filter(t=>!isNaN(t)).sort((t,e)=>e-t);return infoShape("dailymotion",t,{title:a.title||null,authorName:a.owner?.screenname||null,thumbnail:i.length?o[String(i[0])]:null,duration:"number"==typeof a.duration?a.duration:null})},detectInfoSite=t=>/tiktok\.com/.test(t)?"tiktok":/youtube\.com|youtu\.be/.test(t)?"youtube":/vimeo\.com/.test(t)?"vimeo":/facebook\.com|fb\.watch/.test(t)?"facebook":/instagram\.com/.test(t)?"instagram":/pinterest\.com|pin\.it/.test(t)?"pinterest":/dailymotion\.com|dai\.ly/.test(t)?"dailymotion":/likee\.video|l\.likee/.test(t)?"likee":/threads\.net|threads\.com/.test(t)?"threads":/capcut\.com/.test(t)?"capcut":/kwai\.com|kuaishou\.com|kwai-video\.com/.test(t)?"kwai":/snapchat\.com/.test(t)?"snapchat":/x\.com|twitter\.com/.test(t)?"x":"unknown",info=async(t,e={})=>{if("string"!=typeof t||!/^https?:\/\//i.test(t.trim()))throw new Error("Invalid URL: "+String(t).slice(0,80));const a=detectInfoSite(t);try{switch(a){case"youtube":return await infoYouTube(t);case"tiktok":return await infoTikTok(t);case"vimeo":return await infoVimeo(t);case"facebook":case"instagram":return await infoMetaOembed(a,t,e.appToken);case"pinterest":return await infoPinterest(t);case"dailymotion":return await infoDailymotion(t);default:{const{title:e,description:o,thumbnail:i}=await ogScrape(t);return infoShape(a,t,{title:e,description:o,thumbnail:i,duration:null})}}}catch(t){if(/needs an app token/.test(t.message))throw t;throw new Error(`info() failed for ${a}: ${t.message}`)}},alldl=async t=>{let e;if(/tiktok\.com/.test(t))e=await tiktok(t);else if(/facebook\.com|fb\.watch|share\/v\//.test(t))e=await fb(t);else if(/instagram\.com/.test(t))e=await insta(t);else if(/likee\.video|l\.likee/.test(t))e=await likee(t);else if(/threads\.net|threads\.com/.test(t))e=await threads(t);else if(/pinterest\.com|pin\.it/.test(t))e=await pinterest(t);else if(/youtube\.com|youtu\.be/.test(t))e=await youtube(t);else if(/capcut\.com/.test(t))e=await capcut(t);else if(/kwai\.com|kuaishou\.com|kwai-video\.com/.test(t))e=await kwai(t);else if(/snapchat\.com/.test(t))e=await snapchat(t);else if(/dailymotion\.com|dai\.ly/.test(t))e=await dailymotion(t);else if(/vimeo\.com/.test(t))e=await vimeo(t);else{if(!/x\.com|twitter\.com/.test(t))throw new Error("Platform not supported: "+t);e=await twitterDownloader(t)}return{metadata:metadata,data:{title:pickTitle(e),videoUrl:pickVideoUrl(e),source:e.source}}},withMeta=async(t,e,a)=>{const o=await t(e,a);return{metadata:metadata,...o}};alldl.tiktok=t=>withMeta(tiktok,t),alldl.fb=t=>withMeta(fb,t),alldl.insta=t=>withMeta(insta,t),alldl.likee=t=>withMeta(likee,t),alldl.threads=t=>withMeta(threads,t),alldl.pinterest=t=>withMeta(pinterest,t),alldl.youtube=t=>withMeta(youtube,t),alldl.capcut=t=>withMeta(capcut,t),alldl.kwai=t=>withMeta(kwai,t),alldl.snapchat=t=>withMeta(snapchat,t),alldl.dailymotion=t=>withMeta(dailymotion,t),alldl.vimeo=t=>withMeta(vimeo,t),alldl.x=(t,e)=>withMeta(twitterDownloader,t,e),alldl.twitter=(t,e)=>withMeta(twitterDownloader,t,e),alldl.info=(t,e)=>info(t,e);const fs=require("fs"),fsp=fs.promises,path=require("path");function sanitizeFilename(t){return String(t||"video").replace(/[<>:"/\\|?*\x00-\x1f]/g,"").replace(/\s+/g," ").trim().slice(0,100)||"video"}function extFromUrl(t){try{const e=new URL(t).pathname.match(/\.([a-z0-9]{2,4})$/i);return e?"."+e[1].toLowerCase():null}catch{return null}}function extFromType(t){return{"video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/mp4":".m4a","image/jpeg":".jpg","image/png":".png","image/webp":".webp","image/gif":".gif"}[String(t||"").split(";")[0].trim().toLowerCase()]||null}async function streamToFile(t,e,a){const o=await axios({url:t,method:"GET",responseType:"stream",timeout:12e4,maxRedirects:5,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},validateStatus:t=>t>=200&&t<400}),i=parseInt(o.headers["content-length"]||"0",10)||null;let r=0;return await fsp.mkdir(path.dirname(e),{recursive:!0}),await new Promise((t,n)=>{const l=fs.createWriteStream(e);o.data.on("data",t=>{if(r+=t.length,a)try{a({done:r,total:i,percent:i?Math.round(r/i*100):null})}catch{}}),o.data.on("error",n),l.on("error",n),l.on("finish",t),o.data.pipe(l)}),r}const _alldlCore=alldl;async function alldlWithOpts(t,e={}){const a=Math.max(0,0|e.retries||0);let o=null;for(let e=0;e<=a;e++)try{return await _alldlCore(t)}catch(t){o=t,e<a&&await sleep(1e3*(e+1))}throw o}alldlWithOpts.download=async(t,e,a={})=>{if(!t)throw new Error("URL is required");if(!e)throw new Error("Destination path is required");const o=await alldlWithOpts(t,a),i=o.data.videoUrl;if(!i)throw new Error("No downloadable media found: "+t);let r=extFromUrl(i);if(!r)try{r=extFromType((await axios.head(i,{timeout:15e3,maxRedirects:5,validateStatus:t=>t>=200&&t<400})).headers["content-type"])}catch{}r=r||".mp4";const n=sanitizeFilename(o.data.title);let l;try{const t=fs.existsSync(e)?fs.statSync(e):null;l=e.endsWith(path.sep)||t&&t.isDirectory()?path.join(e,n+r):path.extname(e)?e:path.join(e,n+r)}catch{l=path.join(e,n+r)}let s=l,c=1;for(;fs.existsSync(s);)s=path.join(path.dirname(l),`${n} (${c})${r}`),c++;return l=s,{path:l,bytes:await streamToFile(i,l,a.onProgress),title:o.data.title,source:o.data.source,videoUrl:i}},alldlWithOpts.batch=async(t,e={})=>{if(!Array.isArray(t))throw new Error("urls must be an array");const a=Math.max(1,0|e.concurrency||3),o=new Array(t.length);let i=0;const r=Array.from({length:Math.min(a,t.length)},()=>async function(){for(;i<t.length;){const a=i++;try{const i=await alldlWithOpts(t[a],e);o[a]={success:!0,url:t[a],...i}}catch(e){o[a]={success:!1,url:t[a],error:e.message}}if(e.onItem)try{e.onItem(o[a],a)}catch{}}}());return await Promise.all(r),o},Object.assign(alldlWithOpts,alldl),alldlWithOpts.download=alldlWithOpts.download,alldlWithOpts.batch=alldlWithOpts.batch,module.exports={alldl:alldlWithOpts};
|
package/package.json
CHANGED