@coflyn/mori 1.1.0 → 1.2.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/engine.js CHANGED
@@ -58,7 +58,76 @@ function serializeData(obj) {
58
58
  }
59
59
 
60
60
  function cleanUrl(u) {
61
- return u ? u.split("?")[0] : "";
61
+ if (!u) return "";
62
+ const clean = u.split("?")[0];
63
+ const shortsMatch = clean.match(/(?:youtube\.com\/shorts\/|youtu\.be\/)([^"&?/\s]{11})/i);
64
+ if (shortsMatch) {
65
+ return `https://www.youtube.com/watch?v=${shortsMatch[1]}`;
66
+ }
67
+ return clean;
68
+ }
69
+
70
+ const SAFARI_MOBILE_UA = CHROME_MOBILE_UA;
71
+
72
+ function decodeSnapSave(data) {
73
+ try {
74
+ const regex =
75
+ /eval\(function\(h,u,n,t,e,r\)\{.*?\}\("(.*?)",(\d+),"(.*?)",(\d+),(\d+),(\d+)\)\)/;
76
+ const match = data.match(regex);
77
+ if (match) {
78
+ const h = match[1],
79
+ u = parseInt(match[2]),
80
+ n = match[3],
81
+ t = parseInt(match[4]),
82
+ e = parseInt(match[5]);
83
+ const delimiter = n[e],
84
+ parts = h.split(delimiter);
85
+ let decoded = "";
86
+ for (let s of parts) {
87
+ if (s === "") continue;
88
+ let val = 0;
89
+ for (let j = 0; j < s.length; j++)
90
+ val += n.indexOf(s[j]) * Math.pow(e, s.length - 1 - j);
91
+ decoded += String.fromCharCode(val - t);
92
+ }
93
+ try {
94
+ return decodeURIComponent(escape(decoded));
95
+ } catch {
96
+ return Buffer.from(decoded, "binary").toString("utf-8");
97
+ }
98
+ }
99
+ return data;
100
+ } catch (err) {
101
+ return data;
102
+ }
103
+ }
104
+
105
+ function extractFinalUrl(input) {
106
+ if (!input) return null;
107
+ let raw = input.trim().replace(/^["'\\]+|["'\\]+$/g, ""),
108
+ isRender = false;
109
+ if (raw.includes("get_progressApi") || raw.includes("get_progress")) {
110
+ isRender = true;
111
+ const tokenMatch = raw.match(/token=([^&'"]+)/);
112
+ if (tokenMatch) raw = tokenMatch[1];
113
+ }
114
+ if (raw.includes(".") && !raw.startsWith("http")) {
115
+ try {
116
+ const payloadPart = raw.split(".")[1];
117
+ if (payloadPart) {
118
+ const payload = JSON.parse(
119
+ Buffer.from(payloadPart, "base64").toString("utf-8")
120
+ );
121
+ if (payload.video_url)
122
+ return { url: payload.video_url, isRender: true };
123
+ if (payload.url) return { url: payload.url, isRender: false };
124
+ }
125
+ } catch (e) {}
126
+ }
127
+ if (raw.startsWith("//")) return { url: "https:" + raw, isRender };
128
+ if (raw.startsWith("/"))
129
+ return { url: "https://snapsave.app" + raw, isRender };
130
+ return { url: raw, isRender };
62
131
  }
63
132
 
64
133
  globalThis.window.__moriDeps = {
@@ -66,10 +135,13 @@ globalThis.window.__moriDeps = {
66
135
  CHROME_UA,
67
136
  CHROME_DESKTOP_UA,
68
137
  CHROME_MOBILE_UA,
138
+ SAFARI_MOBILE_UA,
69
139
  getUserAgent,
70
140
  cleanUrl,
71
141
  getCookiesFromHeaders,
72
142
  serializeData,
143
+ decodeSnapSave,
144
+ extractFinalUrl,
73
145
  },
74
146
  urlUtils: {
75
147
  getCleanUrl: (u) => (u ? u.trim() : ""),
@@ -250,34 +322,51 @@ export function clearHistory() {
250
322
  }
251
323
  }
252
324
 
253
- export function deleteHistoryItem(index, deleteFile = true) {
325
+ export function deleteHistoryItems(indices, deleteFile = true) {
254
326
  try {
255
327
  const list = getHistory(200);
256
- if (index < 0 || index >= list.length) {
257
- return { success: false, error: "Index out of range" };
258
- }
259
- const [removed] = list.splice(index, 1);
260
- let fileDeleted = false;
261
-
262
- if (deleteFile && removed.path && fs.existsSync(removed.path)) {
263
- try {
264
- fs.unlinkSync(removed.path);
265
- fileDeleted = true;
266
- } catch (_) {}
328
+ const sortedIndices = [...new Set(indices)].sort((a, b) => b - a);
329
+ const deletedItems = [];
330
+ let filesDeletedCount = 0;
331
+
332
+ for (const idx of sortedIndices) {
333
+ if (idx >= 0 && idx < list.length) {
334
+ const [removed] = list.splice(idx, 1);
335
+ let fileDeleted = false;
336
+ if (deleteFile && removed.path && fs.existsSync(removed.path)) {
337
+ try {
338
+ fs.unlinkSync(removed.path);
339
+ fileDeleted = true;
340
+ filesDeletedCount++;
341
+ } catch (_) {}
342
+ }
343
+ deletedItems.push({ item: removed, fileDeleted });
344
+ }
267
345
  }
268
346
 
269
347
  fs.writeFileSync(HISTORY_PATH, JSON.stringify(list, null, 2), "utf8");
270
348
 
271
349
  return {
272
350
  success: true,
273
- item: removed,
274
- fileDeleted,
351
+ count: deletedItems.length,
352
+ filesDeletedCount,
353
+ deletedItems,
275
354
  };
276
355
  } catch (err) {
277
356
  return { success: false, error: err.message };
278
357
  }
279
358
  }
280
359
 
360
+ export function deleteHistoryItem(index, deleteFile = true) {
361
+ const res = deleteHistoryItems([index], deleteFile);
362
+ if (!res.success) return res;
363
+ return {
364
+ success: true,
365
+ item: res.deletedItems[0]?.item,
366
+ fileDeleted: res.deletedItems[0]?.fileDeleted || false,
367
+ };
368
+ }
369
+
281
370
  export function getStats() {
282
371
  const items = getHistory(200);
283
372
  const totalDownloads = items.length;
@@ -526,6 +615,160 @@ export function uninstallScraprEngine() {
526
615
  return true;
527
616
  }
528
617
 
618
+ export async function fetchMoriEngineHistory() {
619
+ try {
620
+ const res = await fetch(
621
+ `https://api.github.com/repos/${GITHUB_REPO}/commits?path=public/js/scrapers/bundle.js&per_page=15`,
622
+ {
623
+ signal: AbortSignal.timeout(10000),
624
+ headers: { "User-Agent": "Mori-CLI" },
625
+ },
626
+ );
627
+ if (!res.ok) return [];
628
+ const commits = await res.json();
629
+ if (!Array.isArray(commits)) return [];
630
+ return commits.map((c) => ({
631
+ sha: c.sha.slice(0, 7),
632
+ fullSha: c.sha,
633
+ message: (c.commit?.message || "").split("\n")[0].trim(),
634
+ date: c.commit?.author?.date || "",
635
+ }));
636
+ } catch (_) {
637
+ return [];
638
+ }
639
+ }
640
+
641
+ export async function downloadMoriEngineByCommit(commitSha, onProgress) {
642
+ const shortSha = commitSha.slice(0, 7);
643
+ if (onProgress) onProgress(`Fetching Mori Core bundle at commit ${shortSha}...`);
644
+
645
+ const bundleUrl = `https://raw.githubusercontent.com/${GITHUB_REPO}/${commitSha}/public/js/scrapers/bundle.js`;
646
+ const metaUrl = `https://raw.githubusercontent.com/${GITHUB_REPO}/${commitSha}/public/scrapers-version.json`;
647
+
648
+ const [bundleRes, metaRes] = await Promise.all([
649
+ fetch(bundleUrl, {
650
+ signal: AbortSignal.timeout(30000),
651
+ headers: { "User-Agent": "Mori-CLI", "Cache-Control": "no-cache" },
652
+ }),
653
+ fetch(metaUrl, {
654
+ signal: AbortSignal.timeout(15000),
655
+ headers: { "User-Agent": "Mori-CLI", "Cache-Control": "no-cache" },
656
+ }).catch(() => null),
657
+ ]);
658
+
659
+ if (!bundleRes.ok) {
660
+ throw new Error(`Failed to fetch bundle at commit ${shortSha}: HTTP ${bundleRes.status}`);
661
+ }
662
+
663
+ const bundleText = await bundleRes.text();
664
+ if (!bundleText || bundleText.length < 5000) {
665
+ throw new Error("Downloaded bundle is empty or invalid.");
666
+ }
667
+
668
+ let meta = { scraperVersion: shortSha };
669
+ if (metaRes && metaRes.ok) {
670
+ try {
671
+ meta = await metaRes.json();
672
+ } catch (_) {}
673
+ }
674
+
675
+ if (!fs.existsSync(OTA_DIR)) {
676
+ fs.mkdirSync(OTA_DIR, { recursive: true });
677
+ }
678
+
679
+ fs.writeFileSync(OTA_BUNDLE_PATH, bundleText, "utf8");
680
+ fs.writeFileSync(
681
+ OTA_META_PATH,
682
+ JSON.stringify(
683
+ {
684
+ scraperVersion: meta.scraperVersion || shortSha,
685
+ updatedAt: Date.now(),
686
+ sourceHash: meta.sourceHash || "",
687
+ changelog: meta.changelog || "",
688
+ commitSha: shortSha,
689
+ },
690
+ null,
691
+ 2,
692
+ ),
693
+ "utf8",
694
+ );
695
+
696
+ cachedMoriScrapers = null;
697
+ return { success: true, version: meta.scraperVersion || shortSha };
698
+ }
699
+
700
+ export async function fetchScraprEngineVersions() {
701
+ try {
702
+ const res = await fetch("https://registry.npmjs.org/@coflyn/scrapr", {
703
+ signal: AbortSignal.timeout(10000),
704
+ headers: { "User-Agent": "Mori-CLI" },
705
+ });
706
+ if (!res.ok) return [];
707
+ const data = await res.json();
708
+ const versions = Object.keys(data.versions || {});
709
+ return versions.reverse();
710
+ } catch (_) {
711
+ return [];
712
+ }
713
+ }
714
+
715
+ export async function downloadScraprEngineVersion(targetVersion, onProgress) {
716
+ if (onProgress) onProgress(`Downloading Scrapr Engine v${targetVersion}...`);
717
+ let bundleText = "";
718
+
719
+ const urls = [
720
+ `https://unpkg.com/@coflyn/scrapr@${targetVersion}/bundle.cjs`,
721
+ `https://cdn.jsdelivr.net/npm/@coflyn/scrapr@${targetVersion}/bundle.cjs`,
722
+ `https://raw.githubusercontent.com/coflyn/scrapr/v${targetVersion}/bundle.cjs`,
723
+ `https://raw.githubusercontent.com/coflyn/scrapr/main/bundle.cjs`,
724
+ ];
725
+
726
+ for (const u of urls) {
727
+ try {
728
+ const res = await fetch(u, {
729
+ signal: AbortSignal.timeout(30000),
730
+ headers: { "User-Agent": "Mori-CLI", "Cache-Control": "no-cache" },
731
+ });
732
+ if (res.ok) {
733
+ bundleText = await res.text();
734
+ if (bundleText && bundleText.length > 50000) break;
735
+ }
736
+ } catch (_) {}
737
+ }
738
+
739
+ if (!bundleText || bundleText.length < 50000) {
740
+ const localDevScrapr = path.resolve(__dirname, "../../../scrapr/bundle.cjs");
741
+ if (fs.existsSync(localDevScrapr)) {
742
+ bundleText = fs.readFileSync(localDevScrapr, "utf8");
743
+ }
744
+ }
745
+
746
+ if (!bundleText || bundleText.length < 50000) {
747
+ throw new Error(`Failed to download Scrapr v${targetVersion} bundle.`);
748
+ }
749
+
750
+ if (!fs.existsSync(SCRAPR_DIR)) {
751
+ fs.mkdirSync(SCRAPR_DIR, { recursive: true });
752
+ }
753
+
754
+ fs.writeFileSync(SCRAPR_BUNDLE_PATH, bundleText, "utf8");
755
+ fs.writeFileSync(
756
+ SCRAPR_META_PATH,
757
+ JSON.stringify(
758
+ {
759
+ version: targetVersion,
760
+ updatedAt: Date.now(),
761
+ },
762
+ null,
763
+ 2,
764
+ ),
765
+ "utf8",
766
+ );
767
+
768
+ cachedScrapr = null;
769
+ return { success: true, version: targetVersion };
770
+ }
771
+
529
772
  /**
530
773
  * Checks for Mori Core OTA updates from GitHub raw.
531
774
  */
@@ -784,6 +1027,21 @@ export const SCRAPR_ONLY_PLATFORMS = new Set([
784
1027
  "sub2unlock",
785
1028
  "rekonise",
786
1029
  "unshorten",
1030
+ // Comic & Manga (Engine 2)
1031
+ "kiryuu",
1032
+ "komikcast",
1033
+ "mangadex",
1034
+ "komikindo",
1035
+ "komiku",
1036
+ "bacakomik",
1037
+ "manhwaindo",
1038
+ "asurascans",
1039
+ "mangabats",
1040
+ // Anime (Engine 2)
1041
+ "otakudesu",
1042
+ "nimegami",
1043
+ "gogoanime",
1044
+ "animetosho",
787
1045
  ]);
788
1046
 
789
1047
  export const RESOLVER_LINK_PLATFORMS = new Set([
@@ -903,9 +1161,64 @@ export function detectPlatform(rawUrl) {
903
1161
  url.includes("dub.sh") ||
904
1162
  url.includes("cutt.ly") ||
905
1163
  url.includes("t.co/") ||
906
- url.includes("shorturl.at")
1164
+ url.includes("shorturl.at") ||
1165
+ url.includes("aka.ms")
907
1166
  )
908
1167
  return "unshorten";
1168
+ // Comic & Manga (Engine 2: Scrapr)
1169
+ if (url.includes("kiryuu.to") || url.includes("kiryuu.id")) return "kiryuu";
1170
+ if (
1171
+ url.includes("komikcast.info") ||
1172
+ url.includes("komikcast.ch") ||
1173
+ url.includes("komikcast.me") ||
1174
+ url.includes("komikcast.cz")
1175
+ )
1176
+ return "komikcast";
1177
+ if (url.includes("mangadex.org")) return "mangadex";
1178
+ if (
1179
+ url.includes("komikindo.ch") ||
1180
+ url.includes("komikindo.org") ||
1181
+ url.includes("komikindo.tv")
1182
+ )
1183
+ return "komikindo";
1184
+ if (url.includes("komiku.org") || url.includes("komiku.id")) return "komiku";
1185
+ if (
1186
+ url.includes("bacakomik.my") ||
1187
+ url.includes("bacakomik.co") ||
1188
+ url.includes("bacakomik.one")
1189
+ )
1190
+ return "bacakomik";
1191
+ if (
1192
+ url.includes("manhwaindo.my") ||
1193
+ url.includes("manhwaindo.id") ||
1194
+ url.includes("manhwaindo.org")
1195
+ )
1196
+ return "manhwaindo";
1197
+ if (
1198
+ url.includes("asurascans.com") ||
1199
+ url.includes("asuracomic.net") ||
1200
+ url.includes("asura.gg")
1201
+ )
1202
+ return "asurascans";
1203
+ if (url.includes("mangabats.com") || url.includes("mangabat.com"))
1204
+ return "mangabats";
1205
+
1206
+ // Anime (Engine 2: Scrapr)
1207
+ if (
1208
+ url.includes("otakudesu.blog") ||
1209
+ url.includes("otakudesu.cloud") ||
1210
+ url.includes("otakudesu.tube") ||
1211
+ url.includes("otakudesu.info")
1212
+ )
1213
+ return "otakudesu";
1214
+ if (url.includes("nimegami.id")) return "nimegami";
1215
+ if (
1216
+ url.includes("gogoanime") ||
1217
+ url.includes("gogoanimes") ||
1218
+ url.includes("anitaku")
1219
+ )
1220
+ return "gogoanime";
1221
+ if (url.includes("animetosho.org")) return "animetosho";
909
1222
  return null;
910
1223
  }
911
1224
 
@@ -1055,21 +1368,30 @@ export async function scrapeWithMori(url, platform, serverPreference = "auto") {
1055
1368
  break;
1056
1369
  }
1057
1370
  case "youtube": {
1371
+ const videoMatch = url.match(
1372
+ /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?|shorts|live)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i,
1373
+ );
1374
+ const isPlaylist =
1375
+ url.includes("list=") && (!videoMatch?.[1] || url.includes("/playlist"));
1376
+ const targetUrl =
1377
+ !isPlaylist && videoMatch?.[1]
1378
+ ? `https://www.youtube.com/watch?v=${videoMatch[1]}`
1379
+ : url;
1058
1380
  if (srv === "server2") {
1059
1381
  scrapers.setYouTubeSource("mobi");
1060
- res = await scrapers.scrapeYouTube(url);
1382
+ res = await scrapers.scrapeYouTube(targetUrl);
1061
1383
  usedServer = "ytmp3.mobi";
1062
1384
  } else if (srv === "server1") {
1063
1385
  scrapers.setYouTubeSource("gg");
1064
- res = await scrapers.scrapeYouTube(url);
1386
+ res = await scrapers.scrapeYouTube(targetUrl);
1065
1387
  usedServer = "ytmp3.gg";
1066
1388
  } else {
1067
1389
  scrapers.setYouTubeSource("gg");
1068
- res = await scrapers.scrapeYouTube(url);
1390
+ res = await scrapers.scrapeYouTube(targetUrl);
1069
1391
  usedServer = "ytmp3.gg";
1070
1392
  if (!res?.status) {
1071
1393
  scrapers.setYouTubeSource("mobi");
1072
- res = await scrapers.scrapeYouTube(url);
1394
+ res = await scrapers.scrapeYouTube(targetUrl);
1073
1395
  usedServer = "ytmp3.mobi";
1074
1396
  }
1075
1397
  }
@@ -1267,17 +1589,26 @@ export async function scrapeWithScrapr(
1267
1589
  break;
1268
1590
  }
1269
1591
  case "youtube": {
1592
+ const videoMatch = url.match(
1593
+ /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?|shorts|live)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i,
1594
+ );
1595
+ const isPlaylist =
1596
+ url.includes("list=") && (!videoMatch?.[1] || url.includes("/playlist"));
1597
+ const targetUrl =
1598
+ !isPlaylist && videoMatch?.[1]
1599
+ ? `https://www.youtube.com/watch?v=${videoMatch[1]}`
1600
+ : url;
1270
1601
  if (srv === "ytmp3gg" || srv === "server1") {
1271
- res = await scrapr.youtube.ytmp3gg(url);
1602
+ res = await scrapr.youtube.ytmp3gg(targetUrl);
1272
1603
  usedServer = "ytmp3.gg";
1273
1604
  } else if (srv === "ytmp3" || srv === "server2") {
1274
- res = await scrapr.youtube.ytmp3(url);
1605
+ res = await scrapr.youtube.ytmp3(targetUrl);
1275
1606
  usedServer = "ytmp3";
1276
1607
  } else {
1277
- res = await scrapr.youtube.ytmp3gg(url);
1608
+ res = await scrapr.youtube.ytmp3gg(targetUrl);
1278
1609
  usedServer = "ytmp3.gg";
1279
1610
  if (!res?.status) {
1280
- res = await scrapr.youtube.ytmp3(url);
1611
+ res = await scrapr.youtube.ytmp3(targetUrl);
1281
1612
  usedServer = "ytmp3";
1282
1613
  }
1283
1614
  }
@@ -1456,6 +1787,60 @@ export async function scrapeWithScrapr(
1456
1787
  case "unshorten":
1457
1788
  res = await scrapr.resolver.unshorten(url);
1458
1789
  break;
1790
+ // Comic & Manga
1791
+ case "kiryuu":
1792
+ res = await scrapr.comic.kiryuu(url);
1793
+ usedServer = "Kiryuu";
1794
+ break;
1795
+ case "komikcast":
1796
+ res = await scrapr.comic.komikcast(url);
1797
+ usedServer = "Komikcast";
1798
+ break;
1799
+ case "mangadex":
1800
+ res = await scrapr.comic.mangadex(url);
1801
+ usedServer = "MangaDex";
1802
+ break;
1803
+ case "komikindo":
1804
+ res = await scrapr.comic.komikindo(url);
1805
+ usedServer = "Komikindo";
1806
+ break;
1807
+ case "komiku":
1808
+ res = await scrapr.comic.komiku(url);
1809
+ usedServer = "Komiku";
1810
+ break;
1811
+ case "bacakomik":
1812
+ res = await scrapr.comic.bacakomik(url);
1813
+ usedServer = "Bacakomik";
1814
+ break;
1815
+ case "manhwaindo":
1816
+ res = await scrapr.comic.manhwaindo(url);
1817
+ usedServer = "ManhwaIndo";
1818
+ break;
1819
+ case "asurascans":
1820
+ res = await scrapr.comic.asurascans(url);
1821
+ usedServer = "AsuraScans";
1822
+ break;
1823
+ case "mangabats":
1824
+ res = await scrapr.comic.mangabats(url);
1825
+ usedServer = "MangaBats";
1826
+ break;
1827
+ // Anime
1828
+ case "otakudesu":
1829
+ res = await scrapr.anime.otakudesu(url);
1830
+ usedServer = "Otakudesu";
1831
+ break;
1832
+ case "nimegami":
1833
+ res = await scrapr.anime.nimegami(url);
1834
+ usedServer = "Nimegami";
1835
+ break;
1836
+ case "gogoanime":
1837
+ res = await scrapr.anime.gogoanime(url);
1838
+ usedServer = "Gogoanime";
1839
+ break;
1840
+ case "animetosho":
1841
+ res = await scrapr.anime.animetosho(url);
1842
+ usedServer = "AnimeTosho";
1843
+ break;
1459
1844
  default:
1460
1845
  throw new Error(`Scrapr does not support platform: ${platform}`);
1461
1846
  }
@@ -1616,50 +2001,231 @@ export async function resolveUrl(url, onStatus) {
1616
2001
  return foundLink;
1617
2002
  }
1618
2003
 
1619
- if (url.startsWith("spotidown_resolve:")) {
2004
+ if (
2005
+ url.startsWith("spotidown_resolve:") ||
2006
+ url.startsWith("soundloaders_resolve:")
2007
+ ) {
1620
2008
  if (onStatus) onStatus("Resolving Spotify direct track...");
1621
- const parts = url.replace("spotidown_resolve:", "").split("|||");
1622
- const payloadStr = parts[0];
1623
- let cookiesStr = parts[1] ? decodeURIComponent(parts[1]) : "";
1624
-
1625
- const reqHeaders = {
1626
- "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
1627
- "User-Agent": CHROME_UA,
1628
- "X-Requested-With": "XMLHttpRequest",
1629
- Referer: "https://spotidown.app/",
1630
- Origin: "https://spotidown.app",
1631
- };
1632
- if (cookiesStr) reqHeaders["Cookie"] = cookiesStr;
2009
+ function createMultipartBody(fields) {
2010
+ const boundary =
2011
+ "----WebKitFormBoundary" + Math.random().toString(36).substring(2);
2012
+ let body = "";
2013
+ for (const [k, v] of Object.entries(fields)) {
2014
+ if (v !== undefined && v !== null) {
2015
+ body += `--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`;
2016
+ }
2017
+ }
2018
+ body += `--${boundary}--\r\n`;
2019
+ return {
2020
+ body,
2021
+ contentType: `multipart/form-data; boundary=${boundary}`,
2022
+ };
2023
+ }
1633
2024
 
1634
- const res = await scraperFetch({
1635
- url: "https://spotidown.app/action/track",
1636
- method: "POST",
1637
- headers: reqHeaders,
1638
- data: payloadStr,
1639
- rawResponse: true,
1640
- });
1641
- let dd = res?.data ?? res;
1642
- if (typeof dd === "string") {
2025
+ const isSoundloaders = url.startsWith("soundloaders_resolve:");
2026
+ const parts = url
2027
+ .replace("spotidown_resolve:", "")
2028
+ .replace("soundloaders_resolve:", "")
2029
+ .split("|||");
2030
+ let dataVal = parts[0] || "";
2031
+ let tokenVal = parts[1] || "";
2032
+ let baseVal = parts[2] ? decodeURIComponent(parts[2]) : "";
2033
+ let cookiesStr = parts[3] ? decodeURIComponent(parts[3]) : "";
2034
+
2035
+ if (dataVal.includes("=") && (!tokenVal || !tokenVal.startsWith("http"))) {
1643
2036
  try {
1644
- dd = JSON.parse(dd);
2037
+ const sp = new URLSearchParams(dataVal);
2038
+ if (sp.has("data")) dataVal = sp.get("data") || "";
2039
+ if (sp.has("token")) tokenVal = sp.get("token") || "";
2040
+ if (sp.has("base")) baseVal = sp.get("base") || "";
2041
+ if (parts[1]) cookiesStr = decodeURIComponent(parts[1]);
1645
2042
  } catch (_) {}
1646
2043
  }
1647
- let dlHtml = (typeof dd === "object" ? dd?.data || dd?.html : dd) || "";
1648
- const parser = new DOMParser();
1649
- const doc = parser.parseFromString(dlHtml, "text/html");
2044
+
1650
2045
  let foundLink = "";
1651
- doc.querySelectorAll("a").forEach((a) => {
1652
- const href = a.getAttribute("href");
1653
- const text = a.textContent.trim();
1654
- if (
1655
- href &&
1656
- href.startsWith("http") &&
1657
- !href.includes("premium.html") &&
1658
- text !== "Download Another Song"
1659
- ) {
1660
- if (!foundLink) foundLink = href;
2046
+
2047
+ // 1. If Soundloaders, try Spotimate first (if it doesn't fail with turnstile token)
2048
+ if (isSoundloaders && !tokenVal.startsWith("bccpF:")) {
2049
+ try {
2050
+ if (!cookiesStr) {
2051
+ try {
2052
+ const rHome = await scraperFetch({
2053
+ url: "https://spotimate.app/en1",
2054
+ headers: { "User-Agent": CHROME_UA },
2055
+ rawResponse: true,
2056
+ });
2057
+ let freshCookies = getCookiesFromHeaders(rHome.headers) || "";
2058
+ const rVerify = await scraperFetch({
2059
+ url: "https://spotimate.app/api/userverify",
2060
+ method: "POST",
2061
+ data: "url=" + encodeURIComponent(baseVal || "https://open.spotify.com"),
2062
+ headers: {
2063
+ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
2064
+ "User-Agent": CHROME_UA,
2065
+ Referer: "https://spotimate.app/en1",
2066
+ Origin: "https://spotimate.app",
2067
+ ...(freshCookies ? { Cookie: freshCookies } : {}),
2068
+ },
2069
+ rawResponse: true,
2070
+ });
2071
+ const vCookies = getCookiesFromHeaders(rVerify.headers);
2072
+ if (vCookies) freshCookies = freshCookies ? `${freshCookies}; ${vCookies}` : vCookies;
2073
+ if (freshCookies) cookiesStr = freshCookies;
2074
+ } catch (_) {}
2075
+ }
2076
+
2077
+ const mp = createMultipartBody({
2078
+ data: dataVal,
2079
+ token: tokenVal,
2080
+ track_token: tokenVal,
2081
+ ...(baseVal ? { base: baseVal } : {}),
2082
+ });
2083
+ const slHeaders = {
2084
+ "Content-Type": mp.contentType,
2085
+ "User-Agent": CHROME_UA,
2086
+ Referer: "https://spotimate.app/en1",
2087
+ Origin: "https://spotimate.app",
2088
+ };
2089
+ if (cookiesStr) slHeaders["Cookie"] = cookiesStr;
2090
+
2091
+ const res = await scraperFetch({
2092
+ url: "https://spotimate.app/action/track",
2093
+ method: "POST",
2094
+ headers: slHeaders,
2095
+ data: mp.body,
2096
+ rawResponse: true,
2097
+ });
2098
+ let dd = res?.data ?? res;
2099
+ if (typeof dd === "string") {
2100
+ try {
2101
+ dd = JSON.parse(dd);
2102
+ } catch (_) {}
2103
+ }
2104
+ let dlHtml = (typeof dd === "object" ? dd?.html || dd?.data : dd) || "";
2105
+ const parser = new DOMParser();
2106
+ const doc = parser.parseFromString(dlHtml, "text/html");
2107
+ doc.querySelectorAll("a").forEach((a) => {
2108
+ const href = a.getAttribute("href")?.trim();
2109
+ const text = a.textContent.trim();
2110
+ if (
2111
+ href &&
2112
+ href.startsWith("http") &&
2113
+ !href.includes("tunecable.com") &&
2114
+ !href.includes("premium") &&
2115
+ !text.toLowerCase().includes("cover") &&
2116
+ !href.includes("scdn.co") &&
2117
+ text !== "Download Another Song"
2118
+ ) {
2119
+ if (!foundLink) foundLink = href;
2120
+ }
2121
+ });
2122
+ if (!foundLink) {
2123
+ const match =
2124
+ dlHtml.match(
2125
+ /href=["'](https:\/\/(?:dl\.spotimate\.app|dl\.soundloaders\.app)[^"']+)["']/,
2126
+ ) ||
2127
+ dlHtml.match(
2128
+ /href=["'](https:\/\/[^"']*(?:cdnv1|\/v1\?token=)[^"']+)["']/,
2129
+ );
2130
+ if (match && match[1]) {
2131
+ foundLink = match[1];
2132
+ }
2133
+ }
2134
+ } catch (_) {}
2135
+ }
2136
+
2137
+ // 2. If SpotiDown or Spotimate fallback needed:
2138
+ if (!foundLink && baseVal) {
2139
+ let spData = dataVal;
2140
+ let spToken = tokenVal;
2141
+ let spBase = baseVal;
2142
+ let spCookies = cookiesStr;
2143
+
2144
+ // If came from Soundloaders, we need genuine SpotiDown tokens
2145
+ if (isSoundloaders || !spData || !spToken || spToken.startsWith("bccpF:")) {
2146
+ try {
2147
+ const rSession = await scraperFetch({
2148
+ url: "https://spotidown.app/action",
2149
+ method: "POST",
2150
+ data: `url=${encodeURIComponent(baseVal)}&g-recaptcha-response=dummy_token`,
2151
+ headers: {
2152
+ "Content-Type":
2153
+ "application/x-www-form-urlencoded; charset=UTF-8",
2154
+ "User-Agent": CHROME_UA,
2155
+ "X-Requested-With": "XMLHttpRequest",
2156
+ Origin: "https://spotidown.app",
2157
+ Referer: "https://spotidown.app/",
2158
+ },
2159
+ rawResponse: true,
2160
+ });
2161
+ const freshCookies = getCookiesFromHeaders(rSession.headers) || "";
2162
+ if (freshCookies) spCookies = freshCookies;
2163
+ let rData = rSession?.data;
2164
+ if (typeof rData === "string") {
2165
+ try {
2166
+ rData = JSON.parse(rData);
2167
+ } catch (_) {}
2168
+ }
2169
+ const html = rData?.data || rData?.html || "";
2170
+ const parser = new DOMParser();
2171
+ const doc = parser.parseFromString(html, "text/html");
2172
+ const form = doc.querySelector('form[name="submitspurl"]');
2173
+ if (form) {
2174
+ spData = form.querySelector('input[name="data"]')?.value || "";
2175
+ spToken = form.querySelector('input[name="token"]')?.value || "";
2176
+ spBase = form.querySelector('input[name="base"]')?.value || baseVal;
2177
+ }
2178
+ } catch (_) {}
1661
2179
  }
1662
- });
2180
+
2181
+ if (spData && spToken) {
2182
+ const mp = createMultipartBody({
2183
+ data: spData,
2184
+ base: spBase,
2185
+ token: spToken,
2186
+ });
2187
+
2188
+ const reqHeaders = {
2189
+ "Content-Type": mp.contentType,
2190
+ "User-Agent": CHROME_UA,
2191
+ "X-Requested-With": "XMLHttpRequest",
2192
+ Referer: "https://spotidown.app/",
2193
+ Origin: "https://spotidown.app",
2194
+ };
2195
+ if (spCookies) reqHeaders["Cookie"] = spCookies;
2196
+
2197
+ const res = await scraperFetch({
2198
+ url: "https://spotidown.app/action/track",
2199
+ method: "POST",
2200
+ headers: reqHeaders,
2201
+ data: mp.body,
2202
+ rawResponse: true,
2203
+ });
2204
+ let dd = res?.data ?? res;
2205
+ if (typeof dd === "string") {
2206
+ try {
2207
+ dd = JSON.parse(dd);
2208
+ } catch (_) {}
2209
+ }
2210
+ let dlHtml = (typeof dd === "object" ? dd?.data || dd?.html : dd) || "";
2211
+ const parser = new DOMParser();
2212
+ const doc = parser.parseFromString(dlHtml, "text/html");
2213
+ doc.querySelectorAll("a").forEach((a) => {
2214
+ const href = a.getAttribute("href");
2215
+ const text = a.textContent.trim();
2216
+ if (
2217
+ href &&
2218
+ href.startsWith("http") &&
2219
+ !href.includes("premium.html") &&
2220
+ !href.includes("ko-fi.com") &&
2221
+ text !== "Download Another Song"
2222
+ ) {
2223
+ if (!foundLink) foundLink = href;
2224
+ }
2225
+ });
2226
+ }
2227
+ }
2228
+
1663
2229
  if (!foundLink) throw new Error("Could not resolve Spotify download link.");
1664
2230
  return foundLink;
1665
2231
  }
@@ -1749,11 +2315,17 @@ export function sanitizeFilename(title, ext = "mp4") {
1749
2315
  }
1750
2316
 
1751
2317
  // 8. Stream Downloader with Progress Reporting
1752
- export async function downloadMediaFile(downloadUrl, outputPath, onProgress) {
2318
+ export async function downloadMediaFile(
2319
+ downloadUrl,
2320
+ outputPath,
2321
+ onProgress,
2322
+ extraHeaders = {},
2323
+ ) {
1753
2324
  const res = await fetch(downloadUrl, {
1754
2325
  headers: {
1755
2326
  "User-Agent": CHROME_UA,
1756
2327
  Accept: "*/*",
2328
+ ...extraHeaders,
1757
2329
  },
1758
2330
  });
1759
2331
 
@@ -1761,6 +2333,17 @@ export async function downloadMediaFile(downloadUrl, outputPath, onProgress) {
1761
2333
  throw new Error(`Download HTTP error: ${res.status} ${res.statusText}`);
1762
2334
  }
1763
2335
 
2336
+ const contentType = (res.headers.get("content-type") || "").toLowerCase();
2337
+ if (
2338
+ contentType.includes("text/html") &&
2339
+ !outputPath.endsWith(".html") &&
2340
+ !outputPath.endsWith(".txt")
2341
+ ) {
2342
+ throw new Error(
2343
+ "Received HTML webpage instead of a direct media stream. Please select a Direct MP4 stream.",
2344
+ );
2345
+ }
2346
+
1764
2347
  const totalBytes = parseInt(res.headers.get("content-length") || "0", 10);
1765
2348
  const fileStream = fs.createWriteStream(outputPath);
1766
2349