@coflyn/mori 1.0.1 → 1.1.0

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
@@ -3,8 +3,10 @@ import os from "os";
3
3
  import path from "path";
4
4
  import { exec, execSync } from "child_process";
5
5
  import { fileURLToPath } from "url";
6
+ import { createRequire } from "module";
6
7
  import { DOMParser } from "linkedom";
7
8
 
9
+ const require = createRequire(import.meta.url);
8
10
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
11
  const ROOT_DIR = path.resolve(__dirname, "..");
10
12
 
@@ -144,6 +146,30 @@ export function readClipboard() {
144
146
  });
145
147
  }
146
148
 
149
+ export function writeClipboard(text) {
150
+ if (!text) return Promise.resolve(false);
151
+ const plat = process.platform;
152
+ return new Promise((resolve) => {
153
+ let proc;
154
+ if (plat === "darwin") {
155
+ proc = exec("pbcopy", (err) => resolve(!err));
156
+ } else if (plat === "win32") {
157
+ proc = exec("clip", (err) => resolve(!err));
158
+ } else {
159
+ proc = exec(
160
+ "which wl-copy >/dev/null 2>&1 && wl-copy || xclip -selection clipboard 2>/dev/null || xsel -b -i 2>/dev/null",
161
+ (err) => resolve(!err),
162
+ );
163
+ }
164
+ if (proc && proc.stdin) {
165
+ proc.stdin.write(String(text));
166
+ proc.stdin.end();
167
+ } else {
168
+ resolve(false);
169
+ }
170
+ });
171
+ }
172
+
147
173
  export function decodeHtmlEntities(str) {
148
174
  if (!str || typeof str !== "string") return "";
149
175
  return str
@@ -287,18 +313,42 @@ export function getStats() {
287
313
  };
288
314
  }
289
315
 
290
- // 3. OTA Hot-Patching Engine
316
+ // 3. OTA Hot-Patching Engine (Mori Core + Scrapr Engine)
291
317
  const GITHUB_REPO = "coflyn/Mori";
292
318
  const OTA_DIR = CONFIG_DIR;
293
319
  export const OTA_BUNDLE_PATH = path.join(OTA_DIR, "scrapers-bundle.js");
294
320
  export const OTA_META_PATH = path.join(OTA_DIR, "scrapers-meta.json");
295
321
 
322
+ export const SCRAPR_DIR = path.join(CONFIG_DIR, "scrapr");
323
+ export const SCRAPR_BUNDLE_PATH = path.join(SCRAPR_DIR, "scrapr-bundle.cjs");
324
+ export const SCRAPR_META_PATH = path.join(SCRAPR_DIR, "version.json");
325
+ export const SCRAPR_VERSION_URL =
326
+ "https://raw.githubusercontent.com/coflyn/scrapr/main/package.json";
327
+ export const SCRAPR_BUNDLE_URL =
328
+ "https://raw.githubusercontent.com/coflyn/scrapr/main/bundle.cjs";
329
+ const SCRAPR_FALLBACK_VERSION = "1.3.1";
330
+
331
+ export function isNewerSemver(latest, current) {
332
+ if (!latest || !current) return false;
333
+ const l = String(latest).replace(/^v/, "").split(".").map(Number);
334
+ const c = String(current).replace(/^v/, "").split(".").map(Number);
335
+ for (let i = 0; i < 3; i++) {
336
+ const lPart = l[i] || 0;
337
+ const cPart = c[i] || 0;
338
+ if (lPart > cPart) return true;
339
+ if (lPart < cPart) return false;
340
+ }
341
+ return false;
342
+ }
343
+
296
344
  export function resetMori() {
297
345
  const filesToDelete = [
298
346
  CONFIG_PATH,
299
347
  HISTORY_PATH,
300
348
  OTA_BUNDLE_PATH,
301
349
  OTA_META_PATH,
350
+ SCRAPR_BUNDLE_PATH,
351
+ SCRAPR_META_PATH,
302
352
  ];
303
353
  for (const f of filesToDelete) {
304
354
  if (fs.existsSync(f)) {
@@ -312,40 +362,177 @@ export function resetMori() {
312
362
  export const OTA_VERSION_URL = `https://raw.githubusercontent.com/${GITHUB_REPO}/main/public/scrapers-version.json`;
313
363
  export const OTA_BUNDLE_URL = `https://raw.githubusercontent.com/${GITHUB_REPO}/main/public/js/scrapers/bundle.js`;
314
364
 
315
- function getBundledVersion() {
316
- const localMetaPath = path.join(__dirname, "scrapers-version.json");
317
- const rootMetaPath = path.join(ROOT_DIR, "public/scrapers-version.json");
318
- const bundledMetaPath = fs.existsSync(localMetaPath)
319
- ? localMetaPath
320
- : rootMetaPath;
365
+ export function isMoriInstalled() {
366
+ return fs.existsSync(OTA_BUNDLE_PATH);
367
+ }
321
368
 
322
- if (fs.existsSync(bundledMetaPath)) {
323
- try {
324
- const data = JSON.parse(fs.readFileSync(bundledMetaPath, "utf8"));
325
- return data.scraperVersion || 1;
326
- } catch (_) {}
327
- }
328
- return 1;
369
+ export function isScraprInstalled() {
370
+ return fs.existsSync(SCRAPR_BUNDLE_PATH);
329
371
  }
330
372
 
331
373
  export function getActiveScraperVersion() {
332
374
  if (fs.existsSync(OTA_META_PATH)) {
333
375
  try {
334
376
  const meta = JSON.parse(fs.readFileSync(OTA_META_PATH, "utf8"));
335
- if (meta.scraperVersion && meta.scraperVersion >= getBundledVersion()) {
336
- return meta.scraperVersion;
337
- }
377
+ return meta.scraperVersion || null;
378
+ } catch (_) {}
379
+ }
380
+ return null;
381
+ }
382
+
383
+ export function getActiveScraprVersion() {
384
+ if (fs.existsSync(SCRAPR_META_PATH)) {
385
+ try {
386
+ const meta = JSON.parse(fs.readFileSync(SCRAPR_META_PATH, "utf8"));
387
+ return meta.version || null;
338
388
  } catch (_) {}
339
389
  }
340
- return getBundledVersion();
390
+ return null;
391
+ }
392
+
393
+ /**
394
+ * Downloads and installs Mori Core Engine into ~/.mori/
395
+ */
396
+ export async function downloadMoriEngine(onProgress) {
397
+ if (onProgress) onProgress("Fetching Mori version metadata...");
398
+ const metaRes = await fetch(OTA_VERSION_URL, {
399
+ signal: AbortSignal.timeout(10000),
400
+ headers: { "User-Agent": "Mori-CLI", "Cache-Control": "no-cache" },
401
+ });
402
+ if (!metaRes.ok) throw new Error(`Failed to fetch Mori version (HTTP ${metaRes.status})`);
403
+ const meta = await metaRes.json();
404
+
405
+ if (onProgress) onProgress("Downloading Mori Engine bundle (~80 KB)...");
406
+ const bundleRes = await fetch(OTA_BUNDLE_URL, {
407
+ signal: AbortSignal.timeout(30000),
408
+ headers: { "User-Agent": "Mori-CLI", "Cache-Control": "no-cache" },
409
+ });
410
+ if (!bundleRes.ok) throw new Error(`Failed to download Mori bundle (HTTP ${bundleRes.status})`);
411
+ const bundleText = await bundleRes.text();
412
+ if (!bundleText || bundleText.length < 5000) {
413
+ throw new Error("Invalid Mori bundle payload received.");
414
+ }
415
+
416
+ if (!fs.existsSync(OTA_DIR)) {
417
+ fs.mkdirSync(OTA_DIR, { recursive: true });
418
+ }
419
+
420
+ fs.writeFileSync(OTA_BUNDLE_PATH, bundleText, "utf8");
421
+ fs.writeFileSync(
422
+ OTA_META_PATH,
423
+ JSON.stringify(
424
+ {
425
+ scraperVersion: meta.scraperVersion || "1.0.0",
426
+ updatedAt: Date.now(),
427
+ sourceHash: meta.sourceHash || "",
428
+ changelog: meta.changelog || "",
429
+ },
430
+ null,
431
+ 2,
432
+ ),
433
+ "utf8",
434
+ );
435
+
436
+ cachedMoriScrapers = null;
437
+ return { success: true, version: meta.scraperVersion || "1.0.0" };
341
438
  }
342
439
 
343
440
  /**
344
- * Checks for OTA updates from GitHub raw.
345
- * If force=true, checks immediately and throws on failure.
346
- * If force=false, checks silently with low timeout (2s).
441
+ * Downloads and installs Scrapr Engine into ~/.mori/scrapr/
442
+ */
443
+ export async function downloadScraprEngine(onProgress) {
444
+ if (onProgress) onProgress("Fetching Scrapr metadata...");
445
+ let version = SCRAPR_FALLBACK_VERSION;
446
+ try {
447
+ const metaRes = await fetch(SCRAPR_VERSION_URL, {
448
+ signal: AbortSignal.timeout(10000),
449
+ headers: { "User-Agent": "Mori-CLI", "Cache-Control": "no-cache" },
450
+ });
451
+ if (metaRes.ok) {
452
+ const meta = await metaRes.json();
453
+ if (meta.version) version = meta.version;
454
+ }
455
+ } catch (_) {}
456
+
457
+ if (onProgress) onProgress("Downloading Scrapr Engine bundle (~2.7 MB)...");
458
+ let bundleText = "";
459
+
460
+ // 1. Try remote GitHub raw URL
461
+ try {
462
+ const bundleRes = await fetch(SCRAPR_BUNDLE_URL, {
463
+ signal: AbortSignal.timeout(45000),
464
+ headers: { "User-Agent": "Mori-CLI", "Cache-Control": "no-cache" },
465
+ });
466
+ if (bundleRes.ok) {
467
+ bundleText = await bundleRes.text();
468
+ }
469
+ } catch (_) {}
470
+
471
+ // 2. Local fallback during development if remote is not yet pushed
472
+ if (!bundleText || bundleText.length < 50000) {
473
+ const localDevScrapr = path.resolve(__dirname, "../../../scrapr/bundle.cjs");
474
+ if (fs.existsSync(localDevScrapr)) {
475
+ bundleText = fs.readFileSync(localDevScrapr, "utf8");
476
+ }
477
+ }
478
+
479
+ if (!bundleText || bundleText.length < 50000) {
480
+ throw new Error(
481
+ "Failed to download Scrapr bundle. Ensure bundle.cjs is published or pushed to coflyn/scrapr.",
482
+ );
483
+ }
484
+
485
+ if (!fs.existsSync(SCRAPR_DIR)) {
486
+ fs.mkdirSync(SCRAPR_DIR, { recursive: true });
487
+ }
488
+
489
+ fs.writeFileSync(SCRAPR_BUNDLE_PATH, bundleText, "utf8");
490
+ fs.writeFileSync(
491
+ SCRAPR_META_PATH,
492
+ JSON.stringify(
493
+ {
494
+ version,
495
+ updatedAt: Date.now(),
496
+ },
497
+ null,
498
+ 2,
499
+ ),
500
+ "utf8",
501
+ );
502
+
503
+ cachedScrapr = null;
504
+ return { success: true, version };
505
+ }
506
+
507
+ export function uninstallMoriEngine() {
508
+ if (fs.existsSync(OTA_BUNDLE_PATH)) {
509
+ try { fs.unlinkSync(OTA_BUNDLE_PATH); } catch (_) {}
510
+ }
511
+ if (fs.existsSync(OTA_META_PATH)) {
512
+ try { fs.unlinkSync(OTA_META_PATH); } catch (_) {}
513
+ }
514
+ cachedMoriScrapers = null;
515
+ return true;
516
+ }
517
+
518
+ export function uninstallScraprEngine() {
519
+ if (fs.existsSync(SCRAPR_BUNDLE_PATH)) {
520
+ try { fs.unlinkSync(SCRAPR_BUNDLE_PATH); } catch (_) {}
521
+ }
522
+ if (fs.existsSync(SCRAPR_META_PATH)) {
523
+ try { fs.unlinkSync(SCRAPR_META_PATH); } catch (_) {}
524
+ }
525
+ cachedScrapr = null;
526
+ return true;
527
+ }
528
+
529
+ /**
530
+ * Checks for Mori Core OTA updates from GitHub raw.
347
531
  */
348
532
  export async function checkForOtaUpdate(force = false) {
533
+ if (!isMoriInstalled()) {
534
+ return { updated: false, notInstalled: true };
535
+ }
349
536
  try {
350
537
  const metaRes = await fetch(OTA_VERSION_URL, {
351
538
  signal: AbortSignal.timeout(force ? 8000 : 2500),
@@ -357,7 +544,6 @@ export async function checkForOtaUpdate(force = false) {
357
544
  const currentVer = getActiveScraperVersion();
358
545
 
359
546
  if (remoteMeta.scraperVersion && remoteMeta.scraperVersion > currentVer) {
360
- // Pull new bundle
361
547
  const bundleRes = await fetch(OTA_BUNDLE_URL, {
362
548
  signal: AbortSignal.timeout(15000),
363
549
  headers: { "User-Agent": "Mori-CLI-OTA", "Cache-Control": "no-cache" },
@@ -390,6 +576,8 @@ export async function checkForOtaUpdate(force = false) {
390
576
  "utf8",
391
577
  );
392
578
 
579
+ cachedMoriScrapers = null;
580
+
393
581
  return {
394
582
  updated: true,
395
583
  oldVersion: currentVer,
@@ -405,53 +593,219 @@ export async function checkForOtaUpdate(force = false) {
405
593
  }
406
594
  }
407
595
 
408
- // 3. Load Scraper Core (OTA Patch > Bundled Asset, with Safe-Mode Recovery)
409
- function loadScraperEngine() {
596
+ /**
597
+ * Checks for Scrapr Engine OTA updates from GitHub raw.
598
+ */
599
+ export async function checkForScraprOtaUpdate(force = false) {
600
+ if (!isScraprInstalled()) {
601
+ return { updated: false, notInstalled: true };
602
+ }
603
+ try {
604
+ const metaRes = await fetch(SCRAPR_VERSION_URL, {
605
+ signal: AbortSignal.timeout(force ? 8000 : 2500),
606
+ headers: { "User-Agent": "Mori-CLI-OTA", "Cache-Control": "no-cache" },
607
+ });
608
+ if (!metaRes.ok) return { updated: false, reason: "Fetch error" };
609
+
610
+ const remoteMeta = await metaRes.json();
611
+ const currentVer = getActiveScraprVersion();
612
+
613
+ if (remoteMeta.version && isNewerSemver(remoteMeta.version, currentVer)) {
614
+ const bundleRes = await fetch(SCRAPR_BUNDLE_URL, {
615
+ signal: AbortSignal.timeout(30000),
616
+ headers: { "User-Agent": "Mori-CLI-OTA", "Cache-Control": "no-cache" },
617
+ });
618
+ if (!bundleRes.ok)
619
+ return { updated: false, reason: "Scrapr bundle download error" };
620
+
621
+ const bundleText = await bundleRes.text();
622
+ if (!bundleText || bundleText.length < 50000) {
623
+ return { updated: false, reason: "Invalid Scrapr bundle payload" };
624
+ }
625
+
626
+ if (!fs.existsSync(SCRAPR_DIR)) {
627
+ fs.mkdirSync(SCRAPR_DIR, { recursive: true });
628
+ }
629
+
630
+ fs.writeFileSync(SCRAPR_BUNDLE_PATH, bundleText, "utf8");
631
+ fs.writeFileSync(
632
+ SCRAPR_META_PATH,
633
+ JSON.stringify(
634
+ {
635
+ version: remoteMeta.version,
636
+ updatedAt: Date.now(),
637
+ },
638
+ null,
639
+ 2,
640
+ ),
641
+ "utf8",
642
+ );
643
+
644
+ cachedScrapr = null;
645
+
646
+ return {
647
+ updated: true,
648
+ oldVersion: currentVer,
649
+ newVersion: remoteMeta.version,
650
+ };
651
+ }
652
+
653
+ return { updated: false, currentVersion: currentVer, latest: true };
654
+ } catch (err) {
655
+ if (force) throw err;
656
+ return { updated: false, error: err.message };
657
+ }
658
+ }
659
+
660
+ // 3. Load Scraper Core (Mori Engine)
661
+ let cachedMoriScrapers = null;
662
+
663
+ export function loadScraperEngine() {
664
+ if (cachedMoriScrapers) return cachedMoriScrapers;
665
+
410
666
  const localBundlePath = path.join(__dirname, "bundle.js");
411
667
  const rootBundlePath = path.join(ROOT_DIR, "public/js/scrapers/bundle.js");
412
- const bundledBundlePath = fs.existsSync(localBundlePath)
413
- ? localBundlePath
414
- : rootBundlePath;
415
668
 
416
- // Attempt A: Load OTA patch from ~/.mori/scrapers-bundle.js
417
- if (fs.existsSync(OTA_BUNDLE_PATH) && fs.existsSync(OTA_META_PATH)) {
669
+ // Priority 1: ~/.mori/scrapers-bundle.js
670
+ if (fs.existsSync(OTA_BUNDLE_PATH)) {
418
671
  try {
419
- const meta = JSON.parse(fs.readFileSync(OTA_META_PATH, "utf8"));
420
- if (meta.scraperVersion && meta.scraperVersion >= getBundledVersion()) {
421
- const patchCode = fs.readFileSync(OTA_BUNDLE_PATH, "utf8");
422
- (0, eval)(patchCode);
423
- if (globalThis.__MoriCoreScrapers) {
424
- return globalThis.__MoriCoreScrapers;
425
- }
672
+ const patchCode = fs.readFileSync(OTA_BUNDLE_PATH, "utf8");
673
+ (0, eval)(patchCode);
674
+ if (globalThis.__MoriCoreScrapers) {
675
+ cachedMoriScrapers = globalThis.__MoriCoreScrapers;
676
+ return cachedMoriScrapers;
426
677
  }
427
- } catch (err) {
428
- // Safe-mode recovery: patch corrupted, delete it and fallback
678
+ } catch (_) {
429
679
  try {
430
680
  fs.unlinkSync(OTA_BUNDLE_PATH);
431
- fs.unlinkSync(OTA_META_PATH);
681
+ if (fs.existsSync(OTA_META_PATH)) fs.unlinkSync(OTA_META_PATH);
432
682
  } catch (_) {}
433
683
  }
434
684
  }
435
685
 
436
- // Attempt B: Bundled fallback
437
- if (!fs.existsSync(bundledBundlePath)) {
438
- throw new Error(
439
- `Scraper bundle not found at ${bundledBundlePath}. Run npm run compile:scrapers.`,
440
- );
686
+ // Priority 2: Dev path fallback
687
+ const devPath = fs.existsSync(localBundlePath)
688
+ ? localBundlePath
689
+ : fs.existsSync(rootBundlePath)
690
+ ? rootBundlePath
691
+ : null;
692
+
693
+ if (devPath) {
694
+ try {
695
+ const bundleCode = fs.readFileSync(devPath, "utf8");
696
+ (0, eval)(bundleCode);
697
+ if (globalThis.__MoriCoreScrapers) {
698
+ cachedMoriScrapers = globalThis.__MoriCoreScrapers;
699
+ return cachedMoriScrapers;
700
+ }
701
+ } catch (_) {}
702
+ }
703
+
704
+ throw new Error("Mori Engine not installed. Use /engine to install.");
705
+ }
706
+
707
+ // 3b. Load Scrapr Engine (Engine 2)
708
+ let cachedScrapr = null;
709
+
710
+ export function loadScraprEngine() {
711
+ if (cachedScrapr) return cachedScrapr;
712
+
713
+ const localBundlePath = path.join(__dirname, "scrapr-bundle.cjs");
714
+ const devScraprPath = path.resolve(__dirname, "../../../scrapr/bundle.cjs");
715
+
716
+ // Priority 1: ~/.mori/scrapr/scrapr-bundle.cjs
717
+ if (fs.existsSync(SCRAPR_BUNDLE_PATH)) {
718
+ try {
719
+ cachedScrapr = require(SCRAPR_BUNDLE_PATH);
720
+ if (cachedScrapr && cachedScrapr.resolver) {
721
+ return cachedScrapr;
722
+ }
723
+ } catch (_) {
724
+ try {
725
+ fs.unlinkSync(SCRAPR_BUNDLE_PATH);
726
+ if (fs.existsSync(SCRAPR_META_PATH)) fs.unlinkSync(SCRAPR_META_PATH);
727
+ } catch (_) {}
728
+ }
441
729
  }
442
730
 
443
- const bundleCode = fs.readFileSync(bundledBundlePath, "utf8");
444
- (0, eval)(bundleCode);
731
+ // Priority 2: Dev path fallback
732
+ const fallback = fs.existsSync(localBundlePath)
733
+ ? localBundlePath
734
+ : fs.existsSync(devScraprPath)
735
+ ? devScraprPath
736
+ : null;
445
737
 
446
- if (!globalThis.__MoriCoreScrapers) {
447
- throw new Error("Failed to initialize __MoriCoreScrapers from bundle.");
738
+ if (fallback) {
739
+ try {
740
+ cachedScrapr = require(fallback);
741
+ if (cachedScrapr && cachedScrapr.resolver) {
742
+ return cachedScrapr;
743
+ }
744
+ } catch (_) {}
448
745
  }
449
- return globalThis.__MoriCoreScrapers;
746
+
747
+ throw new Error("Scrapr Engine not installed. Use /engine to install.");
450
748
  }
451
749
 
452
- export const scrapers = loadScraperEngine();
750
+ function getScraperFetch() {
751
+ try {
752
+ const s = loadScraperEngine();
753
+ if (s?.scraperFetch) return s.scraperFetch;
754
+ } catch (_) {}
755
+ return async function (opts) {
756
+ const res = await fetch(opts.url, {
757
+ method: opts.method || (opts.data ? "POST" : "GET"),
758
+ headers: opts.headers || {},
759
+ body: typeof opts.data === "object" ? JSON.stringify(opts.data) : opts.data,
760
+ });
761
+ const text = await res.text();
762
+ return opts.rawResponse
763
+ ? {
764
+ status: res.status,
765
+ headers: Object.fromEntries(res.headers.entries()),
766
+ data: text,
767
+ url: res.url,
768
+ }
769
+ : text;
770
+ };
771
+ }
453
772
 
454
773
  // 4. Platform Detection
774
+ export const SCRAPR_ONLY_PLATFORMS = new Set([
775
+ "soundcloud",
776
+ "mediafire",
777
+ "sfile",
778
+ "pixeldrain",
779
+ "catbox",
780
+ "krakenfiles",
781
+ "gdrive",
782
+ "doodstream",
783
+ "safelinku",
784
+ "sub2unlock",
785
+ "rekonise",
786
+ "unshorten",
787
+ ]);
788
+
789
+ export const RESOLVER_LINK_PLATFORMS = new Set([
790
+ "catbox",
791
+ "pixeldrain",
792
+ "safelinku",
793
+ "sfile",
794
+ "mediafire",
795
+ "krakenfiles",
796
+ "gdrive",
797
+ "sub2unlock",
798
+ "rekonise",
799
+ "unshorten",
800
+ ]);
801
+
802
+ export const SHORTLINK_PLATFORMS = new Set([
803
+ "safelinku",
804
+ "sub2unlock",
805
+ "rekonise",
806
+ "unshorten",
807
+ ]);
808
+
455
809
  export function detectPlatform(rawUrl) {
456
810
  if (!rawUrl || typeof rawUrl !== "string") return null;
457
811
  const url = rawUrl.toLowerCase();
@@ -467,6 +821,8 @@ export function detectPlatform(rawUrl) {
467
821
  )
468
822
  return "twitter";
469
823
  if (url.includes("spotify.com")) return "spotify";
824
+ if (url.includes("soundcloud.com") || url.includes("on.soundcloud.com"))
825
+ return "soundcloud";
470
826
  if (url.includes("pinterest.com") || url.includes("pin.it"))
471
827
  return "pinterest";
472
828
  if (url.includes("music.apple.com")) return "applemusic";
@@ -502,10 +858,58 @@ export function detectPlatform(rawUrl) {
502
858
  url.includes("tibibox")
503
859
  )
504
860
  return "terabox";
861
+ // File hosts & Resolvers (Engine 2: Scrapr)
862
+ if (url.includes("mediafire.com")) return "mediafire";
863
+ if (url.includes("sfile.mobi") || url.includes("sfile.co")) return "sfile";
864
+ if (url.includes("pixeldrain.com")) return "pixeldrain";
865
+ if (
866
+ url.includes("catbox.moe") ||
867
+ url.includes("litterbox.catbox.moe") ||
868
+ url.includes("litter.catbox.moe")
869
+ )
870
+ return "catbox";
871
+ if (url.includes("krakenfiles.com")) return "krakenfiles";
872
+ if (url.includes("drive.google.com") || url.includes("docs.google.com/file"))
873
+ return "gdrive";
874
+ if (
875
+ /(?:doodstream\.com|ds2play\.com|doods\.pro|dood\.(?:to|so|ws|pm|wf|cx|sh|watch))/i.test(
876
+ url,
877
+ )
878
+ )
879
+ return "doodstream";
880
+ if (
881
+ url.includes("safelinku.com") ||
882
+ url.includes("sfl.gl") ||
883
+ url.includes("semawur.com") ||
884
+ url.includes("safelink.id") ||
885
+ url.includes("sfl.inc") ||
886
+ url.includes("khaddavi.net")
887
+ )
888
+ return "safelinku";
889
+ if (
890
+ url.includes("sub2unlock.com") ||
891
+ url.includes("sub2unlock.net") ||
892
+ url.includes("sub2unlock.io") ||
893
+ url.includes("sub2unlock.me") ||
894
+ url.includes("sub4unlock.com") ||
895
+ url.includes("sub4unlock.io") ||
896
+ url.includes("sub4unlock.net")
897
+ )
898
+ return "sub2unlock";
899
+ if (url.includes("rekonise.com")) return "rekonise";
900
+ if (
901
+ url.includes("bit.ly") ||
902
+ url.includes("tinyurl.com") ||
903
+ url.includes("dub.sh") ||
904
+ url.includes("cutt.ly") ||
905
+ url.includes("t.co/") ||
906
+ url.includes("shorturl.at")
907
+ )
908
+ return "unshorten";
505
909
  return null;
506
910
  }
507
911
 
508
- export const PLATFORM_SERVERS = {
912
+ export const MORI_PLATFORM_SERVERS = {
509
913
  tiktok: [
510
914
  { id: "auto", name: "Auto (Server 1 → Server 2 fallback)" },
511
915
  { id: "server1", name: "Server 1 (TikTokIO)" },
@@ -533,34 +937,98 @@ export const PLATFORM_SERVERS = {
533
937
  ],
534
938
  };
535
939
 
536
- // 5. Unified Scraper with Automatic Server Fallbacks
537
- export async function scrapeUrl(url, serverPreference = "auto") {
538
- const platform = detectPlatform(url);
539
- if (!platform) {
540
- throw new Error("URL is not supported by Mori.");
940
+ export const SCRAPR_PLATFORM_SERVERS = {
941
+ tiktok: [
942
+ { id: "auto", name: "Auto (Cascade all 5 servers)" },
943
+ { id: "tiktokio", name: "TikTokIO (Fast, HD)" },
944
+ { id: "tikdownloader", name: "TikDownloader (Direct HD)" },
945
+ { id: "snaptik", name: "SnapTik (Popular, No Watermark)" },
946
+ { id: "savetik", name: "SaveTik (Alternative)" },
947
+ { id: "ssstik", name: "SSSTik (Fallback)" },
948
+ ],
949
+ instagram: [
950
+ { id: "auto", name: "Auto (Cascade all 4 servers)" },
951
+ { id: "indown", name: "InDown (Fast, High Quality)" },
952
+ { id: "snapsave", name: "SnapSave (Reels/Stories/Posts)" },
953
+ { id: "snapinsta", name: "SnapInsta (Alternative)" },
954
+ { id: "direct", name: "Direct (Public Posts)" },
955
+ ],
956
+ youtube: [
957
+ { id: "auto", name: "Auto (ytmp3.gg → ytmp3 fallback)" },
958
+ { id: "ytmp3gg", name: "ytmp3.gg (Fast, 1080p/720p/MP3)" },
959
+ { id: "ytmp3", name: "ytmp3 (Alternative)" },
960
+ ],
961
+ twitter: [
962
+ { id: "auto", name: "Auto (Cascade all 4 servers)" },
963
+ { id: "tvd", name: "TwitterVideoDownloader (HD)" },
964
+ { id: "savetwt", name: "SaveTWT (Fast)" },
965
+ { id: "tweeload", name: "TweeLoad (Alternative)" },
966
+ { id: "direct", name: "Direct FXTwitter" },
967
+ ],
968
+ spotify: [
969
+ { id: "auto", name: "Auto (Cascade all 4 servers)" },
970
+ { id: "spotidown", name: "SpotiDown (Fast 320kbps)" },
971
+ { id: "soundloaders", name: "SoundLoaders (Reliable)" },
972
+ { id: "spotmate", name: "SpotMate" },
973
+ { id: "spotisaver", name: "SpotiSaver" },
974
+ ],
975
+ facebook: [
976
+ { id: "auto", name: "Auto (SnapSave → FDown fallback)" },
977
+ { id: "snapsave", name: "SnapSave (HD)" },
978
+ { id: "fdown", name: "FDown (Alternative)" },
979
+ ],
980
+ pinterest: [
981
+ { id: "auto", name: "Auto (PinDown → Direct fallback)" },
982
+ { id: "pindown", name: "PinDown" },
983
+ { id: "direct", name: "Direct" },
984
+ ],
985
+ bandcamp: [
986
+ { id: "auto", name: "Auto (Direct → BandcampDownloader fallback)" },
987
+ { id: "direct", name: "Direct Stream" },
988
+ { id: "bandcampdownloader", name: "BandcampDownloader" },
989
+ ],
990
+ };
991
+
992
+ export function getPlatformServers(platform, engine = "auto") {
993
+ if (engine === "scrapr") {
994
+ return SCRAPR_PLATFORM_SERVERS[platform] || null;
541
995
  }
996
+ if (engine === "mori") {
997
+ return MORI_PLATFORM_SERVERS[platform] || null;
998
+ }
999
+ return SCRAPR_PLATFORM_SERVERS[platform] || MORI_PLATFORM_SERVERS[platform] || null;
1000
+ }
1001
+
1002
+ export const PLATFORM_SERVERS = MORI_PLATFORM_SERVERS;
542
1003
 
543
- // Normalize server input (e.g. "1" -> "server1", "2" -> "server2")
1004
+ // 5a. Engine 1: Mori Scraper Core
1005
+ export async function scrapeWithMori(url, platform, serverPreference = "auto") {
1006
+ const scrapers = loadScraperEngine();
544
1007
  let srv = serverPreference;
545
1008
  if (srv === "1") srv = "server1";
546
1009
  if (srv === "2") srv = "server2";
547
1010
 
548
1011
  let res = null;
1012
+ let usedServer = "";
549
1013
 
550
1014
  switch (platform) {
551
1015
  case "tiktok": {
552
1016
  if (srv === "server2") {
553
1017
  scrapers.setTikTokSource("tikdownloader");
554
1018
  res = await scrapers.scrapeTikTok(url);
1019
+ usedServer = "TikDownloader";
555
1020
  } else if (srv === "server1") {
556
1021
  scrapers.setTikTokSource("tiktokio");
557
1022
  res = await scrapers.scrapeTikTok(url);
1023
+ usedServer = "TikTokIO";
558
1024
  } else {
559
1025
  scrapers.setTikTokSource("tiktokio");
560
1026
  res = await scrapers.scrapeTikTok(url);
1027
+ usedServer = "TikTokIO";
561
1028
  if (!res?.status) {
562
1029
  scrapers.setTikTokSource("tikdownloader");
563
1030
  res = await scrapers.scrapeTikTok(url);
1031
+ usedServer = "TikDownloader";
564
1032
  }
565
1033
  }
566
1034
  break;
@@ -569,15 +1037,19 @@ export async function scrapeUrl(url, serverPreference = "auto") {
569
1037
  if (srv === "server2") {
570
1038
  scrapers.setInstagramSource("savevid");
571
1039
  res = await scrapers.scrapeInstagram(url);
1040
+ usedServer = "SaveVid";
572
1041
  } else if (srv === "server1") {
573
1042
  scrapers.setInstagramSource("indown");
574
1043
  res = await scrapers.scrapeInstagram(url);
1044
+ usedServer = "InDown";
575
1045
  } else {
576
1046
  scrapers.setInstagramSource("indown");
577
1047
  res = await scrapers.scrapeInstagram(url);
1048
+ usedServer = "InDown";
578
1049
  if (!res?.status) {
579
1050
  scrapers.setInstagramSource("savevid");
580
1051
  res = await scrapers.scrapeInstagram(url);
1052
+ usedServer = "SaveVid";
581
1053
  }
582
1054
  }
583
1055
  break;
@@ -586,15 +1058,19 @@ export async function scrapeUrl(url, serverPreference = "auto") {
586
1058
  if (srv === "server2") {
587
1059
  scrapers.setYouTubeSource("mobi");
588
1060
  res = await scrapers.scrapeYouTube(url);
1061
+ usedServer = "ytmp3.mobi";
589
1062
  } else if (srv === "server1") {
590
1063
  scrapers.setYouTubeSource("gg");
591
1064
  res = await scrapers.scrapeYouTube(url);
1065
+ usedServer = "ytmp3.gg";
592
1066
  } else {
593
1067
  scrapers.setYouTubeSource("gg");
594
1068
  res = await scrapers.scrapeYouTube(url);
1069
+ usedServer = "ytmp3.gg";
595
1070
  if (!res?.status) {
596
1071
  scrapers.setYouTubeSource("mobi");
597
1072
  res = await scrapers.scrapeYouTube(url);
1073
+ usedServer = "ytmp3.mobi";
598
1074
  }
599
1075
  }
600
1076
  break;
@@ -603,15 +1079,19 @@ export async function scrapeUrl(url, serverPreference = "auto") {
603
1079
  if (srv === "server2") {
604
1080
  scrapers.setTwitterSource("savetwt");
605
1081
  res = await scrapers.scrapeTwitter(url);
1082
+ usedServer = "SaveTWT";
606
1083
  } else if (srv === "server1") {
607
1084
  scrapers.setTwitterSource("tvd");
608
1085
  res = await scrapers.scrapeTwitter(url);
1086
+ usedServer = "TwitterVideoDownloader";
609
1087
  } else {
610
1088
  scrapers.setTwitterSource("tvd");
611
1089
  res = await scrapers.scrapeTwitter(url);
1090
+ usedServer = "TwitterVideoDownloader";
612
1091
  if (!res?.status) {
613
1092
  scrapers.setTwitterSource("savetwt");
614
1093
  res = await scrapers.scrapeTwitter(url);
1094
+ usedServer = "SaveTWT";
615
1095
  }
616
1096
  }
617
1097
  break;
@@ -620,51 +1100,66 @@ export async function scrapeUrl(url, serverPreference = "auto") {
620
1100
  if (srv === "server2") {
621
1101
  scrapers.setSpotifySource("soundloaders");
622
1102
  res = await scrapers.scrapeSpotify(url);
1103
+ usedServer = "SoundLoaders";
623
1104
  } else if (srv === "server1") {
624
1105
  scrapers.setSpotifySource("spotidown");
625
1106
  res = await scrapers.scrapeSpotify(url);
1107
+ usedServer = "SpotiDown";
626
1108
  } else {
627
1109
  scrapers.setSpotifySource("spotidown");
628
1110
  res = await scrapers.scrapeSpotify(url);
1111
+ usedServer = "SpotiDown";
629
1112
  if (!res?.status) {
630
1113
  scrapers.setSpotifySource("soundloaders");
631
1114
  res = await scrapers.scrapeSpotify(url);
1115
+ usedServer = "SoundLoaders";
632
1116
  }
633
1117
  }
634
1118
  break;
635
1119
  }
636
1120
  case "pinterest":
637
1121
  res = await scrapers.scrapePinterest(url);
1122
+ usedServer = "Pinterest";
638
1123
  break;
639
1124
  case "applemusic":
640
1125
  res = await scrapers.scrapeAppleMusic(url);
1126
+ usedServer = "Aplmate";
641
1127
  break;
642
1128
  case "facebook":
643
1129
  res = await scrapers.scrapeFacebook(url);
1130
+ usedServer = "SnapSave";
644
1131
  break;
645
1132
  case "rednote":
646
1133
  res = await scrapers.scrapeRedNote(url);
1134
+ usedServer = "RedNote";
647
1135
  break;
648
1136
  case "douyin":
649
1137
  res = await scrapers.scrapeDouyin(url);
1138
+ usedServer = "Douyin";
650
1139
  break;
651
1140
  case "bilibili":
652
1141
  res = await scrapers.scrapeBilibili(url);
1142
+ usedServer = "Bilibili";
653
1143
  break;
654
1144
  case "threads":
655
1145
  res = await scrapers.scrapeThreads(url);
1146
+ usedServer = "Threads";
656
1147
  break;
657
1148
  case "bandcamp":
658
1149
  res = await scrapers.scrapeBandcamp(url);
1150
+ usedServer = "Bandcamp";
659
1151
  break;
660
1152
  case "pixiv":
661
1153
  res = await scrapers.scrapePixiv(url);
1154
+ usedServer = "Pixiv";
662
1155
  break;
663
1156
  case "reddit":
664
1157
  res = await scrapers.scrapeReddit(url);
1158
+ usedServer = "RapidSave";
665
1159
  break;
666
1160
  case "terabox":
667
1161
  res = await scrapers.scrapeTeraBox(url);
1162
+ usedServer = "TeraBox";
668
1163
  break;
669
1164
  default:
670
1165
  throw new Error(`Platform handler missing for ${platform}`);
@@ -681,16 +1176,406 @@ export async function scrapeUrl(url, serverPreference = "auto") {
681
1176
 
682
1177
  return {
683
1178
  platform,
1179
+ engine: "mori",
1180
+ server: usedServer,
684
1181
  ...result,
685
1182
  };
686
1183
  }
687
1184
 
1185
+ // 5b. Engine 2: Scrapr Stand-alone Scraper & Resolver
1186
+ export async function scrapeWithScrapr(
1187
+ url,
1188
+ platform,
1189
+ serverPreference = "auto",
1190
+ ) {
1191
+ const scrapr = loadScraprEngine();
1192
+ let srv = serverPreference;
1193
+ if (srv === "1") srv = "server1";
1194
+ if (srv === "2") srv = "server2";
1195
+
1196
+ let res = null;
1197
+ let usedServer = "";
1198
+
1199
+ switch (platform) {
1200
+ case "tiktok": {
1201
+ if (srv === "tiktokio" || srv === "server1") {
1202
+ res = await scrapr.tiktok.tiktokio(url);
1203
+ usedServer = "TikTokIO";
1204
+ } else if (srv === "tikdownloader" || srv === "server2") {
1205
+ res = await scrapr.tiktok.tikdownloader(url);
1206
+ usedServer = "TikDownloader";
1207
+ } else if (srv === "snaptik") {
1208
+ res = await scrapr.tiktok.snaptik(url);
1209
+ usedServer = "SnapTik";
1210
+ } else if (srv === "savetik") {
1211
+ res = await scrapr.tiktok.savetik(url);
1212
+ usedServer = "SaveTik";
1213
+ } else if (srv === "ssstik") {
1214
+ res = await scrapr.tiktok.ssstik(url);
1215
+ usedServer = "SSSTik";
1216
+ } else {
1217
+ res = await scrapr.tiktok.tiktokio(url);
1218
+ usedServer = "TikTokIO";
1219
+ if (!res?.status) {
1220
+ res = await scrapr.tiktok.tikdownloader(url);
1221
+ usedServer = "TikDownloader";
1222
+ }
1223
+ if (!res?.status) {
1224
+ res = await scrapr.tiktok.snaptik(url);
1225
+ usedServer = "SnapTik";
1226
+ }
1227
+ if (!res?.status) {
1228
+ res = await scrapr.tiktok.savetik(url);
1229
+ usedServer = "SaveTik";
1230
+ }
1231
+ if (!res?.status) {
1232
+ res = await scrapr.tiktok.ssstik(url);
1233
+ usedServer = "SSSTik";
1234
+ }
1235
+ }
1236
+ break;
1237
+ }
1238
+ case "instagram": {
1239
+ if (srv === "indown" || srv === "server1") {
1240
+ res = await scrapr.instagram.indown(url);
1241
+ usedServer = "InDown";
1242
+ } else if (srv === "snapsave" || srv === "server2") {
1243
+ res = await scrapr.instagram.snapsave(url);
1244
+ usedServer = "SnapSave";
1245
+ } else if (srv === "snapinsta") {
1246
+ res = await scrapr.instagram.snapinsta(url);
1247
+ usedServer = "SnapInsta";
1248
+ } else if (srv === "direct") {
1249
+ res = await scrapr.instagram.direct(url);
1250
+ usedServer = "Direct";
1251
+ } else {
1252
+ res = await scrapr.instagram.indown(url);
1253
+ usedServer = "InDown";
1254
+ if (!res?.status) {
1255
+ res = await scrapr.instagram.snapsave(url);
1256
+ usedServer = "SnapSave";
1257
+ }
1258
+ if (!res?.status) {
1259
+ res = await scrapr.instagram.snapinsta(url);
1260
+ usedServer = "SnapInsta";
1261
+ }
1262
+ if (!res?.status) {
1263
+ res = await scrapr.instagram.direct(url);
1264
+ usedServer = "Direct";
1265
+ }
1266
+ }
1267
+ break;
1268
+ }
1269
+ case "youtube": {
1270
+ if (srv === "ytmp3gg" || srv === "server1") {
1271
+ res = await scrapr.youtube.ytmp3gg(url);
1272
+ usedServer = "ytmp3.gg";
1273
+ } else if (srv === "ytmp3" || srv === "server2") {
1274
+ res = await scrapr.youtube.ytmp3(url);
1275
+ usedServer = "ytmp3";
1276
+ } else {
1277
+ res = await scrapr.youtube.ytmp3gg(url);
1278
+ usedServer = "ytmp3.gg";
1279
+ if (!res?.status) {
1280
+ res = await scrapr.youtube.ytmp3(url);
1281
+ usedServer = "ytmp3";
1282
+ }
1283
+ }
1284
+ break;
1285
+ }
1286
+ case "twitter": {
1287
+ if (srv === "tvd" || srv === "server1") {
1288
+ res = await scrapr.twitter.tvd(url);
1289
+ usedServer = "TwitterVideoDownloader";
1290
+ } else if (srv === "savetwt" || srv === "server2") {
1291
+ res = await scrapr.twitter.savetwt(url);
1292
+ usedServer = "SaveTWT";
1293
+ } else if (srv === "tweeload") {
1294
+ res = await scrapr.twitter.tweeload(url);
1295
+ usedServer = "TweeLoad";
1296
+ } else if (srv === "direct") {
1297
+ res = await scrapr.twitter.direct(url);
1298
+ usedServer = "Direct FXTwitter";
1299
+ } else {
1300
+ res = await scrapr.twitter.tvd(url);
1301
+ usedServer = "TwitterVideoDownloader";
1302
+ if (!res?.status) {
1303
+ res = await scrapr.twitter.savetwt(url);
1304
+ usedServer = "SaveTWT";
1305
+ }
1306
+ if (!res?.status) {
1307
+ res = await scrapr.twitter.tweeload(url);
1308
+ usedServer = "TweeLoad";
1309
+ }
1310
+ if (!res?.status) {
1311
+ res = await scrapr.twitter.direct(url);
1312
+ usedServer = "Direct FXTwitter";
1313
+ }
1314
+ }
1315
+ break;
1316
+ }
1317
+ case "spotify": {
1318
+ if (srv === "spotidown" || srv === "server1") {
1319
+ res = await scrapr.spotify.spotidown(url);
1320
+ usedServer = "SpotiDown";
1321
+ } else if (srv === "soundloaders" || srv === "server2") {
1322
+ res = await scrapr.spotify.soundloaders(url);
1323
+ usedServer = "SoundLoaders";
1324
+ } else if (srv === "spotmate") {
1325
+ res = await scrapr.spotify.spotmate(url);
1326
+ usedServer = "SpotMate";
1327
+ } else if (srv === "spotisaver") {
1328
+ res = await scrapr.spotify.spotisaver(url);
1329
+ usedServer = "SpotiSaver";
1330
+ } else {
1331
+ res = await scrapr.spotify.spotidown(url);
1332
+ usedServer = "SpotiDown";
1333
+ if (!res?.status) {
1334
+ res = await scrapr.spotify.soundloaders(url);
1335
+ usedServer = "SoundLoaders";
1336
+ }
1337
+ if (!res?.status) {
1338
+ res = await scrapr.spotify.spotmate(url);
1339
+ usedServer = "SpotMate";
1340
+ }
1341
+ if (!res?.status) {
1342
+ res = await scrapr.spotify.spotisaver(url);
1343
+ usedServer = "SpotiSaver";
1344
+ }
1345
+ }
1346
+ break;
1347
+ }
1348
+ case "soundcloud":
1349
+ res = await scrapr.soundcloud.klickaud(url);
1350
+ usedServer = "KlickAud";
1351
+ break;
1352
+ case "pinterest": {
1353
+ if (srv === "pindown" || srv === "server1") {
1354
+ res = await scrapr.pinterest.pindown(url);
1355
+ usedServer = "PinDown";
1356
+ } else if (srv === "direct" || srv === "server2") {
1357
+ res = await scrapr.pinterest.direct(url);
1358
+ usedServer = "Direct";
1359
+ } else {
1360
+ res = await scrapr.pinterest.pindown(url);
1361
+ usedServer = "PinDown";
1362
+ if (!res?.status) {
1363
+ res = await scrapr.pinterest.direct(url);
1364
+ usedServer = "Direct";
1365
+ }
1366
+ }
1367
+ break;
1368
+ }
1369
+ case "facebook": {
1370
+ if (srv === "snapsave" || srv === "server1") {
1371
+ res = await scrapr.facebook.snapsave(url);
1372
+ usedServer = "SnapSave";
1373
+ } else if (srv === "fdown" || srv === "server2") {
1374
+ res = await scrapr.facebook.fdown(url);
1375
+ usedServer = "FDown";
1376
+ } else {
1377
+ res = await scrapr.facebook.snapsave(url);
1378
+ usedServer = "SnapSave";
1379
+ if (!res?.status) {
1380
+ res = await scrapr.facebook.fdown(url);
1381
+ usedServer = "FDown";
1382
+ }
1383
+ }
1384
+ break;
1385
+ }
1386
+ case "threads":
1387
+ res = await scrapr.threads.threadster(url);
1388
+ usedServer = "Threadster";
1389
+ break;
1390
+ case "pixiv":
1391
+ res = await scrapr.pixiv.ajax(url);
1392
+ usedServer = "Pixiv";
1393
+ break;
1394
+ case "rednote":
1395
+ res = await scrapr.rednote.direct(url);
1396
+ usedServer = "RedNote";
1397
+ break;
1398
+ case "douyin":
1399
+ res = await scrapr.douyin.direct(url);
1400
+ usedServer = "Douyin";
1401
+ break;
1402
+ case "bilibili":
1403
+ res = await scrapr.bilibili.direct(url);
1404
+ usedServer = "Bilibili";
1405
+ break;
1406
+ case "reddit":
1407
+ res = await scrapr.reddit.rapidsave(url);
1408
+ usedServer = "RapidSave";
1409
+ break;
1410
+ case "terabox":
1411
+ res = await scrapr.terabox.sechno(url);
1412
+ usedServer = "Sechno";
1413
+ break;
1414
+ case "bandcamp": {
1415
+ res = await scrapr.bandcamp.direct(url);
1416
+ usedServer = "Direct";
1417
+ if (!res?.status) {
1418
+ res = await scrapr.bandcamp.bandcampdownloader(url);
1419
+ usedServer = "BandcampDownloader";
1420
+ }
1421
+ break;
1422
+ }
1423
+ case "applemusic":
1424
+ res = await scrapr.applemusic.aplmate(url);
1425
+ break;
1426
+ case "mediafire":
1427
+ res = await scrapr.resolver.mediafire(url);
1428
+ break;
1429
+ case "sfile":
1430
+ res = await scrapr.resolver.sfile(url);
1431
+ break;
1432
+ case "pixeldrain":
1433
+ res = await scrapr.resolver.pixeldrain(url);
1434
+ break;
1435
+ case "catbox":
1436
+ res = await scrapr.resolver.catbox(url);
1437
+ break;
1438
+ case "krakenfiles":
1439
+ res = await scrapr.resolver.krakenfiles(url);
1440
+ break;
1441
+ case "gdrive":
1442
+ res = await scrapr.resolver.gdrive(url);
1443
+ break;
1444
+ case "doodstream":
1445
+ res = await scrapr.resolver.doodstream(url);
1446
+ break;
1447
+ case "safelinku":
1448
+ res = await scrapr.resolver.safelinku(url);
1449
+ break;
1450
+ case "sub2unlock":
1451
+ res = await scrapr.resolver.sub2unlock(url);
1452
+ break;
1453
+ case "rekonise":
1454
+ res = await scrapr.resolver.rekonise(url);
1455
+ break;
1456
+ case "unshorten":
1457
+ res = await scrapr.resolver.unshorten(url);
1458
+ break;
1459
+ default:
1460
+ throw new Error(`Scrapr does not support platform: ${platform}`);
1461
+ }
1462
+
1463
+ if (!res || !res.status) {
1464
+ throw new Error(
1465
+ res?.message || `Failed to scrape media with Scrapr from ${platform}.`,
1466
+ );
1467
+ }
1468
+
1469
+ const result = res.result || {};
1470
+ if (result.title) {
1471
+ result.title = decodeHtmlEntities(result.title);
1472
+ }
1473
+ if (result.author && typeof result.author === "object") {
1474
+ result.author =
1475
+ result.author.name ||
1476
+ result.author.username ||
1477
+ result.author.nickname ||
1478
+ "Creator";
1479
+ }
1480
+
1481
+ let downloads = result.downloads || [];
1482
+ const primaryUrl = result.destinationUrl || result.url;
1483
+ if (!downloads.length && primaryUrl) {
1484
+ downloads = [
1485
+ {
1486
+ type: SHORTLINK_PLATFORMS.has(platform) ? "link" : (result.type || "file"),
1487
+ quality: SHORTLINK_PLATFORMS.has(platform) ? "Resolved Link" : "Direct Download",
1488
+ url: primaryUrl,
1489
+ },
1490
+ ];
1491
+ }
1492
+
1493
+ return {
1494
+ platform,
1495
+ engine: "scrapr",
1496
+ server: usedServer,
1497
+ ...result,
1498
+ downloads,
1499
+ };
1500
+ }
1501
+
1502
+ // 5c. Unified Scraper with Engine Routing & Automatic Fallback
1503
+ export async function scrapeUrl(
1504
+ url,
1505
+ serverPreference = "auto",
1506
+ enginePreference = "auto",
1507
+ ) {
1508
+ const platform = detectPlatform(url);
1509
+ if (!platform) {
1510
+ throw new Error("URL is not supported by Mori.");
1511
+ }
1512
+
1513
+ const engine = (enginePreference || "auto").toLowerCase();
1514
+ const moriInstalled = isMoriInstalled();
1515
+ const scraprInstalled = isScraprInstalled();
1516
+
1517
+ if (!moriInstalled && !scraprInstalled) {
1518
+ throw new Error(
1519
+ "No scraper engine installed. Run 'mori' or use /engine to install.",
1520
+ );
1521
+ }
1522
+
1523
+ // If platform is exclusive to Scrapr
1524
+ if (SCRAPR_ONLY_PLATFORMS.has(platform)) {
1525
+ if (!scraprInstalled) {
1526
+ throw new Error(
1527
+ `Platform '${platform}' requires Scrapr engine. Install with /engine.`,
1528
+ );
1529
+ }
1530
+ return scrapeWithScrapr(url, platform, serverPreference);
1531
+ }
1532
+
1533
+ // Engine 2 explicit
1534
+ if (engine === "scrapr") {
1535
+ if (!scraprInstalled) {
1536
+ throw new Error("Scrapr engine is not installed. Install with /engine.");
1537
+ }
1538
+ return scrapeWithScrapr(url, platform, serverPreference);
1539
+ }
1540
+
1541
+ // Engine 1 explicit
1542
+ if (engine === "mori") {
1543
+ if (!moriInstalled) {
1544
+ throw new Error("Mori engine is not installed. Install with /engine.");
1545
+ }
1546
+ return scrapeWithMori(url, platform, serverPreference);
1547
+ }
1548
+
1549
+ // Auto mode: single engine fallback
1550
+ if (!moriInstalled && scraprInstalled) {
1551
+ return scrapeWithScrapr(url, platform, serverPreference);
1552
+ }
1553
+ if (moriInstalled && !scraprInstalled) {
1554
+ return scrapeWithMori(url, platform, serverPreference);
1555
+ }
1556
+
1557
+ // Both installed: Engine 1 (Mori) first -> fallback to Engine 2 (Scrapr)
1558
+ try {
1559
+ return await scrapeWithMori(url, platform, serverPreference);
1560
+ } catch (moriErr) {
1561
+ try {
1562
+ const scraprRes = await scrapeWithScrapr(url, platform, serverPreference);
1563
+ scraprRes.fallbackFromMori = true;
1564
+ return scraprRes;
1565
+ } catch (_) {
1566
+ throw moriErr;
1567
+ }
1568
+ }
1569
+ }
1570
+
688
1571
  // 6. Asynchronous Direct URL Resolvers
689
1572
  export async function resolveUrl(url, onStatus) {
1573
+ const scraperFetch = getScraperFetch();
1574
+
690
1575
  if (url.startsWith("applemusic_resolve:")) {
691
1576
  if (onStatus) onStatus("Resolving Apple Music direct stream...");
692
1577
  const payloadStr = url.replace("applemusic_resolve:", "");
693
- const res = await scrapers.scraperFetch({
1578
+ const res = await scraperFetch({
694
1579
  method: "POST",
695
1580
  url: "https://aplmate.com/action/track",
696
1581
  headers: {
@@ -746,7 +1631,7 @@ export async function resolveUrl(url, onStatus) {
746
1631
  };
747
1632
  if (cookiesStr) reqHeaders["Cookie"] = cookiesStr;
748
1633
 
749
- const res = await scrapers.scraperFetch({
1634
+ const res = await scraperFetch({
750
1635
  url: "https://spotidown.app/action/track",
751
1636
  method: "POST",
752
1637
  headers: reqHeaders,
@@ -799,19 +1684,19 @@ export async function resolveUrl(url, onStatus) {
799
1684
  Accept: "*/*",
800
1685
  };
801
1686
 
802
- const initData = await scrapers.scraperFetch({
1687
+ const initData = await scraperFetch({
803
1688
  url: `https://a.ymcdn.org/api/v1/init?p=y&23=1llum1n471&_=${Math.random()}`,
804
1689
  headers: mobiHeaders,
805
1690
  });
806
1691
 
807
1692
  if (initData && !initData.error && initData.convertURL) {
808
- let convData = await scrapers.scraperFetch({
1693
+ let convData = await scraperFetch({
809
1694
  url: `${initData.convertURL}&v=${ytId}&f=${format}&_=${Math.random()}`,
810
1695
  headers: mobiHeaders,
811
1696
  });
812
1697
 
813
1698
  while (convData && convData.redirect > 0 && convData.redirectURL) {
814
- convData = await scrapers.scraperFetch({
1699
+ convData = await scraperFetch({
815
1700
  url: `${convData.redirectURL}&v=${ytId}&f=${format}&_=${Math.random()}`,
816
1701
  headers: mobiHeaders,
817
1702
  });
@@ -825,7 +1710,7 @@ export async function resolveUrl(url, onStatus) {
825
1710
 
826
1711
  while (progress < 3 && attempts < 25) {
827
1712
  await new Promise((r) => setTimeout(r, 1200));
828
- const pData = await scrapers.scraperFetch({
1713
+ const pData = await scraperFetch({
829
1714
  url: `${progUrl}&_=${Math.random()}`,
830
1715
  headers: mobiHeaders,
831
1716
  });