-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunQuery.ts
More file actions
697 lines (586 loc) Β· 30.4 KB
/
Copy pathrunQuery.ts
File metadata and controls
697 lines (586 loc) Β· 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import axios from 'axios';
import * as cheerio from 'cheerio';
import { createClient } from '@supabase/supabase-js';
import dotenv from 'dotenv';
import { waterfallMine, mineExtensionAllEpisodes, EXTENSION_WATERFALL } from './engine/waterfall';
import { scrapeGogoanimeLight } from './scrapers/anime/gogoanime';
import { scrapeAnimepahe } from './scrapers/anime/animepahe';
import { getSharedBrowser, closeSharedBrowser } from './scrapers/browserManager';
dotenv.config();
puppeteer.use(StealthPlugin());
const GOGO_DOMAINS = (process.env.GOGO_DOMAINS || '')
.split(',')
.map(d => d.trim().replace(/\/(popular|home)\/?$/i, '').replace(/\/$/, ''))
.filter(Boolean);
const ANIWAVE_CLUSTER = (process.env.ANIWAVE_CLUSTER || '')
.split(',')
.map(d => d.trim().replace(/\/$/, ''))
.filter(Boolean);
const HIANIME_CLUSTER = (process.env.HIANIME_CLUSTER || '')
.split(',')
.map(d => d.trim().replace(/\/(popular|home)\/?$/i, '').replace(/\/$/, ''))
.filter(Boolean);
const supabaseUrl = process.env.SUPABASE_URL || '';
const supabaseKey = process.env.SUPABASE_KEY || '';
async function exitProcess(code: number) {
try {
await closeSharedBrowser();
} catch {}
process.exit(code);
}
if (!supabaseUrl || !supabaseKey) {
console.error('β Missing SUPABASE_URL or SUPABASE_KEY env variables.');
process.exit(1);
}
const supabase = createClient(supabaseUrl, supabaseKey);
const query = process.argv[2];
const serverStr = process.argv[3] || '1';
const episodeStr = process.argv[4] || '';
const forceSource = process.argv[5] || '';
let primaryQueryTitle = query || '';
if (!query) {
console.error('β Usage: ts-node runQuery.ts "anime title" [server] [episode] [forceSource]');
process.exit(1);
}
import { getSearchVariants as getMultiProviderSearchVariants } from './engine/animeMetadata';
// ββ Automated Title Variant Resolver (4-Tier Provider Fallback) ββ
async function getSearchVariants(searchQuery: string): Promise<string[]> {
try {
return await getMultiProviderSearchVariants(searchQuery);
} catch (e) {
return [searchQuery];
}
}
async function saveToSupabase(title: string, episode: number, type: string, url: string) {
const cleanTitle = title.toLowerCase().trim();
const { error } = await supabase.from('anime_links').upsert(
{ title: cleanTitle, episode, type, url },
{ onConflict: 'title, episode, type' }
);
if (error) console.error(`β Supabase error:`, error.message);
else console.log(`β
Saved: [${cleanTitle}] Ep ${episode} (${type})`);
// Save under primary query title as well if variant differs
if (primaryQueryTitle && primaryQueryTitle.toLowerCase().trim() !== cleanTitle) {
const primaryClean = primaryQueryTitle.toLowerCase().trim();
try {
await supabase.from('anime_links').upsert(
{ title: primaryClean, episode, type, url },
{ onConflict: 'title, episode, type' }
);
} catch (e) {}
}
}
async function scrapeAnimePage(browser: any, animeUrl: string, domain: string): Promise<number> {
console.log(`\nπ Scraping series: ${animeUrl}`);
const page = await browser.newPage();
let savedCount = 0;
try {
await page.goto(animeUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
const slugMatch = animeUrl.match(/\/(?:anime|category)\/(.*?)\/?$/i);
const slugBase = slugMatch ? slugMatch[1].split('-')[0].toLowerCase() : '';
let episodeLinks: string[] = await page.evaluate((base: string) => {
const links = Array.from(document.querySelectorAll('a')) as HTMLAnchorElement[];
return [...new Set(
links
.filter(l => l.href && (l.href.includes('-episode-') || l.href.includes('ep-')) && l.href.toLowerCase().includes(base))
.map(l => l.href)
)];
}, slugBase);
episodeLinks = episodeLinks.reverse();
console.log(` πΊ Found ${episodeLinks.length} episodes`);
for (const url of episodeLinks) {
const domainHost = new URL(domain).hostname.replace('.', '\\.');
const match = url.match(new RegExp(`${domainHost}\\/(.*?)-episode-(\\d+)`, 'i'));
if (!match) continue;
const rawTitle = match[1];
const epNum = parseInt(match[2]);
const title = rawTitle.replace(/-/g, ' ').toLowerCase().trim();
try {
const epPage = await browser.newPage();
await epPage.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
const iframeSrc: string | null = await epPage.evaluate(() => {
const iframes = Array.from(document.querySelectorAll('iframe')) as HTMLIFrameElement[];
const player = iframes.find(i => i.src && (
i.src.includes('.php?id=') ||
i.src.includes('.php?ep=') ||
i.src.includes('newplayer') ||
i.src.includes('embed') ||
i.src.includes('gogohd') ||
i.src.includes('gogoplay')
));
return player ? player.src : null;
});
if (iframeSrc) {
await saveToSupabase(title, epNum, 'http', iframeSrc);
savedCount++;
}
await epPage.close();
} catch {
console.log(` β οΈ Failed ep ${epNum}`);
}
}
} catch (e: any) {
console.log(` β Series scrape failed: ${e.message}`);
}
await page.close();
return savedCount;
}
async function mineFromGogo(query: string): Promise<boolean> {
console.log(`\nπ GogoAnime Puppeteer search for: "${query}"`);
const browser = await getSharedBrowser();
let totalSaved = 0;
for (const domain of GOGO_DOMAINS) {
try {
const searchUrl = `${domain}/search.html?keyword=${encodeURIComponent(query)}`;
console.log(`\nπ Searching: ${searchUrl}`);
const searchPage = await browser.newPage();
await searchPage.goto(searchUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
const queryBase = query.split(' ')[0].toLowerCase().replace(/[^a-z0-9]/g, '');
const searchResults: string[] = await searchPage.evaluate((base: string) => {
const primaryLinks = Array.from(document.querySelectorAll('p.name a, .items li a')) as HTMLAnchorElement[];
const allLinks = Array.from(document.querySelectorAll('a')) as HTMLAnchorElement[];
const linksToSearch = primaryLinks.length > 0 ? primaryLinks : allLinks;
return [...new Set(
linksToSearch
.filter(l => l.href && (l.href.includes('/category/') || l.href.includes('/anime/')) && l.href.toLowerCase().includes(base))
.map(l => l.href)
)];
}, queryBase);
await searchPage.close();
if (searchResults.length === 0) {
console.log(`β οΈ No results on ${domain}`);
continue;
}
console.log(`π― Found ${searchResults.length} matching anime on ${domain}`);
for (const animeUrl of searchResults) {
const count = await scrapeAnimePage(browser, animeUrl, domain);
totalSaved += count;
}
if (totalSaved > 0) break; // Stop after first successful domain
} catch (e: any) {
console.log(`β ${domain} failed: ${e.message}`);
}
}
if (totalSaved > 0) {
console.log(`\nβ
GogoAnime: ${totalSaved} episodes saved.`);
return true;
}
return false;
}
async function mineFromNyaa(query: string): Promise<boolean> {
const nyaaMirrors = ['https://nyaa.si', 'https://nyaa.land'];
for (const mirror of nyaaMirrors) {
try {
const nyaaUrl = `${mirror}/?f=0&c=1_2&q=${encodeURIComponent(query)}`;
console.log(`\nπ Nyaa search: ${nyaaUrl}`);
const res = await axios.get(nyaaUrl, {
timeout: 10000,
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }
});
const $ = cheerio.load(res.data);
let savedCount = 0;
$('table.torrent-list tbody tr').each((_, row) => {
const title = $(row).find('td[colspan="2"] a').last().text().trim();
const magnet = $(row).find('td.text-center a[href^="magnet:?"]').attr('href');
const epMatch = title.match(/(?:ep|episode|e)\s*(\d+)/i) || title.match(/\s(\d{1,3})\s/);
const epNum = epMatch ? parseInt(epMatch[1]) : 1;
if (magnet && title) {
saveToSupabase(query, epNum, 'torrent', magnet);
savedCount++;
}
});
if (savedCount > 0) {
console.log(`β
Nyaa: ${savedCount} torrent links saved via ${mirror}.`);
return true;
}
} catch (e: any) {
console.log(`β Nyaa mirror ${mirror} failed: ${e.message}`);
}
}
return false;
}
async function mineFromAniwave(query: string, episodeStr: string): Promise<boolean> {
const epNum = parseInt(episodeStr) || 1;
console.log(`\nπ Aniwave Puppeteer search for: "${query}" Ep: ${epNum}`);
const browser = await getSharedBrowser();
let success = false;
for (const domain of ANIWAVE_CLUSTER) {
try {
const searchUrls = [
`${domain}/?s=${encodeURIComponent(query)}`,
`${domain}/search?keyword=${encodeURIComponent(query)}`,
`${domain}/filter?keyword=${encodeURIComponent(query)}`
];
let searchPage = await browser.newPage();
let firstResult: string | null = null;
for (const searchUrl of searchUrls) {
console.log(`\nπ Searching: ${searchUrl}`);
try {
await searchPage.goto(searchUrl, { waitUntil: 'networkidle2', timeout: 30000 });
await new Promise(r => setTimeout(r, 2000));
firstResult = await searchPage.evaluate((q: any) => {
const links = Array.from(document.querySelectorAll('.item a.name, .bsx a, .film-name a, .card a, a')) as HTMLAnchorElement[];
const querySlug = q.split(' ')[0].toLowerCase().replace(/[^a-z0-9]/g, '');
const target = links.find(l => {
if (!l.href) return false;
const h = l.href.toLowerCase();
const cleanHref = h.split('?')[0].split('#')[0];
const currentClean = window.location.href.toLowerCase().split('?')[0].split('#')[0];
return (h.includes('/anime/') || h.includes('/watch/') || h.includes('/tv/')) &&
h.includes(querySlug) &&
!h.includes('/search') &&
!h.includes('?s=') &&
!h.includes('?keyword=') &&
cleanHref !== currentClean;
});
return target ? target.href : null;
}, query);
if (firstResult) break;
} catch (e) {
continue;
}
}
await searchPage.close();
if (!firstResult) {
console.log(`β οΈ No results on ${domain}`);
continue;
}
console.log(`π― Found anime on ${domain}: ${firstResult}`);
const epPage = await browser.newPage();
await epPage.goto(firstResult, { waitUntil: 'domcontentloaded', timeout: 30000 });
await epPage.waitForSelector('.episodes a, .eplister ul li a, .ss-list a', { timeout: 10000 }).catch(() => {});
const episodeUrl = await epPage.evaluate((ep: any) => {
const eps = Array.from(document.querySelectorAll('.episodes a, .eplister ul li a, .ss-list a.ep-item, a')) as HTMLAnchorElement[];
const target = eps.find(e => {
const text = e.innerText.trim().toLowerCase();
const href = e.href.toLowerCase();
return (
e.getAttribute('data-num') === ep.toString() ||
e.getAttribute('data-number') === ep.toString() ||
text === ep.toString() ||
text === `ep ${ep}` ||
text === `episode ${ep}` ||
href.endsWith(`-episode-${ep}`) ||
href.endsWith(`-ep-${ep}`) ||
e.querySelector('.epl-num')?.textContent?.trim() === ep.toString()
);
});
return target ? target.href : null;
}, epNum);
if (episodeUrl) {
console.log(`π¬ Go to Episode: ${episodeUrl}`);
await epPage.goto(episodeUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
}
await epPage.waitForSelector('iframe', { timeout: 10000 }).catch(() => {});
const iframeSrc = await epPage.evaluate(() => {
const iframes = Array.from(document.querySelectorAll('iframe')) as HTMLIFrameElement[];
const player = iframes.find(i => i.src && (
i.src.includes('embed') ||
i.src.includes('vid') ||
i.src.includes('player') ||
i.src.includes('stream') ||
i.src.includes('mega') ||
i.src.includes('drive') ||
i.src.includes('php?id=') ||
i.src.includes('php?ep=')
));
return player ? player.src : null;
});
await epPage.close();
if (iframeSrc) {
console.log(`β
Found embed: ${iframeSrc}`);
await saveToSupabase(query, epNum, 'embed', iframeSrc);
success = true;
break;
}
} catch (e: any) {
console.log(`β ${domain} failed: ${e.message}`);
}
}
return success;
}
async function mineFromHianimeDirect(query: string, episodeStr: string): Promise<boolean> {
console.log(`\nπ Starting HiAnime Direct Series Mine for: ${query} (Ep: ${episodeStr || 'All'})`);
const browser = await getSharedBrowser();
let success = false;
const domains = HIANIME_CLUSTER.length > 0 ? HIANIME_CLUSTER : ['https://hianime.to'];
for (const domain of domains) {
const page = await browser.newPage();
try {
let searchUrls = [
`${domain}/search?keyword=${encodeURIComponent(query)}`,
`${domain}/?s=${encodeURIComponent(query)}`
];
let animeLink: string | null = null;
for (const searchUrl of searchUrls) {
console.log(`π Searching: ${searchUrl}`);
try {
await page.goto(searchUrl, { waitUntil: 'networkidle2', timeout: 30000 });
await new Promise(r => setTimeout(r, 2000));
animeLink = await page.evaluate((q: any) => {
const primaryLinks = Array.from(document.querySelectorAll('.flw-item .film-name a, .film-detail .film-name a, .item a.name')) as HTMLAnchorElement[];
const allLinks = Array.from(document.querySelectorAll('a')) as HTMLAnchorElement[];
const linksToSearch = primaryLinks.length > 0 ? primaryLinks : allLinks;
const cleanQuery = q.toLowerCase().trim();
const querySlug = cleanQuery.replace(/[^a-z0-9]+/g, '-');
const queryNoSpace = cleanQuery.replace(/[^a-z0-9]/g, '');
let target = linksToSearch.find(l => {
if (!l.href) return false;
const h = l.href.toLowerCase();
const text = (l.innerText || l.textContent || '').toLowerCase().trim();
const cleanHref = h.split('?')[0].split('#')[0];
const currentClean = window.location.href.toLowerCase().split('?')[0].split('#')[0];
const isMatch = text === cleanQuery || h.includes(`/watch/${querySlug}-`) || h.includes(`/${querySlug}`);
return isMatch && !h.includes('/search') && !h.includes('?keyword=') && cleanHref !== currentClean;
});
if (!target) {
target = linksToSearch.find(l => {
if (!l.href) return false;
const h = l.href.toLowerCase();
return (h.includes(querySlug) || h.replace(/[^a-z0-9]/g, '').includes(queryNoSpace)) && !h.includes('/search') && !h.includes('?keyword=');
});
}
return target ? target.href : null;
}, query);
if (animeLink) break;
} catch (e) {
continue;
}
}
if (!animeLink) {
console.log(`β οΈ No results on ${domain}`);
await page.close();
continue;
}
console.log(`π― Found Anime Link: ${animeLink}`);
const animeId = animeLink.split('-').pop() || '';
let episodesToMine: any[] = [];
try {
const ajaxUrl = `${domain}/ajax/v2/episode/list/${animeId}`;
const epListData = await page.evaluate((url: string) => {
return fetch(url, {
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
}).then(res => res.json());
}, ajaxUrl);
if (epListData && epListData.html) {
const epPage = await browser.newPage();
await epPage.setContent(epListData.html);
const episodes = await epPage.evaluate(() => {
return Array.from(document.querySelectorAll('.detail-en-list .item')).map(el => ({
id: el.getAttribute('data-id'),
num: el.getAttribute('data-number'),
title: el.getAttribute('title')
}));
});
await epPage.close();
episodesToMine = episodes;
}
} catch (e) {
console.log(`β οΈ HiAnime AJAX fetch failed, attempting generic fallback...`);
}
if (episodesToMine.length === 0) {
await page.goto(animeLink, { waitUntil: 'networkidle2', timeout: 30000 });
await new Promise(r => setTimeout(r, 1500));
const parsedEps = await page.evaluate(() => {
const eps = Array.from(document.querySelectorAll('.episodes a, .eplister ul li a, .ss-list a.ep-item, .ss-list a, a')) as HTMLAnchorElement[];
const parsedEpisodes: { num: string, url: string }[] = [];
for (const e of eps) {
const text = e.innerText.trim().toLowerCase();
const href = e.href.toLowerCase();
let epNum = e.getAttribute('data-num') || e.getAttribute('data-number') || e.getAttribute('data-ep');
if (!epNum) {
const match = text.match(/ep(?:isode)?\s*(\d+)/) || href.match(/-ep(?:isode)?-(\d+)/) || href.match(/\/ep-(\d+)/);
if (match) epNum = match[1];
}
if (epNum && e.href && !e.href.includes('/search') && !e.href.includes('?keyword=')) {
parsedEpisodes.push({ num: epNum, url: e.href });
}
}
return Array.from(new Map(parsedEpisodes.map(item => [item.num, item])).values());
});
if (parsedEps.length > 0) {
episodesToMine = parsedEps.sort((a: any, b: any) => parseInt(a.num) - parseInt(b.num));
} else {
const match = animeLink.match(/-ep(?:isode)?-(\d+)/) || animeLink.match(/\/ep-(\d+)/);
const epNum = match ? match[1] : (episodeStr || '1');
episodesToMine.push({ num: epNum, url: animeLink });
}
}
console.log(`π Total Episodes found: ${episodesToMine.length}`);
console.log(`β‘ Deep-Dive Series Mining: Mining ${episodesToMine.length} episodes of "${query}"...`);
for (const ep of episodesToMine) {
if (!ep.num) continue;
try {
console.log(`π Mining Episode ${ep.num}...`);
await page.setRequestInterception(true);
let directUrl: string | null = null;
const requestHandler = (request: any) => {
const url = request.url();
if (url.includes('.m3u8') || (url.includes('source') && url.includes('.mp4'))) {
directUrl = url;
}
request.continue();
};
page.on('request', requestHandler);
const epUrl = ep.url ? ep.url : `${domain}/watch/${animeId}?ep=${ep.id}`;
await page.goto(epUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
// Event-driven fast wait (2.5s instead of 6s static sleep)
await new Promise(r => setTimeout(r, 2500));
const iframeSrc = await page.evaluate(() => {
const iframes = Array.from(document.querySelectorAll('iframe')) as HTMLIFrameElement[];
const player = iframes.find(i => i.src && (
i.src.includes('embed') ||
i.src.includes('vid') ||
i.src.includes('player') ||
i.src.includes('stream') ||
i.src.includes('mega') ||
i.src.includes('drive') ||
i.src.includes('php?id=') ||
i.src.includes('php?ep=')
));
return player ? player.src : null;
});
if (directUrl) {
console.log(`β
SUCCESS: Ep ${ep.num} direct stream -> ${directUrl}`);
await saveToSupabase(query, parseInt(ep.num || ''), 'm3u8', directUrl);
success = true;
}
if (iframeSrc) {
console.log(`β
SUCCESS: Ep ${ep.num} iframe -> ${iframeSrc}`);
await saveToSupabase(query, parseInt(ep.num || ''), 'embed', iframeSrc);
success = true;
}
page.off('request', requestHandler);
await page.setRequestInterception(false);
} catch (epErr: any) {
console.error(`β Error mining Episode ${ep.num}:`, epErr.message);
}
}
await page.close();
if (success) break;
} catch (e: any) {
console.log(`β ${domain} failed: ${e.message}`);
await page.close();
}
}
return success;
}
(async () => {
console.log(`\nπ Ronin API One-Shot Query: "${query}" Server: ${serverStr} Ep: ${episodeStr} ForceSource: ${forceSource}\n`);
// Always mine Nyaa torrents first regardless of source mode
try {
console.log(`\nπ΄ββ οΈ Always-On Nyaa Torrent Extraction for "${query}"...`);
await mineFromNyaa(query);
} catch (e: any) {
console.log(`β οΈ Nyaa torrent pass note: ${e.message}`);
}
if (forceSource && forceSource.toLowerCase() !== 'ronin' && forceSource.toLowerCase() !== 'main server') {
console.log(`\nβ³ Forcing Deep-Dive extraction from source "${forceSource}" for "${query}" (Requested Ep: ${episodeStr || '1'})...`);
const targetEpNum = parseInt(episodeStr) || 1;
try {
if (forceSource.toLowerCase() === 'gogoanime' || forceSource.toLowerCase() === 'gogoanime direct') {
console.log(`\nβ³ Mining from GogoAnime Light...`);
await scrapeGogoanimeLight(query, targetEpNum, GOGO_DOMAINS);
await exitProcess(0);
} else {
const { minedCount } = await mineExtensionAllEpisodes(forceSource, query, targetEpNum, saveToSupabase);
if (minedCount > 0) {
console.log(`\nβ
Deep-Dive extension mining completed successfully for: "${query}" (${minedCount} episodes saved via "${forceSource}")`);
await exitProcess(0);
} else {
console.error(`β Forced extension source "${forceSource}" failed to find streams for: "${query}"`);
await exitProcess(1);
}
}
} catch (err: any) {
console.error(`β Forced source mining crashed:`, err.message);
await exitProcess(1);
}
}
if (serverStr === '2') {
const success = await mineFromAniwave(query, episodeStr);
if (!success) {
console.error(`β Aniwave failed for: "${query}"`);
await exitProcess(1);
}
} else if (serverStr === '3') {
const success = await mineFromHianimeDirect(query, episodeStr);
if (!success) {
console.error(`β HiAnime failed for: "${query}"`);
await exitProcess(1);
}
} else {
const titleVariants = await getSearchVariants(query);
console.log(`\nπ Resolved Title Variants for "${query}":`, titleVariants);
let overallMined = false;
for (const titleVar of titleVariants) {
console.log(`\n=================================================`);
console.log(`π Mining Pass with Title Variant: "${titleVar}"`);
console.log(`=================================================`);
console.log(`\nβ³ Step 1: Running Instant Gogoanime Scraper...`);
const targetEp = parseInt(episodeStr) || 1;
const fastGogoResult = await scrapeGogoanimeLight(titleVar, targetEp, GOGO_DOMAINS);
let gogoSuccess = !!fastGogoResult;
let hianimeDirectSuccess = false;
if (!gogoSuccess) {
console.log(`\nβ³ Trying HiAnime Direct Scraper for "${titleVar}"...`);
hianimeDirectSuccess = await mineFromHianimeDirect(titleVar, episodeStr);
if (!hianimeDirectSuccess) {
console.log(`\nβ οΈ Falling back to GogoAnime Puppeteer for "${titleVar}"...`);
gogoSuccess = await mineFromGogo(titleVar);
}
}
let animepaheSuccess = false;
if (!gogoSuccess && !hianimeDirectSuccess) {
console.log(`\nβ³ GogoAnime & HiAnime failed. Trying Animepahe Direct Scraper for "${titleVar}"...`);
try {
const paheStream = await scrapeAnimepahe(titleVar, targetEp);
if (paheStream) {
animepaheSuccess = true;
console.log(`π Animepahe successfully mined Ep ${targetEp} stream!`);
}
} catch (e: any) {
console.log(`β Animepahe direct failed for "${titleVar}": ${e.message}`);
}
}
let extensionSuccess = false;
if (!hianimeDirectSuccess && !gogoSuccess && !animepaheSuccess) {
console.log(`\nβ³ Step 2: Running Extension Waterfall for "${titleVar}"...`);
for (const extName of EXTENSION_WATERFALL) {
try {
const { minedCount } = await mineExtensionAllEpisodes(extName, titleVar, targetEp, saveToSupabase);
if (minedCount > 0) {
console.log(`π Extension "${extName}" successfully mined ${minedCount} episodes for "${titleVar}"!`);
extensionSuccess = true;
break;
}
} catch (e: any) {
console.log(`β Extension "${extName}" failed for "${titleVar}": ${e.message}`);
}
}
}
console.log(`\nβ³ Step 3: Mining Nyaa, Aniwave & Dub streams in parallel...`);
const isDubQuery = query.toLowerCase().endsWith(' dub');
const [nyaaSuccess, aniwaveSuccess] = await Promise.all([
mineFromNyaa(titleVar),
mineFromAniwave(titleVar, episodeStr),
(!isDubQuery)
? mineExtensionAllEpisodes('allanime', `${titleVar} dub`, targetEp, saveToSupabase).catch(() => ({}))
: Promise.resolve({ minedCount: 0 })
]);
if (hianimeDirectSuccess || gogoSuccess || extensionSuccess || nyaaSuccess || aniwaveSuccess) {
overallMined = true;
console.log(`π Successfully mined streams using title variant: "${titleVar}"!`);
break;
}
}
if (!overallMined) {
console.error(`β All sources failed for: "${query}" across all title variants.`);
await exitProcess(1);
}
}
console.log(`\nβ
Mining completed for: "${query}"`);
await exitProcess(0);
})();