@coflyn/mori 1.0.1 → 1.2.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/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import fs from "fs";
4
+ import os from "os";
4
5
  import path from "path";
5
6
  import { parseArgs } from "node:util";
6
7
  import * as p from "@clack/prompts";
@@ -8,12 +9,24 @@ import pc from "picocolors";
8
9
  import {
9
10
  detectPlatform,
10
11
  PLATFORM_SERVERS,
12
+ getPlatformServers,
11
13
  scrapeUrl,
12
14
  resolveUrl,
13
15
  sanitizeFilename,
14
16
  downloadMediaFile,
15
17
  checkForOtaUpdate,
16
18
  getActiveScraperVersion,
19
+ getActiveScraprVersion,
20
+ checkForScraprOtaUpdate,
21
+ isMoriInstalled,
22
+ isScraprInstalled,
23
+ downloadMoriEngine,
24
+ downloadScraprEngine,
25
+ uninstallMoriEngine,
26
+ uninstallScraprEngine,
27
+ RESOLVER_LINK_PLATFORMS,
28
+ SHORTLINK_PLATFORMS,
29
+ writeClipboard,
17
30
  getSavedConfig,
18
31
  saveConfig,
19
32
  openDirectory,
@@ -22,6 +35,7 @@ import {
22
35
  addToHistory,
23
36
  clearHistory,
24
37
  deleteHistoryItem,
38
+ deleteHistoryItems,
25
39
  readClipboard,
26
40
  getNonCollidingPath,
27
41
  resetMori,
@@ -32,9 +46,14 @@ import {
32
46
  pingNetwork,
33
47
  compileImagesToPdf,
34
48
  CHROME_UA,
49
+ loadScraprEngine,
50
+ fetchMoriEngineHistory,
51
+ downloadMoriEngineByCommit,
52
+ fetchScraprEngineVersions,
53
+ downloadScraprEngineVersion,
35
54
  } from "./engine.js";
36
55
 
37
- const APP_VERSION = "1.0.1";
56
+ const APP_VERSION = "1.2.0";
38
57
 
39
58
  function isNewerVersion(latest, current) {
40
59
  if (!latest || !current) return false;
@@ -91,21 +110,203 @@ function renderProgressBar(percent, width = 22) {
91
110
  return pc.white("█".repeat(filled)) + pc.dim("░".repeat(empty));
92
111
  }
93
112
 
94
- function printBanner(coreVer) {
113
+ function formatPath(filePath) {
114
+ if (!filePath) return "";
115
+ const home = os.homedir();
116
+ if (filePath.startsWith(home)) {
117
+ return `~${filePath.slice(home.length)}`;
118
+ }
119
+ return filePath;
120
+ }
121
+
122
+ function truncateText(str, max = 72) {
123
+ if (!str || typeof str !== "string") return "";
124
+ const single = str.replace(/\r?\n|\r/g, " ").trim();
125
+ if (single.length <= max) return single;
126
+ return single.substring(0, max - 3) + "...";
127
+ }
128
+
129
+ function formatStreamItem(d, i, allDownloads = []) {
130
+ const typeStr = (d.type || "").toLowerCase();
131
+ const qualityStr = (d.quality || "").trim();
132
+
133
+ const isAudio =
134
+ typeStr.includes("audio") ||
135
+ typeStr.includes("music") ||
136
+ typeStr.includes("mp3");
137
+
138
+ const isPhoto = typeStr.includes("photo") || typeStr.includes("image");
139
+
140
+ if (isAudio) {
141
+ const qual =
142
+ qualityStr &&
143
+ !qualityStr.toLowerCase().includes("audio") &&
144
+ !qualityStr.toLowerCase().includes("music") &&
145
+ !qualityStr.toLowerCase().includes("mp3")
146
+ ? ` (${qualityStr})`
147
+ : "";
148
+ return {
149
+ label: `MP3 Audio${qual}`,
150
+ hint: "audio",
151
+ };
152
+ }
153
+
154
+ if (isPhoto) {
155
+ return {
156
+ label: `Photo #${i + 1}`,
157
+ hint: qualityStr || "image",
158
+ };
159
+ }
160
+
161
+ // Video stream
162
+ let resLabel = "";
163
+ if (qualityStr && qualityStr.toLowerCase() !== "video") {
164
+ resLabel = qualityStr;
165
+ } else if (/^\d+p$/i.test(d.type)) {
166
+ resLabel = d.type;
167
+ } else if (allDownloads.length > 0) {
168
+ const videoStreams = allDownloads.filter(
169
+ (item) =>
170
+ !item.type?.toLowerCase().includes("audio") &&
171
+ !item.type?.toLowerCase().includes("music") &&
172
+ !item.type?.toLowerCase().includes("photo"),
173
+ );
174
+ const vIdx = videoStreams.indexOf(d);
175
+ if (vIdx === 0) resLabel = "HD / Best Quality";
176
+ else if (vIdx === 1) resLabel = "Standard Quality";
177
+ else resLabel = `Option ${vIdx + 1}`;
178
+ } else {
179
+ resLabel = "Video";
180
+ }
181
+
182
+ const mirrorTag = d.isMirror ? " [Mirror]" : "";
183
+ return {
184
+ label: `${resLabel} Video${mirrorTag}`,
185
+ hint: mirrorTag ? "mirror" : "video",
186
+ };
187
+ }
188
+
189
+ const MORI_BANNER = [
190
+ "███╗ ███╗ ██████╗ ██████╗ ██╗",
191
+ "████╗ ████║██╔═══██╗██╔══██╗██║",
192
+ "██╔████╔██║██║ ██║██████╔╝██║",
193
+ "██║╚██╔╝██║██║ ██║██╔══██╗██║",
194
+ "██║ ╚═╝ ██║╚██████╔╝██║ ██║██║",
195
+ "╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝",
196
+ ];
197
+
198
+ function renderBanner() {
199
+ return MORI_BANNER.map(
200
+ (l) =>
201
+ " " +
202
+ l
203
+ .replace(/(█+)/g, pc.bold(pc.cyan("$1")))
204
+ .replace(/([╗║╚╝═]+)/g, pc.dim(pc.cyan("$1"))),
205
+ ).join("\n");
206
+ }
207
+
208
+ function printBanner(coreVer, scraprVer) {
209
+ console.log("\n" + renderBanner() + "\n");
210
+ const engines = [];
211
+ if (coreVer) engines.push(`mori v${coreVer}`);
212
+ if (scraprVer) engines.push(`scrapr v${scraprVer}`);
213
+ const engineStr =
214
+ engines.length > 0 ? engines.join(" • ") : "no engine installed";
95
215
  const brand =
96
216
  pc.bold(pc.inverse(" MORI ")) +
97
217
  " " +
98
218
  pc.bold(`v${APP_VERSION}`) +
99
219
  " " +
100
- pc.dim(`(core v${coreVer})`);
220
+ pc.dim(`(${engineStr})`);
101
221
  const sub = pc.dim(
102
- "Save anything, from anywhere. No watermarks. No tracking.",
222
+ "Save anything, from anywhere. Dual-Engine powered.",
103
223
  );
104
224
  p.intro(`${brand}\n ${sub}`);
105
225
  }
106
226
 
227
+ async function ensureEnginesInstalled() {
228
+ const moriInstalled = isMoriInstalled();
229
+ const scraprInstalled = isScraprInstalled();
230
+
231
+ if (moriInstalled || scraprInstalled) {
232
+ return true;
233
+ }
234
+
235
+ p.note(
236
+ `Welcome to Mori CLI!\n\n` +
237
+ `Mori is a lightweight CLI wrapper without pre-bundled scraper engines.\n` +
238
+ `Choose which engine(s) you would like to download to get started:`,
239
+ pc.bold("First-Time Engine Setup"),
240
+ );
241
+
242
+ const choice = await p.select({
243
+ message: "Which engine would you like to install?",
244
+ options: [
245
+ {
246
+ value: "both",
247
+ label: "Both (Mori Core + Scrapr) [Recommended]",
248
+ hint: "All 27 platforms: social media, audio, file hosts & unshorteners",
249
+ },
250
+ {
251
+ value: "scrapr",
252
+ label: "Scrapr Engine only (~2.7 MB)",
253
+ hint: "Stand-alone engine with file host resolvers (MediaFire, Sfile, GDrive, etc.)",
254
+ },
255
+ {
256
+ value: "mori",
257
+ label: "Mori Engine only (~80 KB)",
258
+ hint: "Ultra lightweight core scrapers (TikTok, IG, YouTube, Spotify, X, etc.)",
259
+ },
260
+ {
261
+ value: "skip",
262
+ label: "Skip for now",
263
+ hint: "Install manually later via /engine",
264
+ },
265
+ ],
266
+ initialValue: "both",
267
+ });
268
+
269
+ if (p.isCancel(choice) || choice === "skip") {
270
+ p.log.warn("Setup skipped. You will need to install an engine before scraping.");
271
+ return false;
272
+ }
273
+
274
+ if (choice === "both" || choice === "mori") {
275
+ const s = p.spinner();
276
+ s.start(pc.dim("Installing Mori Core Engine (~80 KB)..."));
277
+ try {
278
+ const res = await downloadMoriEngine();
279
+ s.stop(pc.bold(`✔ Mori Core Engine installed (v${res.version}).`));
280
+ } catch (err) {
281
+ s.stop(pc.bold(`✕ Failed to install Mori Engine: ${err.message}`));
282
+ }
283
+ }
284
+
285
+ if (choice === "both" || choice === "scrapr") {
286
+ const s = p.spinner();
287
+ s.start(pc.dim("Installing Scrapr Engine (~2.7 MB)..."));
288
+ try {
289
+ const res = await downloadScraprEngine();
290
+ s.stop(pc.bold(`✔ Scrapr Engine installed (v${res.version}).`));
291
+ } catch (err) {
292
+ s.stop(pc.bold(`✕ Failed to install Scrapr Engine: ${err.message}`));
293
+ }
294
+ }
295
+
296
+ const defEngine = choice === "both" ? "auto" : choice;
297
+ saveConfig({ defaultEngine: defEngine });
298
+
299
+ p.log.message(
300
+ `${pc.bold("● Default engine set:")} ${pc.white(defEngine)} ${pc.dim("(change anytime with /engine)")}`,
301
+ );
302
+
303
+ return isMoriInstalled() || isScraprInstalled();
304
+ }
305
+
107
306
  function printHelp() {
108
307
  console.log(`
308
+ ${renderBanner()}
309
+
109
310
  ${pc.bold(pc.inverse(" MORI CLI "))} ${pc.bold(`v${APP_VERSION}`)}
110
311
 
111
312
  ${pc.bold("USAGE:")}
@@ -113,20 +314,24 @@ ${pc.bold("USAGE:")}
113
314
  ${pc.white("npx @coflyn/mori")} ${pc.dim("[URL]")} ${pc.dim("[OPTIONS]")}
114
315
 
115
316
  ${pc.bold("OPTIONS:")}
116
- ${pc.white("-o, --output <dir>")} Destination folder (default: ${pc.dim("~/Downloads/Mori")})
117
- ${pc.white("-s, --server <1|2>")} Choose scraper server (TikTok, IG, YouTube, X, Spotify)
118
- ${pc.white("-a, --audio")} Download audio-only stream (MP3/M4A)
119
- ${pc.white("-p, --pdf")} Compile photo album directly into a single PDF
120
- ${pc.white("-c, --clip")} Auto-fetch link from system clipboard
121
- ${pc.white("-y, --yes")} Download best/first available stream automatically
122
- ${pc.white("-i, --info")} Inspect and display media details only
123
- ${pc.white("-u, --update")} Check and pull latest OTA scraper patch
124
- ${pc.white("-h, --help")} Show this documentation
125
- ${pc.white("-v, --version")} Print version number
126
-
127
- ${pc.bold("SUPPORTED PLATFORMS (16):")}
128
- ${pc.dim("TikTok • Instagram • YouTube • Twitter/X • Spotify • Pinterest • Facebook")}
129
- ${pc.dim("Bilibili • Reddit • RedNote • Threads • Pixiv • Bandcamp • Apple Music • Douyin • TeraBox")}
317
+ ${pc.white("-o, --output <dir>")} Destination folder (default: ${pc.dim("~/Downloads/Mori")})
318
+ ${pc.white("-e, --engine <auto|mori|scrapr>")} Scraper engine choice (default: ${pc.dim("auto")})
319
+ ${pc.white("-s, --server <1|2>")} Choose scraper server (TikTok, IG, YouTube, X, Spotify)
320
+ ${pc.white("-a, --audio")} Download audio-only stream (MP3/M4A)
321
+ ${pc.white("-p, --pdf")} Compile photo album directly into a single PDF
322
+ ${pc.white("-c, --clip")} Auto-fetch link from system clipboard
323
+ ${pc.white("-y, --yes")} Download best/first available stream automatically
324
+ ${pc.white("-i, --info")} Inspect and display media details only
325
+ ${pc.white("-u, --update")} Check and pull latest OTA scraper patches
326
+ ${pc.white("-h, --help")} Show this documentation
327
+ ${pc.white("-v, --version")} Print version number
328
+
329
+ ${pc.bold("SUPPORTED PLATFORMS (27 • DUAL-ENGINE):")}
330
+ ${pc.dim("Social & Video:")} TikTok • Instagram • YouTube • Twitter/X • Facebook • Douyin
331
+ Bilibili • Threads • RedNote • Reddit • Pixiv • Doodstream
332
+ ${pc.dim("Music & Audio :")} Spotify • SoundCloud • Apple Music • Bandcamp
333
+ ${pc.dim("Cloud & Files :")} TeraBox • MediaFire • Sfile • Catbox • Pixeldrain • Krakenfiles • GDrive
334
+ ${pc.dim("Resolvers :")} SafeLinkU • Sub2Unlock • Rekonise • Link Unshortener
130
335
 
131
336
  ${pc.bold("EXAMPLES:")}
132
337
  ${pc.dim("# Interactive")}
@@ -135,13 +340,13 @@ ${pc.bold("EXAMPLES:")}
135
340
  # Download link directly from clipboard
136
341
  mori --clip
137
342
 
138
- # Download audio-only (MP3)
139
- mori https://youtu.be/dQw4w9WgXcQ -a
343
+ # Use Scrapr engine explicitly
344
+ mori https://www.mediafire.com/file/... -e scrapr
140
345
 
141
- # Direct link with Server 2
142
- mori https://www.tiktok.com/@user/video/123456789 -s 2
346
+ # Download audio-only (MP3)
347
+ mori https://soundcloud.com/... -a
143
348
 
144
- # Check OTA scraper updates
349
+ # Check OTA updates for both engines
145
350
  mori --update
146
351
  `);
147
352
  }
@@ -163,16 +368,31 @@ async function runConcurrentPool(items, concurrency, fn) {
163
368
  }
164
369
 
165
370
  async function processDownloadItem({ item, meta, outputDir, index, total }) {
371
+ let detectedExt = "";
372
+ const rawFilename = item.filename || meta.filename;
373
+ if (rawFilename && path.extname(rawFilename)) {
374
+ detectedExt = path.extname(rawFilename).replace(/^\./, "");
375
+ } else if (item.url) {
376
+ try {
377
+ const uPath = new URL(item.url).pathname;
378
+ const uExt = path.extname(uPath).replace(/^\./, "");
379
+ if (uExt && uExt.length <= 5 && !uExt.includes("/")) detectedExt = uExt;
380
+ } catch (_) {}
381
+ }
382
+
166
383
  const ext =
167
- item.type?.toLowerCase().includes("mp3") ||
384
+ detectedExt ||
385
+ (item.type?.toLowerCase().includes("mp3") ||
168
386
  item.type?.toLowerCase().includes("audio")
169
387
  ? "mp3"
170
388
  : item.type?.toLowerCase().includes("photo") ||
171
389
  item.type?.toLowerCase().includes("image")
172
390
  ? "jpg"
173
- : "mp4";
391
+ : "mp4");
174
392
 
175
- let baseTitle = meta.title || "Media";
393
+ let baseTitle = rawFilename
394
+ ? path.basename(rawFilename, path.extname(rawFilename))
395
+ : (meta.title || "Media");
176
396
  if (total > 1) {
177
397
  baseTitle = `${baseTitle}_${index + 1}`;
178
398
  }
@@ -196,21 +416,32 @@ async function processDownloadItem({ item, meta, outputDir, index, total }) {
196
416
 
197
417
  let finalBytes = 0;
198
418
  try {
199
- await downloadMediaFile(directUrl, destPath, (prog) => {
200
- finalBytes = prog.downloadedBytes;
201
- const bar = renderProgressBar(prog.percent, 20);
202
- const pct = `${prog.percent.toFixed(0)}%`.padStart(4);
203
- const dl = formatBytes(prog.downloadedBytes);
204
- const tot = prog.totalBytes > 0 ? formatBytes(prog.totalBytes) : "?";
205
- const spd = `${formatBytes(prog.speedBps)}/s`;
206
-
207
- const line = ` ${bar} ${pc.bold(pct)} ${pc.dim(`(${dl}/${tot} • ${spd})`)}`;
208
- process.stdout.write(`\r${line}\x1b[K`);
209
- });
419
+ await downloadMediaFile(
420
+ directUrl,
421
+ destPath,
422
+ (prog) => {
423
+ finalBytes = prog.downloadedBytes;
424
+ const bar = renderProgressBar(prog.percent, 20);
425
+ const pct = `${prog.percent.toFixed(0)}%`.padStart(4);
426
+ const dl = formatBytes(prog.downloadedBytes);
427
+ const tot = prog.totalBytes > 0 ? formatBytes(prog.totalBytes) : "?";
428
+ const spd = `${formatBytes(prog.speedBps)}/s`;
429
+
430
+ const line = ` ${bar} ${pc.bold(pct)} ${pc.dim(`(${dl}/${tot} • ${spd})`)}`;
431
+ process.stdout.write(`\r${line}\x1b[K`);
432
+ },
433
+ {
434
+ ...(meta.url ? { Referer: meta.url } : {}),
435
+ ...(directUrl.includes("googlevideo.com")
436
+ ? { Referer: "https://desustream.net/" }
437
+ : {}),
438
+ ...(item.headers || {}),
439
+ },
440
+ );
210
441
 
211
442
  process.stdout.write("\r\x1b[2K");
212
443
  p.log.message(
213
- `${pc.bold("● Saved:")} ${pc.bold(path.basename(destPath))} ${pc.dim(`(${path.relative(process.cwd(), destPath)})`)}`,
444
+ `${pc.bold("● Saved:")} ${pc.bold(path.basename(destPath))} ${pc.dim(`(${formatPath(destPath)})`)}`,
214
445
  );
215
446
  addToHistory({
216
447
  url: meta.url || "",
@@ -241,9 +472,11 @@ async function handleScrapeAndDownload(targetUrl, options) {
241
472
  }
242
473
 
243
474
  const savedConfig = getSavedConfig();
244
- // Dual Server Selection prompt for supported platforms
475
+ const engineChoice = options.engine || savedConfig.defaultEngine || "auto";
476
+
477
+ // Server Selection prompt for supported platforms based on active engine
245
478
  let serverChoice = options.server || savedConfig.defaultServer;
246
- const serverList = PLATFORM_SERVERS[platform];
479
+ const serverList = getPlatformServers(platform, engineChoice);
247
480
  const isInteractive = Boolean(process.stdin.isTTY);
248
481
  if (
249
482
  (!serverChoice || serverChoice === "auto") &&
@@ -273,7 +506,7 @@ async function handleScrapeAndDownload(targetUrl, options) {
273
506
 
274
507
  let media;
275
508
  try {
276
- media = await scrapeUrl(targetUrl, serverChoice || "auto");
509
+ media = await scrapeUrl(targetUrl, serverChoice || "auto", engineChoice);
277
510
  media.url = targetUrl;
278
511
  s.stop(pc.dim("Link analyzed."));
279
512
  } catch (err) {
@@ -281,20 +514,117 @@ async function handleScrapeAndDownload(targetUrl, options) {
281
514
  return false;
282
515
  }
283
516
 
517
+ const serverTag = media.server ? ` • ${media.server}` : "";
518
+ const engineBadge =
519
+ media.engine === "scrapr"
520
+ ? media.fallbackFromMori
521
+ ? pc.yellow(`[Scrapr • Fallback${serverTag}]`)
522
+ : pc.cyan(`[Scrapr Engine${serverTag}]`)
523
+ : pc.green(`[Mori Engine${serverTag}]`);
524
+
525
+ // Direct Link / Resolver Platforms (catbox, pixeldrain, sfl.gl, mediafire, sfile, etc.)
526
+ if (RESOLVER_LINK_PLATFORMS.has(media.platform)) {
527
+ // If it's a multi-file collection (e.g. catbox collection, pixeldrain list)
528
+ if (
529
+ media.type === "album" &&
530
+ Array.isArray(media.downloads) &&
531
+ media.downloads.length > 1
532
+ ) {
533
+ const urls = media.downloads.map((d) => d.url).filter(Boolean);
534
+ const urlText = urls.join("\n");
535
+ if (urlText) {
536
+ await writeClipboard(urlText);
537
+ }
538
+
539
+ const cardLines = [
540
+ `${pc.dim("Title :")} ${truncateText(media.title, 65) || "Collection Album"}`,
541
+ `${pc.dim("Engine :")} ${engineBadge}`,
542
+ `${pc.dim("Files :")} ${urls.length} item(s)`,
543
+ ];
544
+ p.note(cardLines.join("\n"), pc.bold(media.platform.toUpperCase()));
545
+
546
+ if (urls.length) {
547
+ p.log.success(
548
+ `${pc.bold(`✔ ${urls.length} URLs copied to clipboard:`)}`,
549
+ );
550
+ urls.slice(0, 5).forEach((u, i) => {
551
+ p.log.message(` ${pc.dim(`[${i + 1}]`)} ${pc.cyan(u)}`);
552
+ });
553
+ if (urls.length > 5) {
554
+ p.log.message(` ${pc.dim(`... and ${urls.length - 5} more`)}`);
555
+ }
556
+ }
557
+
558
+ addToHistory({
559
+ url: targetUrl,
560
+ title: media.title || targetUrl,
561
+ platform: media.platform,
562
+ filename: "",
563
+ path: urls[0] || "",
564
+ bytes: 0,
565
+ });
566
+
567
+ return true;
568
+ }
569
+
570
+ const directUrl =
571
+ media.destinationUrl ||
572
+ media.url ||
573
+ media.downloads?.[0]?.url ||
574
+ "";
575
+
576
+ if (directUrl) {
577
+ await writeClipboard(directUrl);
578
+ }
579
+
580
+ const cardLines = [
581
+ `${pc.dim("Title :")} ${truncateText(media.title || media.filename, 65) || "Direct / Resolved Link"}`,
582
+ `${pc.dim("Engine :")} ${engineBadge}`,
583
+ `${pc.dim("URL :")} ${truncateText(directUrl, 65)}`,
584
+ ];
585
+ if (media.size && media.size !== "Unknown") {
586
+ cardLines.push(`${pc.dim("Size :")} ${pc.white(media.size)}`);
587
+ }
588
+ p.note(cardLines.join("\n"), pc.bold(media.platform.toUpperCase()));
589
+
590
+ if (directUrl) {
591
+ p.log.success(
592
+ `${pc.bold("✔ URL copied to clipboard:")} ${pc.underline(pc.cyan(directUrl))}`,
593
+ );
594
+ }
595
+
596
+ addToHistory({
597
+ url: targetUrl,
598
+ title: media.title || media.filename || directUrl,
599
+ platform: media.platform,
600
+ filename: media.filename || "",
601
+ path: directUrl,
602
+ bytes: 0,
603
+ });
604
+
605
+ return true;
606
+ }
607
+
284
608
  // Metadata card with Platform name as title (e.g. TIKTOK, INSTAGRAM)
285
609
  const infoLines = [
286
- `${pc.dim("Title :")} ${media.title || "Untitled"}`,
287
- `${pc.dim("Creator :")} ${media.author || "Creator"}`,
288
- `${pc.dim("Streams :")} ${media.downloads?.length || 0} option(s)`,
610
+ `${pc.dim("Title :")} ${truncateText(media.title, 68) || "Untitled"}`,
611
+ `${pc.dim("Creator :")} ${truncateText(media.author, 40) || "Creator"}`,
612
+ `${pc.dim("Engine :")} ${engineBadge}`,
289
613
  ];
614
+ if (media.viaResolver) {
615
+ infoLines.push(
616
+ `${pc.dim("Via :")} ${pc.magenta(media.viaResolver.toUpperCase())} ${pc.dim(`(${media.originalShortUrl || ""})`)}`,
617
+ );
618
+ }
619
+ infoLines.push(`${pc.dim("Streams :")} ${media.downloads?.length || 0} option(s)`);
290
620
  p.note(infoLines.join("\n"), pc.bold(media.platform.toUpperCase()));
291
621
 
292
622
  if (options.info) {
293
623
  if (media.downloads?.length) {
294
- const streamLines = media.downloads.map(
295
- (d, idx) =>
296
- ` ${pc.bold(`[${idx + 1}]`)} ${pc.white(d.type || "Stream")} ${d.quality ? pc.dim(`(${d.quality})`) : ""} ${d.isMirror ? pc.dim("[Mirror]") : ""}`,
297
- );
624
+ const streamLines = media.downloads.map((d, idx) => {
625
+ const item = formatStreamItem(d, idx, media.downloads);
626
+ return ` ${pc.bold(`[${idx + 1}]`)} ${pc.white(item.label)}`;
627
+ });
298
628
  p.note(streamLines.join("\n"), pc.dim("Available Streams"));
299
629
  }
300
630
  return true;
@@ -516,6 +846,7 @@ async function handleScrapeAndDownload(targetUrl, options) {
516
846
  headers: {
517
847
  "User-Agent": CHROME_UA,
518
848
  Accept: "*/*",
849
+ ...(media.url ? { Referer: media.url } : {}),
519
850
  ...(item.headers || {}),
520
851
  },
521
852
  });
@@ -657,37 +988,511 @@ async function handleScrapeAndDownload(targetUrl, options) {
657
988
  });
658
989
  }
659
990
 
660
- return true;
661
- } else {
662
- let selectedItem = downloads[0];
991
+ return true;
992
+ } else {
993
+ let selectedItem = downloads[0];
994
+
995
+ if (downloads.length > 1) {
996
+ const formatChoice = await p.select({
997
+ message: "Select stream:",
998
+ options: downloads.map((d, i) => {
999
+ const item = formatStreamItem(d, i, downloads);
1000
+ return {
1001
+ value: i,
1002
+ label: pc.bold(item.label),
1003
+ hint: item.hint ? pc.dim(item.hint) : undefined,
1004
+ };
1005
+ }),
1006
+ });
1007
+
1008
+ if (p.isCancel(formatChoice)) {
1009
+ p.cancel("Cancelled.");
1010
+ return false;
1011
+ }
1012
+ selectedItem = downloads[formatChoice];
1013
+ }
1014
+
1015
+ if (selectedItem?.type === "link") {
1016
+ const linkUrl = selectedItem.url;
1017
+ await writeClipboard(linkUrl);
1018
+ p.log.success(
1019
+ `${pc.bold("✔ Mirror link copied to clipboard:")} ${pc.underline(pc.cyan(linkUrl))}`,
1020
+ );
1021
+ addToHistory({
1022
+ url: targetUrl,
1023
+ title: `${media.title || "Media"} (${selectedItem.quality || "Mirror"})`,
1024
+ platform: media.platform,
1025
+ filename: "",
1026
+ path: linkUrl,
1027
+ bytes: 0,
1028
+ });
1029
+ return true;
1030
+ }
1031
+
1032
+ await processDownloadItem({
1033
+ item: selectedItem,
1034
+ meta: media,
1035
+ outputDir,
1036
+ index: 0,
1037
+ total: 1,
1038
+ });
1039
+ }
1040
+
1041
+ return true;
1042
+ }
1043
+
1044
+ async function handleSearchAndDownload(query, forcedType = null, options = {}) {
1045
+ const scrapr = loadScraprEngine();
1046
+ let provider = null;
1047
+
1048
+ if (forcedType === "anime") {
1049
+ const chosen = await p.select({
1050
+ message: `Select Anime Provider for "${query}":`,
1051
+ options: [
1052
+ { value: "otakudesu", label: "Otakudesu (Indonesian Sub)" },
1053
+ { value: "gogoanime", label: "Gogoanime (English Sub)" },
1054
+ ],
1055
+ });
1056
+ if (p.isCancel(chosen)) return false;
1057
+ provider = chosen;
1058
+ } else if (forcedType === "comic") {
1059
+ const chosen = await p.select({
1060
+ message: `Select Comic Provider for "${query}":`,
1061
+ options: [
1062
+ { value: "komikindo", label: "Komikindo (Indonesian)" },
1063
+ { value: "komiku", label: "Komiku (Indonesian)" },
1064
+ { value: "asurascans", label: "Asura Scans (English / Manhwa)" },
1065
+ ],
1066
+ });
1067
+ if (p.isCancel(chosen)) return false;
1068
+ provider = chosen;
1069
+ } else {
1070
+ const chosen = await p.select({
1071
+ message: `Search query "${query}":`,
1072
+ options: [
1073
+ { value: "otakudesu", label: "Anime • Otakudesu (Sub Indo)" },
1074
+ { value: "gogoanime", label: "Anime • Gogoanime (Sub Eng)" },
1075
+ { value: "komikindo", label: "Comic • Komikindo (Sub Indo)" },
1076
+ { value: "komiku", label: "Comic • Komiku (Sub Indo)" },
1077
+ { value: "asurascans", label: "Comic • Asura Scans (English)" },
1078
+ ],
1079
+ });
1080
+ if (p.isCancel(chosen)) return false;
1081
+ provider = chosen;
1082
+ }
1083
+
1084
+ const s = p.spinner();
1085
+
1086
+ if (provider === "otakudesu") {
1087
+ s.start(pc.dim(`Searching Otakudesu for "${query}"...`));
1088
+ let searchRes;
1089
+ try {
1090
+ searchRes = await scrapr.anime.otakudesu.search(query);
1091
+ } catch (err) {
1092
+ s.stop(pc.bold(`✕ Search failed: ${err.message}`));
1093
+ return false;
1094
+ }
1095
+ s.stop(pc.dim("Search complete."));
1096
+
1097
+ const items = searchRes?.result || [];
1098
+ if (items.length === 0) {
1099
+ p.log.warn(`No anime found for "${query}" on Otakudesu.`);
1100
+ return false;
1101
+ }
1102
+
1103
+ const animeChoices = items.map((it) => ({
1104
+ value: it.url,
1105
+ label: `${it.title} ${it.meta ? pc.dim(`(${it.meta})`) : ""}`,
1106
+ }));
1107
+ animeChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1108
+
1109
+ const chosenAnimeUrl = await p.select({
1110
+ message: `Select Anime (${items.length} found):`,
1111
+ options: animeChoices,
1112
+ });
1113
+ if (p.isCancel(chosenAnimeUrl) || chosenAnimeUrl === "cancel") {
1114
+ p.cancel("Cancelled.");
1115
+ return false;
1116
+ }
1117
+
1118
+ s.start(pc.dim("Fetching episode list..."));
1119
+ let epRes;
1120
+ try {
1121
+ epRes = await scrapr.anime.otakudesu.getEpisodes(chosenAnimeUrl);
1122
+ } catch (err) {
1123
+ s.stop(pc.bold(`✕ Failed to fetch episodes: ${err.message}`));
1124
+ return false;
1125
+ }
1126
+ s.stop(pc.dim("Episodes fetched."));
1127
+
1128
+ const episodes = epRes?.result || [];
1129
+ if (episodes.length === 0) {
1130
+ p.log.warn("No episodes found for this anime.");
1131
+ return false;
1132
+ }
1133
+
1134
+ const epChoices = episodes.map((ep) => ({
1135
+ value: ep.url,
1136
+ label: ep.title,
1137
+ }));
1138
+ epChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1139
+
1140
+ const chosenEpUrl = await p.select({
1141
+ message: `Select Episode (${episodes.length} episodes):`,
1142
+ options: epChoices,
1143
+ });
1144
+ if (p.isCancel(chosenEpUrl) || chosenEpUrl === "cancel") {
1145
+ p.cancel("Cancelled.");
1146
+ return false;
1147
+ }
1148
+
1149
+ return await handleScrapeAndDownload(chosenEpUrl, options);
1150
+ }
1151
+
1152
+ if (provider === "gogoanime") {
1153
+ s.start(pc.dim(`Searching Gogoanime for "${query}"...`));
1154
+ let searchRes;
1155
+ try {
1156
+ searchRes = await scrapr.anime.gogoanime.search(query);
1157
+ } catch (err) {
1158
+ s.stop(pc.bold(`✕ Search failed: ${err.message}`));
1159
+ return false;
1160
+ }
1161
+ s.stop(pc.dim("Search complete."));
1162
+
1163
+ const items = searchRes?.result || [];
1164
+ if (items.length === 0) {
1165
+ p.log.warn(`No anime found for "${query}" on Gogoanime.`);
1166
+ return false;
1167
+ }
1168
+
1169
+ const animeChoices = items.map((it) => ({
1170
+ value: it.url,
1171
+ label: it.title,
1172
+ }));
1173
+ animeChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1174
+
1175
+ const chosenAnimeUrl = await p.select({
1176
+ message: `Select Anime (${items.length} found):`,
1177
+ options: animeChoices,
1178
+ });
1179
+ if (p.isCancel(chosenAnimeUrl) || chosenAnimeUrl === "cancel") {
1180
+ p.cancel("Cancelled.");
1181
+ return false;
1182
+ }
1183
+
1184
+ s.start(pc.dim("Fetching episode list..."));
1185
+ let epRes;
1186
+ try {
1187
+ epRes = await scrapr.anime.gogoanime.getEpisodes(chosenAnimeUrl);
1188
+ } catch (err) {
1189
+ s.stop(pc.bold(`✕ Failed to fetch episodes: ${err.message}`));
1190
+ return false;
1191
+ }
1192
+ s.stop(pc.dim("Episodes fetched."));
1193
+
1194
+ const episodes = epRes?.result || [];
1195
+ if (episodes.length === 0) {
1196
+ p.log.warn("No episodes found for this anime.");
1197
+ return false;
1198
+ }
1199
+
1200
+ const epChoices = episodes.slice(0, 100).map((ep) => ({
1201
+ value: ep.url,
1202
+ label: ep.title,
1203
+ }));
1204
+ epChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1205
+
1206
+ const chosenEpUrl = await p.select({
1207
+ message: `Select Episode (${episodes.length} episodes):`,
1208
+ options: epChoices,
1209
+ });
1210
+ if (p.isCancel(chosenEpUrl) || chosenEpUrl === "cancel") {
1211
+ p.cancel("Cancelled.");
1212
+ return false;
1213
+ }
1214
+
1215
+ return await handleScrapeAndDownload(chosenEpUrl, options);
1216
+ }
1217
+
1218
+ if (provider === "komikindo") {
1219
+ s.start(pc.dim(`Searching Komikindo for "${query}"...`));
1220
+ let searchRes;
1221
+ try {
1222
+ searchRes = await scrapr.comic.komikindo.search(query);
1223
+ } catch (err) {
1224
+ s.stop(pc.bold(`✕ Search failed: ${err.message}`));
1225
+ return false;
1226
+ }
1227
+ s.stop(pc.dim("Search complete."));
1228
+
1229
+ const items = searchRes?.result || [];
1230
+ if (items.length === 0) {
1231
+ p.log.warn(`No comics found for "${query}" on Komikindo.`);
1232
+ return false;
1233
+ }
1234
+
1235
+ const comicChoices = items.map((it) => ({
1236
+ value: it.url,
1237
+ label: it.title,
1238
+ }));
1239
+ comicChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1240
+
1241
+ const chosenComicUrl = await p.select({
1242
+ message: `Select Comic (${items.length} found):`,
1243
+ options: comicChoices,
1244
+ });
1245
+ if (p.isCancel(chosenComicUrl) || chosenComicUrl === "cancel") {
1246
+ p.cancel("Cancelled.");
1247
+ return false;
1248
+ }
1249
+
1250
+ s.start(pc.dim("Fetching chapter list..."));
1251
+ let chRes;
1252
+ try {
1253
+ chRes = await scrapr.comic.komikindo.getChapters(chosenComicUrl);
1254
+ } catch (err) {
1255
+ s.stop(pc.bold(`✕ Failed to fetch chapters: ${err.message}`));
1256
+ return false;
1257
+ }
1258
+ s.stop(pc.dim("Chapters fetched."));
1259
+
1260
+ const chapters = chRes?.result || [];
1261
+ if (chapters.length === 0) {
1262
+ p.log.warn("No chapters found for this comic.");
1263
+ return false;
1264
+ }
1265
+
1266
+ const chChoices = chapters.slice(0, 100).map((ch) => ({
1267
+ value: ch.url,
1268
+ label: ch.title,
1269
+ }));
1270
+ chChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1271
+
1272
+ const chosenChUrl = await p.select({
1273
+ message: `Select Chapter (${chapters.length} available):`,
1274
+ options: chChoices,
1275
+ });
1276
+ if (p.isCancel(chosenChUrl) || chosenChUrl === "cancel") {
1277
+ p.cancel("Cancelled.");
1278
+ return false;
1279
+ }
1280
+
1281
+ return await handleScrapeAndDownload(chosenChUrl, options);
1282
+ }
1283
+
1284
+ if (provider === "komiku") {
1285
+ s.start(pc.dim(`Searching Komiku for "${query}"...`));
1286
+ let searchRes;
1287
+ try {
1288
+ searchRes = await scrapr.comic.komiku.search(query);
1289
+ } catch (err) {
1290
+ s.stop(pc.bold(`✕ Search failed: ${err.message}`));
1291
+ return false;
1292
+ }
1293
+ s.stop(pc.dim("Search complete."));
1294
+
1295
+ const items = searchRes?.result || [];
1296
+ if (items.length === 0) {
1297
+ p.log.warn(`No comics found for "${query}" on Komiku.`);
1298
+ return false;
1299
+ }
1300
+
1301
+ const comicChoices = items.map((it) => ({
1302
+ value: it.url,
1303
+ label: it.title,
1304
+ }));
1305
+ comicChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1306
+
1307
+ const chosenComicUrl = await p.select({
1308
+ message: `Select Comic (${items.length} found):`,
1309
+ options: comicChoices,
1310
+ });
1311
+ if (p.isCancel(chosenComicUrl) || chosenComicUrl === "cancel") {
1312
+ p.cancel("Cancelled.");
1313
+ return false;
1314
+ }
1315
+
1316
+ s.start(pc.dim("Fetching chapter list..."));
1317
+ let chRes;
1318
+ try {
1319
+ chRes = await scrapr.comic.komiku.getChapters(chosenComicUrl);
1320
+ } catch (err) {
1321
+ s.stop(pc.bold(`✕ Failed to fetch chapters: ${err.message}`));
1322
+ return false;
1323
+ }
1324
+ s.stop(pc.dim("Chapters fetched."));
1325
+
1326
+ const chapters = chRes?.result || [];
1327
+ if (chapters.length === 0) {
1328
+ p.log.warn("No chapters found for this comic.");
1329
+ return false;
1330
+ }
1331
+
1332
+ const chChoices = chapters.slice(0, 100).map((ch) => ({
1333
+ value: ch.url,
1334
+ label: ch.title,
1335
+ }));
1336
+ chChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1337
+
1338
+ const chosenChUrl = await p.select({
1339
+ message: `Select Chapter (${chapters.length} available):`,
1340
+ options: chChoices,
1341
+ });
1342
+ if (p.isCancel(chosenChUrl) || chosenChUrl === "cancel") {
1343
+ p.cancel("Cancelled.");
1344
+ return false;
1345
+ }
1346
+
1347
+ return await handleScrapeAndDownload(chosenChUrl, options);
1348
+ }
1349
+
1350
+ if (provider === "asurascans") {
1351
+ s.start(pc.dim(`Searching Asura Scans for "${query}"...`));
1352
+ let searchRes;
1353
+ try {
1354
+ searchRes = await scrapr.comic.asurascans.search(query);
1355
+ } catch (err) {
1356
+ s.stop(pc.bold(`✕ Search failed: ${err.message}`));
1357
+ return false;
1358
+ }
1359
+ s.stop(pc.dim("Search complete."));
1360
+
1361
+ const items = searchRes?.result || [];
1362
+ if (items.length === 0) {
1363
+ p.log.warn(`No comics found for "${query}" on Asura Scans.`);
1364
+ return false;
1365
+ }
1366
+
1367
+ const comicChoices = items.map((it) => ({
1368
+ value: it.url,
1369
+ label: `${it.title} ${it.status ? pc.dim(`[${it.status}]`) : ""}`,
1370
+ }));
1371
+ comicChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1372
+
1373
+ const chosenComicUrl = await p.select({
1374
+ message: `Select Comic (${items.length} found):`,
1375
+ options: comicChoices,
1376
+ });
1377
+ if (p.isCancel(chosenComicUrl) || chosenComicUrl === "cancel") {
1378
+ p.cancel("Cancelled.");
1379
+ return false;
1380
+ }
1381
+
1382
+ s.start(pc.dim("Fetching chapter list..."));
1383
+ let chRes;
1384
+ try {
1385
+ chRes = await scrapr.comic.asurascans.getChapters(chosenComicUrl);
1386
+ } catch (err) {
1387
+ s.stop(pc.bold(`✕ Failed to fetch chapters: ${err.message}`));
1388
+ return false;
1389
+ }
1390
+ s.stop(pc.dim("Chapters fetched."));
1391
+
1392
+ const chapters = chRes?.result || [];
1393
+ if (chapters.length === 0) {
1394
+ p.log.warn("No chapters found for this comic.");
1395
+ return false;
1396
+ }
1397
+
1398
+ const chChoices = chapters.slice(0, 100).map((ch) => ({
1399
+ value: ch.url,
1400
+ label: ch.title,
1401
+ }));
1402
+ chChoices.push({ value: "cancel", label: pc.dim("Cancel") });
1403
+
1404
+ const chosenChUrl = await p.select({
1405
+ message: `Select Chapter (${chapters.length} available):`,
1406
+ options: chChoices,
1407
+ });
1408
+ if (p.isCancel(chosenChUrl) || chosenChUrl === "cancel") {
1409
+ p.cancel("Cancelled.");
1410
+ return false;
1411
+ }
1412
+
1413
+ return await handleScrapeAndDownload(chosenChUrl, options);
1414
+ }
1415
+
1416
+ return false;
1417
+ }
1418
+
1419
+ async function handleRollbackMori() {
1420
+ const s = p.spinner();
1421
+ s.start(pc.dim("Fetching Mori Engine commit history from GitHub..."));
1422
+ const history = await fetchMoriEngineHistory();
1423
+ s.stop(pc.dim("History fetched."));
1424
+
1425
+ if (history.length === 0) {
1426
+ p.log.warn("Could not fetch Mori Core commit history from GitHub.");
1427
+ return false;
1428
+ }
1429
+
1430
+ const currentVer = getActiveScraperVersion();
1431
+ const commitChoice = await p.select({
1432
+ message: `Select Mori Core version / commit (Current: v${currentVer || "none"}):`,
1433
+ options: [
1434
+ ...history.map((h, idx) => ({
1435
+ value: h.fullSha,
1436
+ label: `[${h.sha}] ${h.message}`,
1437
+ hint: `${idx === 0 ? "Latest • " : ""}${h.date ? h.date.split("T")[0] : ""}`,
1438
+ })),
1439
+ { value: "cancel", label: pc.dim("Cancel") },
1440
+ ],
1441
+ });
1442
+
1443
+ if (p.isCancel(commitChoice) || commitChoice === "cancel") return false;
1444
+
1445
+ const dlSpin = p.spinner();
1446
+ dlSpin.start(pc.dim("Downloading Mori Core bundle..."));
1447
+ try {
1448
+ const res = await downloadMoriEngineByCommit(commitChoice, (msg) => {
1449
+ dlSpin.message(pc.dim(msg));
1450
+ });
1451
+ dlSpin.stop(pc.bold(`✔ Mori Core Engine installed (v${res.version}).`));
1452
+ return true;
1453
+ } catch (err) {
1454
+ dlSpin.stop(pc.bold(`✕ Installation failed: ${err.message}`));
1455
+ return false;
1456
+ }
1457
+ }
1458
+
1459
+ async function handleRollbackScrapr() {
1460
+ const s = p.spinner();
1461
+ s.start(pc.dim("Fetching available Scrapr versions from NPM..."));
1462
+ const versions = await fetchScraprEngineVersions();
1463
+ s.stop(pc.dim("Versions fetched."));
663
1464
 
664
- if (downloads.length > 1) {
665
- const formatChoice = await p.select({
666
- message: "Select stream:",
667
- options: downloads.map((d, i) => ({
668
- value: i,
669
- label: pc.bold(d.type || `Stream ${i + 1}`),
670
- hint: d.quality || (d.isMirror ? "Mirror" : ""),
671
- })),
672
- });
1465
+ if (versions.length === 0) {
1466
+ p.log.warn("Could not fetch Scrapr versions from registry.");
1467
+ return false;
1468
+ }
673
1469
 
674
- if (p.isCancel(formatChoice)) {
675
- p.cancel("Cancelled.");
676
- return false;
677
- }
678
- selectedItem = downloads[formatChoice];
679
- }
1470
+ const currentVer = getActiveScraprVersion();
1471
+ const verChoice = await p.select({
1472
+ message: `Select Scrapr version to install (Current: v${currentVer || "none"}):`,
1473
+ options: [
1474
+ ...versions.slice(0, 15).map((v) => ({
1475
+ value: v,
1476
+ label: `v${v}${v === currentVer ? pc.green(" (current)") : ""}`,
1477
+ })),
1478
+ { value: "cancel", label: pc.dim("Cancel") },
1479
+ ],
1480
+ });
680
1481
 
681
- await processDownloadItem({
682
- item: selectedItem,
683
- meta: media,
684
- outputDir,
685
- index: 0,
686
- total: 1,
1482
+ if (p.isCancel(verChoice) || verChoice === "cancel") return false;
1483
+
1484
+ const dlSpin = p.spinner();
1485
+ dlSpin.start(pc.dim(`Installing Scrapr Engine v${verChoice}...`));
1486
+ try {
1487
+ const res = await downloadScraprEngineVersion(verChoice, (msg) => {
1488
+ dlSpin.message(pc.dim(msg));
687
1489
  });
1490
+ dlSpin.stop(pc.bold(`✔ Scrapr Engine v${res.version} installed.`));
1491
+ return true;
1492
+ } catch (err) {
1493
+ dlSpin.stop(pc.bold(`✕ Installation failed: ${err.message}`));
1494
+ return false;
688
1495
  }
689
-
690
- return true;
691
1496
  }
692
1497
 
693
1498
  async function main() {
@@ -695,6 +1500,7 @@ async function main() {
695
1500
  args: process.argv.slice(2),
696
1501
  options: {
697
1502
  output: { type: "string", short: "o" },
1503
+ engine: { type: "string", short: "e" },
698
1504
  server: { type: "string", short: "s" },
699
1505
  audio: { type: "boolean", short: "a", default: false },
700
1506
  pdf: { type: "boolean", short: "p", default: false },
@@ -715,26 +1521,65 @@ async function main() {
715
1521
  }
716
1522
 
717
1523
  if (values.version) {
718
- console.log(
719
- `Mori CLI v${APP_VERSION} (core v${getActiveScraperVersion()})`,
720
- );
1524
+ const core = getActiveScraperVersion();
1525
+ const scrapr = getActiveScraprVersion();
1526
+ const parts = [];
1527
+ if (core) parts.push(`mori core v${core}`);
1528
+ if (scrapr) parts.push(`scrapr v${scrapr}`);
1529
+ const engStr = parts.length > 0 ? ` (${parts.join(" • ")})` : " (no engines installed)";
1530
+ console.log(`Mori CLI v${APP_VERSION}${engStr}`);
721
1531
  process.exit(0);
722
1532
  }
723
1533
 
724
1534
  // Handle manual OTA update flag
725
1535
  if (values.update) {
1536
+ const moriInst = isMoriInstalled();
1537
+ const scraprInst = isScraprInstalled();
1538
+
1539
+ if (!moriInst && !scraprInst) {
1540
+ p.log.warn("No scraper engines installed yet. Run 'mori' to set up engines.");
1541
+ process.exit(0);
1542
+ }
1543
+
726
1544
  const s = p.spinner();
727
- s.start(pc.dim("Checking remote scraper patch..."));
1545
+ s.start(pc.dim("Checking remote scraper updates..."));
728
1546
  try {
729
- const res = await checkForOtaUpdate(true);
730
- if (res.updated) {
731
- s.stop(
732
- pc.bold(`✔ Scrapers updated to v${res.newVersion}`) +
733
- (res.changelog ? pc.dim(` — ${res.changelog}`) : ""),
1547
+ const [moriRes, scraprRes] = await Promise.allSettled([
1548
+ moriInst ? checkForOtaUpdate(true) : Promise.resolve({ notInstalled: true }),
1549
+ scraprInst ? checkForScraprOtaUpdate(true) : Promise.resolve({ notInstalled: true }),
1550
+ ]);
1551
+
1552
+ const moriUpdate = moriRes.status === "fulfilled" ? moriRes.value : null;
1553
+ const scraprUpdate =
1554
+ scraprRes.status === "fulfilled" ? scraprRes.value : null;
1555
+
1556
+ const lines = [];
1557
+ if (moriUpdate?.updated) {
1558
+ lines.push(
1559
+ pc.bold(`✔ Mori Core updated to v${moriUpdate.newVersion}`) +
1560
+ (moriUpdate.changelog ? pc.dim(` — ${moriUpdate.changelog}`) : ""),
1561
+ );
1562
+ } else if (moriInst && moriUpdate) {
1563
+ lines.push(
1564
+ pc.dim(
1565
+ `Mori Core is up to date (v${moriUpdate.currentVersion || getActiveScraperVersion()}).`,
1566
+ ),
1567
+ );
1568
+ }
1569
+
1570
+ if (scraprUpdate?.updated) {
1571
+ lines.push(
1572
+ pc.bold(`✔ Scrapr Engine updated to v${scraprUpdate.newVersion}`),
1573
+ );
1574
+ } else if (scraprInst && scraprUpdate) {
1575
+ lines.push(
1576
+ pc.dim(
1577
+ `Scrapr Engine is up to date (v${scraprUpdate.currentVersion || getActiveScraprVersion()}).`,
1578
+ ),
734
1579
  );
735
- } else {
736
- s.stop(pc.dim(`Scrapers already up to date (v${res.currentVersion}).`));
737
1580
  }
1581
+
1582
+ s.stop(lines.join("\n"));
738
1583
  } catch (err) {
739
1584
  s.stop(pc.bold(`✕ OTA check failed: ${err.message}`));
740
1585
  }
@@ -742,20 +1587,42 @@ async function main() {
742
1587
  }
743
1588
 
744
1589
  const coreVer = getActiveScraperVersion();
745
- printBanner(coreVer);
1590
+ const scraprVer = getActiveScraprVersion();
1591
+ printBanner(coreVer, scraprVer);
746
1592
 
747
- // Background non-blocking silent OTA check (timeout 2s)
748
- checkForOtaUpdate(false)
749
- .then((ota) => {
750
- if (ota?.updated) {
751
- p.log.message(
752
- pc.dim(
753
- `● New scraper patch installed in background: v${ota.newVersion}`,
754
- ),
755
- );
756
- }
757
- })
758
- .catch(() => {});
1593
+ // Check if first-run engine setup is required
1594
+ if (!isMoriInstalled() && !isScraprInstalled()) {
1595
+ await ensureEnginesInstalled();
1596
+ }
1597
+
1598
+ // Background non-blocking silent OTA check (only for installed engines)
1599
+ if (isMoriInstalled()) {
1600
+ checkForOtaUpdate(false)
1601
+ .then((ota) => {
1602
+ if (ota?.updated) {
1603
+ p.log.message(
1604
+ pc.dim(
1605
+ `● New Mori Core patch installed in background: v${ota.newVersion}`,
1606
+ ),
1607
+ );
1608
+ }
1609
+ })
1610
+ .catch(() => {});
1611
+ }
1612
+
1613
+ if (isScraprInstalled()) {
1614
+ checkForScraprOtaUpdate(false)
1615
+ .then((scraprOta) => {
1616
+ if (scraprOta?.updated) {
1617
+ p.log.message(
1618
+ pc.dim(
1619
+ `● New Scrapr Engine bundle installed in background: v${scraprOta.newVersion}`,
1620
+ ),
1621
+ );
1622
+ }
1623
+ })
1624
+ .catch(() => {});
1625
+ }
759
1626
 
760
1627
  const cliUpdatePromise = checkCliUpdate();
761
1628
 
@@ -785,6 +1652,26 @@ async function main() {
785
1652
  let lastUrl = null;
786
1653
 
787
1654
  if (targetUrl) {
1655
+ const isUrl =
1656
+ targetUrl.startsWith("http://") || targetUrl.startsWith("https://");
1657
+ if (!isUrl) {
1658
+ lastUrl = targetUrl;
1659
+ await handleSearchAndDownload(targetUrl, null, {
1660
+ ...values,
1661
+ output: currentOutputDir,
1662
+ });
1663
+ const newVer = await cliUpdatePromise;
1664
+ if (newVer) {
1665
+ p.log.message(
1666
+ pc.yellow(
1667
+ `● Update available: v${APP_VERSION} → v${newVer} (run: npm i -g @coflyn/mori)`,
1668
+ ),
1669
+ );
1670
+ }
1671
+ p.outro(pc.dim("Complete."));
1672
+ process.exit(0);
1673
+ }
1674
+
788
1675
  const platform = detectPlatform(targetUrl);
789
1676
  if (!platform) {
790
1677
  p.log.error(`Unsupported URL: ${targetUrl}`);
@@ -820,17 +1707,22 @@ async function main() {
820
1707
 
821
1708
  while (keepGoing) {
822
1709
  const urlInput = await p.text({
823
- message: "Paste link:",
824
- placeholder: "https://... or type /help",
1710
+ message: "Paste link or search title:",
1711
+ placeholder: "https://..., anime/comic title, or type /help",
825
1712
  validate: (val) => {
826
1713
  if (!val || val.trim().length === 0)
827
- return "Please enter a URL or /command.";
1714
+ return "Please enter a URL, title, or /command.";
828
1715
  const clean = val.trim().toLowerCase();
829
1716
  if (clean === "exit" || clean === "quit" || clean === "q")
830
1717
  return undefined;
831
1718
  if (clean.startsWith("/")) return undefined;
832
- if (!detectPlatform(val.trim())) {
833
- return "Platform not supported. Type /platform to view supported platforms.";
1719
+ if (
1720
+ val.trim().startsWith("http://") ||
1721
+ val.trim().startsWith("https://")
1722
+ ) {
1723
+ if (!detectPlatform(val.trim())) {
1724
+ return "Platform not supported. Type /platform to view supported platforms.";
1725
+ }
834
1726
  }
835
1727
  return undefined;
836
1728
  },
@@ -859,17 +1751,62 @@ async function main() {
859
1751
  case "platform":
860
1752
  case "platforms": {
861
1753
  const platformList = [
862
- `${pc.bold("Video :")} TikTok, Douyin, YouTube, Instagram, Facebook, Bilibili, Reddit, Threads, Twitter/X`,
863
- `${pc.bold("Audio :")} Spotify, Apple Music, Bandcamp`,
864
- `${pc.bold("Photo :")} Pinterest, Pixiv, RedNote (Xiaohongshu)`,
865
- `${pc.bold("Cloud :")} TeraBox (1024tera, nephobox, etc.)`,
1754
+ `${pc.bold("Social/Video:")} TikTok, Douyin, YouTube, Instagram, Facebook, Bilibili, Reddit, Threads, Twitter/X, Doodstream`,
1755
+ `${pc.bold("Music/Audio :")} Spotify, SoundCloud, Apple Music, Bandcamp`,
1756
+ `${pc.bold("Photo/Art :")} Pinterest, Pixiv, RedNote (Xiaohongshu)`,
1757
+ `${pc.bold("Cloud/Files :")} TeraBox, MediaFire, Sfile, Catbox, Pixeldrain, Krakenfiles, Google Drive`,
1758
+ `${pc.bold("Resolvers :")} SafeLinkU, Sub2Unlock, Rekonise, Link Unshortener`,
1759
+ `${pc.bold("Comic/Manga :")} Kiryuu, Komikcast, MangaDex, Komikindo, Komiku, Bacakomik, ManhwaIndo, Asura Scans, MangaBats`,
1760
+ `${pc.bold("Anime :")} Otakudesu, Nimegami, Gogoanime, AnimeTosho`,
866
1761
  ];
867
- p.note(platformList.join("\n"), pc.dim("Supported Platforms (16)"));
1762
+ p.note(platformList.join("\n"), pc.dim("Supported Platforms (40 • Dual-Engine)"));
1763
+ break;
1764
+ }
1765
+
1766
+ case "anime": {
1767
+ let query = args.join(" ").trim();
1768
+ if (!query) {
1769
+ const qInput = await p.text({
1770
+ message: "Enter anime title to search:",
1771
+ placeholder: "e.g. majo no tabi tabi",
1772
+ validate: (v) => (!v || !v.trim() ? "Title required." : undefined),
1773
+ });
1774
+ if (p.isCancel(qInput)) break;
1775
+ query = qInput.trim();
1776
+ }
1777
+ await handleSearchAndDownload(query, "anime", {
1778
+ ...values,
1779
+ output: currentOutputDir,
1780
+ });
1781
+ break;
1782
+ }
1783
+
1784
+ case "comic":
1785
+ case "manga": {
1786
+ let query = args.join(" ").trim();
1787
+ if (!query) {
1788
+ const qInput = await p.text({
1789
+ message: "Enter comic/manga title to search:",
1790
+ placeholder: "e.g. solo leveling",
1791
+ validate: (v) => (!v || !v.trim() ? "Title required." : undefined),
1792
+ });
1793
+ if (p.isCancel(qInput)) break;
1794
+ query = qInput.trim();
1795
+ }
1796
+ await handleSearchAndDownload(query, "comic", {
1797
+ ...values,
1798
+ output: currentOutputDir,
1799
+ });
868
1800
  break;
869
1801
  }
870
1802
 
871
1803
  case "play": {
872
- const items = getHistory(15);
1804
+ const items = getHistory(25);
1805
+ if (items.length === 0) {
1806
+ p.log.warn("No download history found to play.");
1807
+ break;
1808
+ }
1809
+
873
1810
  let targetItem = null;
874
1811
  let targetNum = 1;
875
1812
 
@@ -887,13 +1824,6 @@ async function main() {
887
1824
  } else {
888
1825
  const customPath = path.resolve(args.join(" "));
889
1826
  if (fs.existsSync(customPath)) {
890
- const ext = path.extname(customPath).toLowerCase();
891
- if (ext !== ".mp4" && ext !== ".mp3" && ext !== ".m4a") {
892
- p.log.warn(
893
- `Cannot play ${ext ? ext.toUpperCase() : "this"} file. /play is only for MP4 and MP3 (use /open to view files).`,
894
- );
895
- break;
896
- }
897
1827
  try {
898
1828
  await openFile(customPath);
899
1829
  p.log.step(`${pc.bold("Playing:")} ${pc.dim(customPath)}`);
@@ -902,27 +1832,40 @@ async function main() {
902
1832
  }
903
1833
  break;
904
1834
  }
1835
+ p.log.error(`File does not exist: ${customPath}`);
1836
+ break;
905
1837
  }
906
1838
  } else {
907
- if (items.length > 0) {
908
- const playIdx = items.findIndex((it) => {
909
- const ext = path
910
- .extname(it.path || it.filename || "")
911
- .toLowerCase();
912
- return ext === ".mp4" || ext === ".mp3" || ext === ".m4a";
913
- });
914
- if (playIdx !== -1) {
915
- targetItem = items[playIdx];
916
- targetNum = playIdx + 1;
917
- } else {
918
- targetItem = items[0];
919
- }
920
- }
921
- }
1839
+ const selectChoice = await p.select({
1840
+ message: "Select media to play:",
1841
+ options: [
1842
+ ...items.map((it, idx) => {
1843
+ const ext = path
1844
+ .extname(it.path || it.filename || "")
1845
+ .toLowerCase();
1846
+ const typeLabel =
1847
+ ext === ".mp4" || ext === ".mkv" || ext === ".webm"
1848
+ ? "VIDEO"
1849
+ : ext === ".mp3" || ext === ".m4a" || ext === ".wav"
1850
+ ? "AUDIO"
1851
+ : ext === ".pdf"
1852
+ ? "PDF"
1853
+ : ext.slice(1).toUpperCase() || "MEDIA";
1854
+ return {
1855
+ value: idx,
1856
+ label: `[#${idx + 1}] ${it.filename || it.title || "Media"}`,
1857
+ hint: `${it.platform || "media"} • ${typeLabel}`,
1858
+ };
1859
+ }),
1860
+ { value: -1, label: pc.dim("Cancel") },
1861
+ ],
1862
+ });
922
1863
 
923
- if (!targetItem) {
924
- p.log.warn("No downloaded media found in history to play.");
925
- break;
1864
+ if (p.isCancel(selectChoice) || selectChoice === -1) {
1865
+ break;
1866
+ }
1867
+ targetItem = items[selectChoice];
1868
+ targetNum = selectChoice + 1;
926
1869
  }
927
1870
 
928
1871
  if (!targetItem.path || !fs.existsSync(targetItem.path)) {
@@ -932,20 +1875,6 @@ async function main() {
932
1875
  break;
933
1876
  }
934
1877
 
935
- const fileExt = path
936
- .extname(targetItem.path || targetItem.filename || "")
937
- .toLowerCase();
938
- if (
939
- fileExt !== ".mp4" &&
940
- fileExt !== ".mp3" &&
941
- fileExt !== ".m4a"
942
- ) {
943
- p.log.warn(
944
- `Item #${targetNum} is a ${fileExt ? fileExt.toUpperCase() : "non-audio/video"} file. /play is only for MP4 and MP3 (type /open to view files).`,
945
- );
946
- break;
947
- }
948
-
949
1878
  try {
950
1879
  await openFile(targetItem.path);
951
1880
  p.log.step(
@@ -960,63 +1889,96 @@ async function main() {
960
1889
  case "delete":
961
1890
  case "del":
962
1891
  case "rm": {
963
- const items = getHistory(20);
1892
+ const items = getHistory(25);
964
1893
  if (items.length === 0) {
965
1894
  p.log.warn("No download history to delete.");
966
1895
  break;
967
1896
  }
968
1897
 
969
- let targetIndex = -1;
1898
+ let targetIndices = [];
970
1899
 
971
1900
  if (args[0]) {
972
- const numArg = parseInt(args[0], 10);
973
- if (isNaN(numArg) || numArg < 1 || numArg > items.length) {
1901
+ const rawIndices = args[0]
1902
+ .split(",")
1903
+ .map((s) => parseInt(s.trim(), 10));
1904
+ const validIndices = rawIndices
1905
+ .filter((n) => !isNaN(n) && n >= 1 && n <= items.length)
1906
+ .map((n) => n - 1);
1907
+
1908
+ if (validIndices.length === 0) {
974
1909
  p.log.warn(
975
1910
  `Invalid index. Available range: 1 to ${items.length}.`,
976
1911
  );
977
1912
  break;
978
1913
  }
979
- targetIndex = numArg - 1;
1914
+ targetIndices = validIndices;
980
1915
  } else {
981
- const selectChoice = await p.select({
982
- message: "Select item to delete:",
1916
+ const selectedChoices = await p.multiselect({
1917
+ message:
1918
+ "Select item(s) to delete (Space to toggle, Enter to confirm):",
983
1919
  options: [
984
1920
  ...items.map((it, idx) => ({
985
1921
  value: idx,
986
1922
  label: `[#${idx + 1}] ${it.filename || it.title || "Media"}`,
987
1923
  hint: it.platform || "",
988
1924
  })),
989
- { value: -1, label: pc.dim("Cancel") },
990
1925
  ],
1926
+ required: false,
991
1927
  });
992
1928
 
993
- if (p.isCancel(selectChoice) || selectChoice === -1) {
1929
+ if (p.isCancel(selectedChoices) || selectedChoices.length === 0) {
1930
+ p.log.step(pc.dim("Deletion cancelled."));
994
1931
  break;
995
1932
  }
996
- targetIndex = selectChoice;
1933
+ targetIndices = selectedChoices;
997
1934
  }
998
1935
 
999
- const itemToDelete = items[targetIndex];
1000
- const confirm = await p.confirm({
1001
- message: `Delete "${itemToDelete.filename || itemToDelete.title}" from disk and history?`,
1002
- initialValue: false,
1936
+ const targetNames = targetIndices
1937
+ .map(
1938
+ (i) => `[#${i + 1}] ${items[i]?.filename || items[i]?.title}`,
1939
+ )
1940
+ .join(", ");
1941
+
1942
+ const deleteMode = await p.select({
1943
+ message:
1944
+ targetIndices.length === 1
1945
+ ? `Delete "${items[targetIndices[0]]?.filename || items[targetIndices[0]]?.title}":`
1946
+ : `Delete ${targetIndices.length} item(s) (${targetNames}):`,
1947
+ options: [
1948
+ {
1949
+ value: "both",
1950
+ label: "Delete from disk & remove from history",
1951
+ hint: "Permanently deletes the physical file",
1952
+ },
1953
+ {
1954
+ value: "history",
1955
+ label: "Remove from history only",
1956
+ hint: "Keeps the file safe on disk",
1957
+ },
1958
+ { value: "cancel", label: pc.dim("Cancel") },
1959
+ ],
1003
1960
  });
1004
1961
 
1005
- if (p.isCancel(confirm) || !confirm) {
1962
+ if (p.isCancel(deleteMode) || deleteMode === "cancel") {
1006
1963
  p.log.step(pc.dim("Deletion cancelled."));
1007
1964
  break;
1008
1965
  }
1009
1966
 
1010
- const res = deleteHistoryItem(targetIndex, true);
1967
+ const deleteFromDisk = deleteMode === "both";
1968
+ const res = deleteHistoryItems(targetIndices, deleteFromDisk);
1011
1969
  if (res.success) {
1012
- const fileNote = res.fileDeleted
1013
- ? pc.dim("(deleted from disk & removed from history)")
1014
- : pc.dim("(removed from history; file was not on disk)");
1970
+ const fileNote = deleteFromDisk
1971
+ ? res.filesDeletedCount > 0
1972
+ ? pc.dim(
1973
+ `(${res.filesDeletedCount} file(s) deleted from disk & removed from history)`,
1974
+ )
1975
+ : pc.dim(`(removed from history; file(s) not found on disk)`)
1976
+ : pc.dim(`(removed from history; file(s) preserved on disk)`);
1015
1977
  p.log.step(
1016
- `${pc.bold("✔ Deleted:")} ${pc.white(itemToDelete.filename || itemToDelete.title)} ${fileNote}`,
1978
+ `${pc.bold("✔ Deleted:")} ${pc.white(`${res.count} item(s)`)} ${fileNote}`,
1017
1979
  );
1018
1980
  } else {
1019
- p.log.error(`Failed to delete item: ${res.error}`);
1981
+ p.log.error(`Failed to delete items: ${res.error}`);
1020
1982
  }
1021
1983
  break;
1022
1984
  }
@@ -1169,6 +2131,233 @@ async function main() {
1169
2131
  break;
1170
2132
  }
1171
2133
 
2134
+ case "engine": {
2135
+ const moriInst = isMoriInstalled();
2136
+ const scraprInst = isScraprInstalled();
2137
+ const currentPref = getSavedConfig().defaultEngine || "auto";
2138
+
2139
+ const options = [
2140
+ {
2141
+ value: "auto",
2142
+ label: "Auto (Recommended)",
2143
+ hint: `Cascade engines • Mori: ${moriInst ? "v" + (getActiveScraperVersion() || "installed") : "missing"} • Scrapr: ${scraprInst ? "v" + (getActiveScraprVersion() || "installed") : "missing"}`,
2144
+ },
2145
+ {
2146
+ value: "mori",
2147
+ label: "Mori Engine",
2148
+ hint: `Core browser scrapers ~80 KB • ${moriInst ? "Installed (v" + (getActiveScraperVersion() || "1.0.0") + ")" : "Not installed"}`,
2149
+ },
2150
+ {
2151
+ value: "scrapr",
2152
+ label: "Scrapr Engine",
2153
+ hint: `Resolvers & scrapers ~2.7 MB • ${scraprInst ? "Installed (v" + (getActiveScraprVersion() || "1.3.1") + ")" : "Not installed"}`,
2154
+ },
2155
+ ];
2156
+
2157
+ if (!moriInst || !scraprInst) {
2158
+ options.push({
2159
+ value: "install_missing",
2160
+ label: "Install Missing Engine...",
2161
+ hint: !moriInst && !scraprInst ? "Both missing" : !moriInst ? "Install Mori" : "Install Scrapr",
2162
+ });
2163
+ }
2164
+
2165
+ options.push({
2166
+ value: "manage",
2167
+ label: "Manage Engines (Reinstall / Uninstall)...",
2168
+ hint: "Re-download or remove engines",
2169
+ });
2170
+
2171
+ const choice = await p.select({
2172
+ message: "Select extraction engine preference:",
2173
+ options,
2174
+ initialValue: currentPref,
2175
+ });
2176
+
2177
+ if (p.isCancel(choice)) break;
2178
+
2179
+ if (choice === "install_missing") {
2180
+ if (!moriInst) {
2181
+ const s = p.spinner();
2182
+ s.start(pc.dim("Installing Mori Core Engine (~80 KB)..."));
2183
+ try {
2184
+ const res = await downloadMoriEngine();
2185
+ s.stop(pc.bold(`✔ Mori Core Engine installed (v${res.version}).`));
2186
+ } catch (err) {
2187
+ s.stop(pc.bold(`✕ Failed: ${err.message}`));
2188
+ }
2189
+ }
2190
+ if (!scraprInst) {
2191
+ const s = p.spinner();
2192
+ s.start(pc.dim("Installing Scrapr Engine (~2.7 MB)..."));
2193
+ try {
2194
+ const res = await downloadScraprEngine();
2195
+ s.stop(pc.bold(`✔ Scrapr Engine installed (v${res.version}).`));
2196
+ } catch (err) {
2197
+ s.stop(pc.bold(`✕ Failed: ${err.message}`));
2198
+ }
2199
+ }
2200
+ break;
2201
+ }
2202
+
2203
+ if (choice === "manage") {
2204
+ const mgmtChoice = await p.select({
2205
+ message: "Engine Management:",
2206
+ options: [
2207
+ {
2208
+ value: "reinstall_mori",
2209
+ label: "Reinstall Latest Mori Engine (~80 KB)",
2210
+ hint: moriInst ? "Re-fetch latest bundle" : "Install",
2211
+ },
2212
+ {
2213
+ value: "reinstall_scrapr",
2214
+ label: "Reinstall Latest Scrapr Engine (~2.7 MB)",
2215
+ hint: scraprInst ? "Re-fetch latest bundle" : "Install",
2216
+ },
2217
+ {
2218
+ value: "version_mori",
2219
+ label: "Choose / Downgrade Mori Core Version...",
2220
+ hint: "Install specific commit from GitHub",
2221
+ },
2222
+ {
2223
+ value: "version_scrapr",
2224
+ label: "Choose / Downgrade Scrapr Engine Version...",
2225
+ hint: "Install specific release from NPM",
2226
+ },
2227
+ ...(moriInst
2228
+ ? [
2229
+ {
2230
+ value: "uninstall_mori",
2231
+ label: "Uninstall Mori Engine",
2232
+ hint: "Delete ~/.mori/scrapers-bundle.js",
2233
+ },
2234
+ ]
2235
+ : []),
2236
+ ...(scraprInst
2237
+ ? [
2238
+ {
2239
+ value: "uninstall_scrapr",
2240
+ label: "Uninstall Scrapr Engine",
2241
+ hint: "Delete ~/.mori/scrapr/",
2242
+ },
2243
+ ]
2244
+ : []),
2245
+ { value: "cancel", label: pc.dim("Cancel") },
2246
+ ],
2247
+ });
2248
+
2249
+ if (p.isCancel(mgmtChoice) || mgmtChoice === "cancel") break;
2250
+
2251
+ if (mgmtChoice === "reinstall_mori") {
2252
+ const s = p.spinner();
2253
+ s.start(pc.dim("Downloading Mori Engine..."));
2254
+ try {
2255
+ const res = await downloadMoriEngine();
2256
+ s.stop(pc.bold(`✔ Mori Engine installed (v${res.version}).`));
2257
+ } catch (err) {
2258
+ s.stop(pc.bold(`✕ Failed: ${err.message}`));
2259
+ }
2260
+ } else if (mgmtChoice === "reinstall_scrapr") {
2261
+ const s = p.spinner();
2262
+ s.start(pc.dim("Downloading Scrapr Engine..."));
2263
+ try {
2264
+ const res = await downloadScraprEngine();
2265
+ s.stop(pc.bold(`✔ Scrapr Engine installed (v${res.version}).`));
2266
+ } catch (err) {
2267
+ s.stop(pc.bold(`✕ Failed: ${err.message}`));
2268
+ }
2269
+ } else if (mgmtChoice === "version_mori") {
2270
+ await handleRollbackMori();
2271
+ } else if (mgmtChoice === "version_scrapr") {
2272
+ await handleRollbackScrapr();
2273
+ } else if (mgmtChoice === "uninstall_mori") {
2274
+ uninstallMoriEngine();
2275
+ p.log.message(pc.dim("✔ Mori Engine uninstalled."));
2276
+ } else if (mgmtChoice === "uninstall_scrapr") {
2277
+ uninstallScraprEngine();
2278
+ p.log.message(pc.dim("✔ Scrapr Engine uninstalled."));
2279
+ }
2280
+ break;
2281
+ }
2282
+
2283
+ // If selected mori but not installed
2284
+ if (choice === "mori" && !moriInst) {
2285
+ const confirmDl = await p.confirm({
2286
+ message: "Mori Engine is not installed. Download now (~80 KB)?",
2287
+ initialValue: true,
2288
+ });
2289
+ if (!p.isCancel(confirmDl) && confirmDl) {
2290
+ const s = p.spinner();
2291
+ s.start(pc.dim("Downloading Mori Engine..."));
2292
+ try {
2293
+ const res = await downloadMoriEngine();
2294
+ s.stop(pc.bold(`✔ Mori Engine installed (v${res.version}).`));
2295
+ } catch (err) {
2296
+ s.stop(pc.bold(`✕ Failed: ${err.message}`));
2297
+ break;
2298
+ }
2299
+ } else {
2300
+ break;
2301
+ }
2302
+ }
2303
+
2304
+ // If selected scrapr but not installed
2305
+ if (choice === "scrapr" && !scraprInst) {
2306
+ const confirmDl = await p.confirm({
2307
+ message: "Scrapr Engine is not installed. Download now (~2.7 MB)?",
2308
+ initialValue: true,
2309
+ });
2310
+ if (!p.isCancel(confirmDl) && confirmDl) {
2311
+ const s = p.spinner();
2312
+ s.start(pc.dim("Downloading Scrapr Engine..."));
2313
+ try {
2314
+ const res = await downloadScraprEngine();
2315
+ s.stop(pc.bold(`✔ Scrapr Engine installed (v${res.version}).`));
2316
+ } catch (err) {
2317
+ s.stop(pc.bold(`✕ Failed: ${err.message}`));
2318
+ break;
2319
+ }
2320
+ } else {
2321
+ break;
2322
+ }
2323
+ }
2324
+
2325
+ saveConfig({ defaultEngine: choice });
2326
+ p.log.message(
2327
+ `${pc.bold("● Default engine set:")} ${pc.white(choice)}`,
2328
+ );
2329
+ break;
2330
+ }
2331
+
2332
+ case "rollback":
2333
+ case "downgrade": {
2334
+ const rbChoice = await p.select({
2335
+ message: "Select engine to rollback / choose version:",
2336
+ options: [
2337
+ {
2338
+ value: "mori",
2339
+ label: "Mori Core Engine",
2340
+ hint: `Current: v${getActiveScraperVersion() || "not installed"}`,
2341
+ },
2342
+ {
2343
+ value: "scrapr",
2344
+ label: "Scrapr Engine",
2345
+ hint: `Current: v${getActiveScraprVersion() || "not installed"}`,
2346
+ },
2347
+ { value: "cancel", label: pc.dim("Cancel") },
2348
+ ],
2349
+ });
2350
+
2351
+ if (p.isCancel(rbChoice) || rbChoice === "cancel") break;
2352
+
2353
+ if (rbChoice === "mori") {
2354
+ await handleRollbackMori();
2355
+ } else if (rbChoice === "scrapr") {
2356
+ await handleRollbackScrapr();
2357
+ }
2358
+ break;
2359
+ }
2360
+
1172
2361
  case "clip":
1173
2362
  case "paste": {
1174
2363
  const s = p.spinner();
@@ -1243,13 +2432,14 @@ async function main() {
1243
2432
  break;
1244
2433
  }
1245
2434
 
1246
- const items = getHistory(15);
2435
+ const items = getHistory(25);
1247
2436
  if (items.length === 0) {
1248
2437
  p.log.message(pc.dim("No download history yet."));
1249
2438
  break;
1250
2439
  }
1251
2440
 
1252
- // Check if user specified an iteration number, e.g. /history 1
2441
+ let selectedIndex = -1;
2442
+
1253
2443
  const numArg = parseInt(args[0], 10);
1254
2444
  if (!isNaN(numArg)) {
1255
2445
  if (numArg < 1 || numArg > items.length) {
@@ -1258,40 +2448,56 @@ async function main() {
1258
2448
  );
1259
2449
  break;
1260
2450
  }
1261
- const selected = items[numArg - 1];
1262
- if (!selected.url) {
1263
- p.log.warn(
1264
- `Item #${numArg} has no recorded source URL (downloaded prior to URL tracking).`,
1265
- );
2451
+ selectedIndex = numArg - 1;
2452
+ } else {
2453
+ const choice = await p.select({
2454
+ message: "Download History (Select to re-download):",
2455
+ options: [
2456
+ ...items.map((it, idx) => ({
2457
+ value: idx,
2458
+ label: `[#${idx + 1}] ${it.filename || it.title || "Media"}`,
2459
+ hint: `${it.platform?.toUpperCase() || ""}${it.timestamp ? ` • ${formatRelativeTime(it.timestamp)}` : ""}`,
2460
+ })),
2461
+ { value: "clear", label: pc.red("🗑 Clear all history") },
2462
+ { value: "cancel", label: pc.dim("Cancel") },
2463
+ ],
2464
+ });
2465
+
2466
+ if (p.isCancel(choice) || choice === "cancel") {
1266
2467
  break;
1267
2468
  }
1268
- p.log.message(
1269
- `${pc.bold("● Re-downloading from history:")} ${pc.inverse(` ${selected.platform?.toUpperCase()} `)} ${pc.dim(selected.url)}`,
2469
+
2470
+ if (choice === "clear") {
2471
+ const confirmClear = await p.confirm({
2472
+ message:
2473
+ "Are you sure you want to clear all download history?",
2474
+ initialValue: false,
2475
+ });
2476
+ if (confirmClear && !p.isCancel(confirmClear)) {
2477
+ clearHistory();
2478
+ p.log.message(pc.dim("Download history cleared."));
2479
+ }
2480
+ break;
2481
+ }
2482
+
2483
+ selectedIndex = choice;
2484
+ }
2485
+
2486
+ const selected = items[selectedIndex];
2487
+ if (!selected.url) {
2488
+ p.log.warn(
2489
+ `Item #${selectedIndex + 1} has no recorded source URL (downloaded prior to URL tracking).`,
1270
2490
  );
1271
- lastUrl = selected.url;
1272
- await handleScrapeAndDownload(selected.url, {
1273
- ...values,
1274
- output: currentOutputDir,
1275
- });
1276
2491
  break;
1277
2492
  }
1278
-
1279
- const historyLines = items.map((it, idx) => {
1280
- const num = pc.bold(`[${idx + 1}]`);
1281
- const badge = pc.inverse(` ${it.platform.toUpperCase()} `);
1282
- const name = pc.bold(it.filename || it.title || "Media");
1283
- const rel = it.timestamp
1284
- ? pc.dim(`(${formatRelativeTime(it.timestamp)})`)
1285
- : "";
1286
- return `${num} ${badge} ${name} ${rel}`;
1287
- });
1288
-
1289
- p.note(
1290
- historyLines.join("\n"),
1291
- pc.dim(
1292
- `Recent Downloads (${items.length}) • /history <num> to redownload • /history clear to reset`,
1293
- ),
2493
+ p.log.message(
2494
+ `${pc.bold("● Re-downloading from history:")} ${pc.inverse(` ${selected.platform?.toUpperCase()} `)} ${pc.dim(selected.url)}`,
1294
2495
  );
2496
+ lastUrl = selected.url;
2497
+ await handleScrapeAndDownload(selected.url, {
2498
+ ...values,
2499
+ output: currentOutputDir,
2500
+ });
1295
2501
  break;
1296
2502
  }
1297
2503
 
@@ -1299,9 +2505,11 @@ async function main() {
1299
2505
  const cfg = getSavedConfig();
1300
2506
  const cfgLines = [
1301
2507
  `${pc.bold("Download Dir :")} ${pc.white(currentOutputDir)}`,
2508
+ `${pc.bold("Default Engine:")} ${pc.white(cfg.defaultEngine || "auto")}`,
1302
2509
  `${pc.bold("Default Server:")} ${pc.white(cfg.defaultServer || "auto")}`,
1303
2510
  `${pc.bold("CLI Version :")} ${pc.white(`v${APP_VERSION}`)}`,
1304
- `${pc.bold("Core Version :")} ${pc.white(`v${getActiveScraperVersion()}`)}`,
2511
+ `${pc.bold("Mori Core Ver :")} ${pc.white(`v${getActiveScraperVersion()}`)}`,
2512
+ `${pc.bold("Scrapr Ver :")} ${pc.white(`v${getActiveScraprVersion()}`)}`,
1305
2513
  `${pc.bold("Config Path :")} ${pc.dim(CONFIG_PATH)}`,
1306
2514
  ];
1307
2515
  p.note(cfgLines.join("\n"), pc.dim("Active Configuration"));
@@ -1404,7 +2612,14 @@ async function main() {
1404
2612
  s.start(pc.dim("Checking for updates..."));
1405
2613
  try {
1406
2614
  const cliVer = await checkCliUpdate();
1407
- const ota = await checkForOtaUpdate(true);
2615
+ const [moriRes, scraprRes] = await Promise.allSettled([
2616
+ isMoriInstalled()
2617
+ ? checkForOtaUpdate(true)
2618
+ : Promise.resolve({ notInstalled: true }),
2619
+ isScraprInstalled()
2620
+ ? checkForScraprOtaUpdate(true)
2621
+ : Promise.resolve({ notInstalled: true }),
2622
+ ]);
1408
2623
 
1409
2624
  s.stop(pc.bold("Update Check:"));
1410
2625
 
@@ -1420,15 +2635,44 @@ async function main() {
1420
2635
  );
1421
2636
  }
1422
2637
 
1423
- if (ota.updated) {
2638
+ const moriUpdate =
2639
+ moriRes.status === "fulfilled" ? moriRes.value : null;
2640
+ const scraprUpdate =
2641
+ scraprRes.status === "fulfilled" ? scraprRes.value : null;
2642
+
2643
+ if (moriUpdate?.notInstalled) {
1424
2644
  p.log.step(
1425
- pc.bold(`✔ Scrapers updated to v${ota.newVersion}`) +
1426
- (ota.changelog ? pc.dim(` — ${ota.changelog}`) : ""),
2645
+ pc.dim("Mori Engine: Not installed (install with /engine)."),
1427
2646
  );
1428
- } else {
2647
+ } else if (moriUpdate?.updated) {
2648
+ p.log.step(
2649
+ pc.bold(`✔ Mori Core updated to v${moriUpdate.newVersion}`) +
2650
+ (moriUpdate.changelog
2651
+ ? pc.dim(` — ${moriUpdate.changelog}`)
2652
+ : ""),
2653
+ );
2654
+ } else if (moriUpdate) {
2655
+ p.log.step(
2656
+ pc.dim(
2657
+ `Mori Core is up to date (v${moriUpdate.currentVersion || getActiveScraperVersion()}).`,
2658
+ ),
2659
+ );
2660
+ }
2661
+
2662
+ if (scraprUpdate?.notInstalled) {
2663
+ p.log.step(
2664
+ pc.dim("Scrapr Engine: Not installed (install with /engine)."),
2665
+ );
2666
+ } else if (scraprUpdate?.updated) {
2667
+ p.log.step(
2668
+ pc.bold(
2669
+ `✔ Scrapr Engine updated to v${scraprUpdate.newVersion}`,
2670
+ ),
2671
+ );
2672
+ } else if (scraprUpdate) {
1429
2673
  p.log.step(
1430
2674
  pc.dim(
1431
- `Scraper engine is up to date (v${ota.currentVersion}).`,
2675
+ `Scrapr Engine is up to date (v${scraprUpdate.currentVersion || getActiveScraprVersion()}).`,
1432
2676
  ),
1433
2677
  );
1434
2678
  }
@@ -1469,30 +2713,34 @@ async function main() {
1469
2713
  case "clear":
1470
2714
  case "cls": {
1471
2715
  console.clear();
1472
- printBanner(getActiveScraperVersion());
2716
+ printBanner(getActiveScraperVersion(), getActiveScraprVersion());
1473
2717
  break;
1474
2718
  }
1475
2719
 
1476
2720
  case "help":
1477
2721
  case "?": {
1478
2722
  const cmds = [
2723
+ `${pc.bold("/anime [query]")} Search and download anime episodes`,
2724
+ `${pc.bold("/comic [query]")} Search and download comic chapters (supports PDF)`,
1479
2725
  `${pc.bold("/clip")} Download link currently in clipboard`,
1480
2726
  `${pc.bold("/audio [url]")} Download audio stream only (MP3/M4A)`,
1481
2727
  `${pc.bold("/pdf [url]")} Download photo album compiled directly into 1 PDF`,
1482
- `${pc.bold("/play [num]")} Play downloaded media in default system player`,
2728
+ `${pc.bold("/play [num]")} Interactive media player picker (or /play <num>)`,
1483
2729
  `${pc.bold("/ping [host]")} Check user network latency (default: 1.1.1.1)`,
1484
2730
  `${pc.bold("/info [url]")} Inspect media details without downloading`,
1485
2731
  `${pc.bold("/retry")} Re-download the last link processed`,
1486
2732
  `${pc.bold("/batch")} Bulk download multiple links at once`,
1487
- `${pc.bold("/platform")} List all 16 supported media platforms`,
2733
+ `${pc.bold("/platform")} List all 40 supported media platforms`,
1488
2734
  `${pc.bold("/dir")} View or set download directory (persistent)`,
1489
2735
  `${pc.bold("/open")} Open download folder in file manager`,
2736
+ `${pc.bold("/engine")} Set default extraction engine (auto/mori/scrapr)`,
1490
2737
  `${pc.bold("/server")} Set default scraper server (auto/1/2)`,
1491
- `${pc.bold("/history [num]")} View or redownload history item (/history 1, /history clear)`,
1492
- `${pc.bold("/delete [num]")} Delete downloaded file from disk and history`,
2738
+ `${pc.bold("/history")} Interactive download history & redownload picker`,
2739
+ `${pc.bold("/delete")} Interactive bulk delete from disk & history (Space)`,
1493
2740
  `${pc.bold("/stats")} View total downloads & storage statistics`,
1494
2741
  `${pc.bold("/config")} Show active Mori configuration`,
1495
- `${pc.bold("/update")} Check and apply remote OTA scraper patch`,
2742
+ `${pc.bold("/update")} Check and apply remote OTA scraper patches`,
2743
+ `${pc.bold("/rollback")} Rollback or install specific engine versions`,
1496
2744
  `${pc.bold("/reset")} Factory reset Mori config, cache, & history`,
1497
2745
  `${pc.bold("/clear")} Clear screen and reprint header`,
1498
2746
  `${pc.bold("/exit, /q")} Exit Mori CLI`,
@@ -1520,10 +2768,17 @@ async function main() {
1520
2768
  }
1521
2769
 
1522
2770
  lastUrl = rawInput;
1523
- await handleScrapeAndDownload(rawInput, {
1524
- ...values,
1525
- output: currentOutputDir,
1526
- });
2771
+ if (!rawInput.startsWith("http://") && !rawInput.startsWith("https://")) {
2772
+ await handleSearchAndDownload(rawInput, null, {
2773
+ ...values,
2774
+ output: currentOutputDir,
2775
+ });
2776
+ } else {
2777
+ await handleScrapeAndDownload(rawInput, {
2778
+ ...values,
2779
+ output: currentOutputDir,
2780
+ });
2781
+ }
1527
2782
 
1528
2783
  const next = await p.confirm({
1529
2784
  message: "Continue?",