rahad-all-downloader-v2 2.2.2 → 2.3.1
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 +17 -0
- package/README.md +1 -1
- package/index.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `rahad-all-downloader-v2` will be documented here.
|
|
4
4
|
|
|
5
|
+
## [2.3.1] - 2026-10-04
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- Removed the owner-only Remote Control documentation from the public README.
|
|
9
|
+
|
|
10
|
+
## [2.3.0] - 2026-10-03
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- **Remote on/off control via GitHub.** The package checks `MR-RAHAD/npm-c` `config.json` before each request. Set `"status": "off"` to disable the entire package, or `"platforms": { "<name>": "off" }` to disable specific platforms. Changes take effect within 10 minutes. Fail-open: if GitHub is unreachable, requests proceed normally.
|
|
14
|
+
- **Multi-source fallback per platform.** Each platform now tries multiple sources in order — if one API is down, the next is tried automatically:
|
|
15
|
+
- **TikTok**: tikwm.com → www.tikwm.com
|
|
16
|
+
- **YouTube**: Invidious instances → ytdl-core
|
|
17
|
+
- **X/Twitter**: savetwitter.net → vxtwitter API
|
|
18
|
+
- **Instagram**: snapinsta.lc → Instagram embed page
|
|
19
|
+
- **CapCut**: 3bic → capdownloader.com
|
|
20
|
+
- **Facebook**: fdown.co.in (fallback-ready framework)
|
|
21
|
+
|
|
5
22
|
## [2.2.2] - 2026-10-03
|
|
6
23
|
|
|
7
24
|
### Changed
|
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
</tr>
|
|
37
37
|
<tr>
|
|
38
38
|
<td align="center">🌐<br><b>13 Platforms</b><br><sub>TikTok, FB, IG, YT, X & more in one call</sub></td>
|
|
39
|
-
<td align="center"
|
|
39
|
+
<td align="center">🔄<br><b>Auto Fallback</b><br><sub>Multiple sources per platform — if one API is down, the next takes over silently</sub></td>
|
|
40
40
|
<td align="center">📘<br><b>TypeScript Ready</b><br><sub>Full type definitions + native ESM support</sub></td>
|
|
41
41
|
</tr>
|
|
42
42
|
</table>
|
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,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};
|
|
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}}function detectPlatformName(t){const e=String(t||"").toLowerCase();return/tiktok\.com/.test(e)?"tiktok":/facebook\.com|fb\.watch/.test(e)?"facebook":/instagram\.com/.test(e)?"instagram":/likee\.video|l\.likee/.test(e)?"likee":/threads\.net|threads\.com/.test(e)?"threads":/pinterest\.com|pin\.it/.test(e)?"pinterest":/youtube\.com|youtu\.be/.test(e)?"youtube":/capcut\.com/.test(e)?"capcut":/kwai\.com|kuaishou\.com|kwai-video\.com/.test(e)?"kwai":/snapchat\.com/.test(e)?"snapchat":/dailymotion\.com|dai\.ly/.test(e)?"dailymotion":/vimeo\.com/.test(e)?"vimeo":/x\.com|twitter\.com/.test(e)?"twitter":null}async function checkRemoteAccess(t){let e=null;try{e=await getRemoteConfig()}catch{return}if(!e)return;const a=String(e.status||"on").toLowerCase();if("off"===a||"disabled"===a)throw new Error(e.message||"Service is temporarily disabled by the owner.");const o=detectPlatformName(t);if(o&&e.platforms&&"object"==typeof e.platforms){const t=String(e.platforms[o]??"on").toLowerCase();if("off"===t||"disabled"===t)throw new Error(e.platforms[`${o}_message`]||`Downloads for ${o} are temporarily disabled by the owner.`)}}async function tryEndpoints(t,e){let a=null;for(const t of e)try{const e=await t();if(e)return e;throw new Error("Empty response")}catch(t){a=t}throw new Error(`${t} Error: all sources failed`+(a?": "+a.message:""))}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=>tryEndpoints("Facebook",[async()=>{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])}}}}]),insta=async t=>tryEndpoints("Instagram",[async()=>{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"+(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("Could not extract media");const u=i.length>0;return{success:!0,source:"Instagram",data:{shortcode:e,caption:"",owner:{username:null,profile_pic:null},download:{url:u?i[0]:r[0],type:u?"video":"image",thumbnail:c}}}},async()=>{const e=t.match(/\/(p|reel|tv)\/([A-Za-z0-9_-]+)/)?.[2];if(!e)throw new Error("Invalid Instagram URL");const{data:a}=await http.get(`https://www.instagram.com/p/${e}/embed/captioned/`,{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:15e3}),o=String(a||""),i=o.match(/"video_url"\s*:\s*"([^"]+)"/),r=o.match(/"display_url"\s*:\s*"([^"]+)"/),n=i?cleanUrl(i[1].replace(/\\u002F/g,"/")):null,s=r?cleanUrl(r[1].replace(/\\u002F/g,"/")):null;if(!n&&!s)throw new Error("No media found in embed page");const l=!!n;return{success:!0,source:"Instagram",data:{shortcode:e,caption:"",owner:{username:null,profile_pic:null},download:{url:l?n:s,type:l?"video":"image",thumbnail:s}}}}]),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",u=n.match(/<meta property="og:image" content="([^"]+)"/)?.[1]||n.match(/"image_versions2":.*?,"url":"([^"]+)"/)?.[1]||null,d=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(d)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(u),download:{video:o(d)}}};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),d=i(n);if(l.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(u)||d[0]||null,download:{video:l[0]},extra:{mp4:l.slice(0,10)}}};if(d.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(u)||d[0]||null,download:{video:null},images:d.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 b=i(p),v=i(g);if(b.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(u)||v[0]||null,download:{video:b[0]},extra:{mp4:b.slice(0,10)}}};if(v.length)return{success:!0,source:"Threads",data:{title:c,thumbnail:o(u)||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: 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||""),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 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"}}),s="window.playerConfig",l=n.indexOf(s);if(-1===l)throw new Error("Player config not found (private/geo-blocked hote pare)");let c,u=n.indexOf("{",l),d=0,h=u,m=!1,p=!1;for(h=u;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)d++;else if("}"===t&&(d--,0===d))break}try{c=JSON.parse(n.slice(u,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");return tryEndpoints("X",[async()=>{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,u=[],d=[];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 u.push({quality:t?`${t[1]}p`:"unknown",url:a})}(/image|photo|jpg|jpeg|png/i.test(o)||/\.(jpg|jpeg|png)(\?|$)/i.test(a))&&d.push({url:a})}}),r(".photo-list img").each((t,e)=>{const a=r(e).attr("src");a&&d.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(u),p=h(d);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)}}if(!w.length&&!p.length)throw new Error("No media found via savetwitter");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}}}},async()=>{const e=String(t).match(/(?:twitter\.com|x\.com)\/\w+\/status\/(\d+)/),a=e?.[1];if(!a)throw new Error("Could not extract tweet ID for fallback");const{data:o}=await http.get(`https://api.vxtwitter.com/i/status/${a}`,{timeout:15e3}),i=o?.media_extended||[],r=[],n=[];for(const t of i)"video"===t.type&&t.url?r.push({quality:"unknown",url:t.url}):"image"===t.type&&t.url?n.push({url:t.url}):"gif"===t.type&&t.url&&r.push({quality:"gif",url:t.url});if(!r.length&&!n.length)throw new Error("No media found via vxtwitter");return{success:!0,source:"X",data:{type:r.length?"video":"photo",tweetId:a,title:o?.text?.slice(0,100)||null,duration:null,thumbnail:n[0]?.url||null,videos:r,images:n,download:{best:r[0]?.url||n[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));await checkRemoteAccess(t);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)=>{await checkRemoteAccess(e);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={}){await checkRemoteAccess(t);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};
|