This repository was archived by the owner on May 22, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathaddon.js
More file actions
906 lines (798 loc) · 42.9 KB
/
Copy pathaddon.js
File metadata and controls
906 lines (798 loc) · 42.9 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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//===============
// AMATSU STREMIO ADDON - CORE LOGIC
// (Consistent UI + StremThru Cache + Strict Episode Enforcing + Dynamic Season & Episode Extraction)
// P2P Integration: Direct infoHash handover to Stremio including Tracker-Injection.
// Explicit Resolution Toggles & Fixed Movie Manifest.
//===============
const { addonBuilder } = require("stremio-addon-sdk");
const axios = require("axios");
const { searchAnime, getAnimeMeta, getTrendingAnime, getTopAnime, getAiringAnime, getSeasonalAnime, getJikanMeta, fetchEpisodeDetails, getCurrentSeasonInfo } = require("./lib/anilist");
const { searchNyaaForAnime } = require("./lib/nyaa");
const { checkRD, checkTorbox, getActiveRD, getActiveTorbox } = require("./lib/debrid");
const { extractEpisodeNumber, getBatchRange, isEpisodeMatch, selectBestVideoFile, isSeasonBatch, verifyTitleMatch } = require("./lib/parser");
let BASE_URL = process.env.BASE_URL || "http://127.0.0.1:7002";
BASE_URL = BASE_URL.replace(/\/+$/, "");
const INTERNAL_TB_KEY = process.env.INTERNAL_TORBOX_KEY || "";
const FLARESOLVERR_URL = process.env.FLARESOLVERR_URL || null;
//===============
// GLOBAL CONCURRENCY LIMITER (Anti-Self-DDoS)
// Limits the amount of concurrent outgoing requests to external trackers.
// This prevents IP bans from services like Nyaa when Stremio fires multiple
// search requests simultaneously.
//===============
const MAX_CONCURRENT_SCRAPES = 5;
let activeScrapes = 0;
const scrapeQueue = [];
async function enqueueScrape(queryFn) {
return new Promise((resolve, reject) => {
const task = async () => {
activeScrapes++;
try {
const result = await queryFn();
resolve(result);
} catch (e) {
reject(e);
} finally {
activeScrapes--;
if (scrapeQueue.length > 0) {
const nextTask = scrapeQueue.shift();
nextTask();
}
}
};
if (activeScrapes < MAX_CONCURRENT_SCRAPES) {
task();
} else {
scrapeQueue.push(task);
}
});
}
//===============
// BASE64 ENCODING UTILITIES
// Converts strings to a URL-safe Base64 format to be passed safely
// through Stremio catalog and stream IDs without breaking routing.
//===============
function toBase64Safe(str) {
return Buffer.from(str, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function fromBase64Safe(str) {
try {
return Buffer.from(str.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
} catch (e) {
return "";
}
}
//===============
// CONFIGURATION PARSER
// Extracts and decodes the user's specific settings (API keys, preferences)
// that are embedded within the Stremio manifest URL payload.
//===============
function parseConfig(config) {
let parsed = {};
try {
if (config && config.Amatsu) {
const decoded = Buffer.from(config.Amatsu.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
parsed = JSON.parse(decoded);
} else {
parsed = config || {};
}
} catch (e) {}
return parsed;
}
//===============
// TITLE PREFERENCE APPLIER
// Swaps the default Romaji titles with English ones if the user has
// configured "useEnglishTitles" in their addon settings.
//===============
function applyTitlePreference(metas, userConfig) {
if (!userConfig.useEnglishTitles || !metas) return metas;
return metas.map(m => ({ ...m, name: m.englishName || m.name }));
}
//===============
// SIZE PARSER
// Converts human-readable file sizes (e.g., "1.5 GB") into raw bytes
// to allow mathematically accurate sorting of streams later on.
//===============
function parseSizeToBytes(sizeStr) {
if (!sizeStr || typeof sizeStr !== "string") return 0;
const match = sizeStr.match(/([\d.]+)\s*(GB|MB|KB|GiB|MiB|KiB|B)/i);
if (!match) return 0;
const val = parseFloat(match[1]);
const unit = match[2].toUpperCase();
if (unit.includes("G")) return val * 1024 * 1024 * 1024;
if (unit.includes("M")) return val * 1024 * 1024;
return val * 1024;
}
//===============
// RESOLUTION TAG EXTRACTOR
// Scans the torrent title for common resolution indicators and standardizes
// them into predefined tags for filtering and UI presentation.
//===============
function extractTags(title) {
let res = "SD";
if (/(4320p|8k|FUHD)/i.test(title)) res = "8K";
else if (/(2160p|4k|UHD)/i.test(title)) res = "4K";
else if (/(1440p|2k|QHD)/i.test(title)) res = "2K";
else if (/(1080p|1080|FHD)/i.test(title)) res = "1080p";
else if (/(720p|720|HD)/i.test(title)) res = "720p";
else if (/(480p|480)/i.test(title)) res = "480p";
return { res };
}
//===============
// LANGUAGE MATRIX
// Contains robust Regular Expressions to detect audio and subtitle
// languages from standard anime fan-sub naming conventions.
//===============
const LANG_REGEX = {
"GER": /\b(ger|deu|german|deutsch|de-de)\b|(?:^|[\[\(\-_ ])(de)(?:[\]\)\-_ ]|$)/i,
"FRE": /\b(fre|fra|french|vostfr|vf|fr-fr)\b|(?:^|[\[\(\-_ ])(fr)(?:[\]\)\-_ ]|$)/i,
"ITA": /\b(ita|italian|it-it)\b|(?:^|[\[\(\-_ ])(it)(?:[\]\)\-_ ]|$)/i,
"SPA": /\b(spa|esp|spanish|es-es|castellano)\b|(?:^|[\[\(\-_ ])(es)(?:[\]\)\-_ ]|$)/i,
"LAT": /\b(lat|latino|es-mx|es-419)\b|(?:^|[\[\(\-_ ])(lat)(?:[\]\)\-_ ]|$)/i,
"RUS": /\b(rus|russian|ru-ru)\b|(?:^|[\[\(\-_ ])(ru)(?:[\]\)\-_ ]|$)/i,
"POR": /\b(por|pt-br|portuguese|pt-pt)\b|(?:^|[\[\(\-_ ])(pt)(?:[\]\)\-_ ]|$)/i,
"ARA": /\b(ara|arabic|ar-sa)\b|(?:^|[\[\(\-_ ])(ar)(?:[\]\)\-_ ]|$)/i,
"CHI": /\b(chi|chinese|chs|cht|mandarin|zh-cn|zh-tw)\b|(?:^|[\[\(\-_ ])(zh)(?:[\]\)\-_ ]|$)|(简|繁|中文字幕)/i,
"KOR": /\b(kor|korean|ko-kr)\b|(?:^|[\[\(\-_ ])(ko)(?:[\]\)\-_ ]|$)/i,
"HIN": /\b(hin|hindi|hi-in)\b|(?:^|[\[\(\-_ ])(hi)(?:[\]\)\-_ ]|$)/i,
"POL": /\b(pol|polish|pl-pl)\b|(?:^|[\[\(\-_ ])(pl)(?:[\]\)\-_ ]|$)/i,
"NLD": /\b(nld|dut|dutch|nl-nl)\b|(?:^|[\[\(\-_ ])(nl)(?:[\]\)\-_ ]|$)/i,
"TUR": /\b(tur|turkish|tr-tr)\b|(?:^|[\[\(\-_ ])(tr)(?:[\]\)\-_ ]|$)/i,
"VIE": /\b(vie|vietnamese|vi-vn)\b|(?:^|[\[\(\-_ ])(vi)(?:[\]\)\-_ ]|$)/i,
"IND": /\b(ind|indonesian|id-id)\b|(?:^|[\[\(\-_ ])(id)(?:[\]\)\-_ ]|$)/i,
"ENG": /\b(eng|english|dubbed|subbed|en-us|en-gb)\b|(?:^|[\[\(\-_ ])(en)(?:[\]\)\-_ ]|$)/i,
"JPN": /\b(jpn|japanese|raw|jp-jp)\b|(?:^|[\[\(\-_ ])(jp)(?:[\]\)\-_ ]|$)/i,
"MULTI": /(multi|dual|multi-audio|multi-sub)/i
};
//===============
// LANGUAGE EXTRACTOR
// Checks the title against the user's preferred languages first,
// falling back to multi-audio, English, or Japanese raw status.
//===============
function extractLanguage(title, userLangs = []) {
const lower = title.toLowerCase();
for (let lang of userLangs) {
if (LANG_REGEX[lang] && LANG_REGEX[lang].test(lower)) return lang;
}
if (LANG_REGEX["MULTI"].test(lower)) return "MULTI";
if (LANG_REGEX["ENG"].test(lower)) return "ENG";
if (LANG_REGEX["JPN"].test(lower)) return "JPN";
return "ENG";
}
//===============
// SEARCH QUERY SANITIZER
// Removes special characters, brackets, and excessive whitespace from
// raw titles to formulate a clean query string for external trackers.
//===============
function sanitizeSearchQuery(title) {
if (!title) return "";
return title.replace(/\(.*?\)/g, "")
.replace(/\[.*?\]/g, "")
.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()\[\]"'<>?+|\\・、。「」『』【】[]()〈〉≪≫《》〔〕…—~〜♥♡★☆♪]/g, " ")
.replace(/\s{2,}/g, " ")
.trim();
}
//===============
// STREMIO ADDON MANIFEST
// Defines the capabilities, catalogs, and ID prefixes the addon supports.
//===============
const manifest = {
"id": "org.community.amatsu", "version": "9.6.1", "name": "Amatsu", "logo": BASE_URL + "/amatsu.png",
"description": "The ultimate Nyaa Gateway. Parallel Search for Anime, Live-Action, and more.",
"types": ["anime", "movie", "series"],
"resources": [
"catalog",
{
"name": "meta",
"types": ["anime", "movie", "series"],
"idPrefixes": ["anilist:", "amatsu_raw:"]
},
{
"name": "stream",
"types": ["anime", "movie", "series"],
"idPrefixes": ["anilist:", "nyaa:", "kitsu:", "tt", "amatsu_raw:"]
}
],
"catalogs": [
{ "id": "amatsu_seasonal_series", "type": "anime", "name": "Amatsu Current Season" },
{ "id": "amatsu_airing_series", "type": "anime", "name": "Amatsu Currently Airing" },
{ "id": "amatsu_trending_series", "type": "anime", "name": "Amatsu Trending Series" },
{ "id": "amatsu_top_series", "type": "anime", "name": "Amatsu Top Rated Series" },
{ "id": "amatsu_trending_movie", "type": "movie", "name": "Amatsu Trending Movies" },
{ "id": "amatsu_top_movie", "type": "movie", "name": "Amatsu Top Rated Movies" },
{ "id": "amatsu_search", "type": "anime", "name": "Amatsu Search", "extra": [{ "name": "search", "isRequired": true }] },
{ "id": "amatsu_search", "type": "movie", "name": "Amatsu Search", "extra": [{ "name": "search", "isRequired": true }] },
{ "id": "amatsu_search", "type": "series", "name": "Amatsu Series", "extra": [{ "name": "search", "isRequired": true }] }
],
"config": [{ "key": "Amatsu", "type": "text", "title": "Amatsu Internal Payload" }],
"behaviorHints": { "configurable": true, "configurationRequired": true }
};
const builder = new addonBuilder(manifest);
//===============
// CATALOG HANDLER
// Processes requests for the Stremio discover board (Trending, Top, Airing).
// Also manages the search functionality, querying multiple sources and generating
// a fallback "RAW SEARCH" card if standard metadata APIs fail to find a match.
//===============
builder.defineCatalogHandler(async ({ type, id, extra, config }) => {
try {
const userConfig = parseConfig(config);
if (id === "amatsu_seasonal_series" && userConfig.showSeasonalSeries !== false) {
const results = await getSeasonalAnime("anime");
return { "metas": applyTitlePreference(results.filter(m => m.type === type), userConfig), "cacheMaxAge": 14400 };
}
if (id === "amatsu_airing_series" && userConfig.showAiringSeries !== false) {
const results = await getAiringAnime("anime");
return { "metas": applyTitlePreference(results.filter(m => m.type === type), userConfig), "cacheMaxAge": 14400 };
}
if (id === "amatsu_trending_series" && userConfig.showTrendingSeries !== false) {
const results = await getTrendingAnime("anime");
return { "metas": applyTitlePreference(results.filter(m => m.type === type), userConfig), "cacheMaxAge": 21600 };
}
if (id === "amatsu_top_series" && userConfig.showTopSeries !== false) {
const results = await getTopAnime("anime");
return { "metas": applyTitlePreference(results.filter(m => m.type === type), userConfig), "cacheMaxAge": 86400 };
}
if (id === "amatsu_trending_movie" && userConfig.showTrendingMovies !== false) {
const results = await getTrendingAnime("movie");
return { "metas": applyTitlePreference(results.filter(m => m.type === type), userConfig), "cacheMaxAge": 21600 };
}
if (id === "amatsu_top_movie" && userConfig.showTopMovies !== false) {
const results = await getTopAnime("movie");
return { "metas": applyTitlePreference(results.filter(m => m.type === type), userConfig), "cacheMaxAge": 86400 };
}
if (id === "amatsu_search" && extra.search) {
const nyaaPromise = searchNyaaForAnime(extra.search).catch(() => []);
const timeoutPromise = new Promise(resolve => setTimeout(() => resolve([]), 3500));
const [anilistRes, cinemetaRes, nyaaRes] = await Promise.all([
searchAnime(extra.search).catch(() => []),
axios.get(`https://v3-cinemeta.strem.io/catalog/${type}/top/search=${encodeURIComponent(extra.search)}.json`, { timeout: 4000 }).then(res => res.data.metas || []).catch(() => []),
Promise.race([nyaaPromise, timeoutPromise])
]);
const results = [];
const seenIds = new Set();
const mappedAnilist = applyTitlePreference(anilistRes.filter(m => m.type === type), userConfig);
mappedAnilist.forEach(m => {
results.push(m);
seenIds.add(m.id);
});
cinemetaRes.forEach(m => {
if (!seenIds.has(m.id)) {
results.push(m);
seenIds.add(m.id);
}
});
// Fallback generation for obscure searches
if (results.length < 2 && nyaaRes.length > 0) {
results.push({
"id": `amatsu_raw:${type}:${toBase64Safe(extra.search)}`,
"type": type,
"name": extra.search + " (RAW SEARCH)",
"poster": `https://dummyimage.com/600x900/1a1a1a/42a5f5.png?text=${encodeURIComponent(extra.search)}\nRaw+Search`,
"background": `https://dummyimage.com/1920x1080/1a1a1a/42a5f5.png?text=${encodeURIComponent(extra.search)}`,
"description": `Found ${nyaaRes.length} raw torrents. Use this if no official metadata matches.`
});
}
return { "metas": results, "cacheMaxAge": 86400 };
}
return { "metas": [] };
} catch (e) { return { "metas": [] }; }
});
//===============
// META HANDLER
// Provides the detailed view for a single item (description, episodes, poster).
// Capable of dynamically generating fake metadata for "RAW SEARCH" items so
// the user can still select an episode and trigger the stream handler.
//===============
builder.defineMetaHandler(async ({ type, id, config }) => {
try {
const userConfig = parseConfig(config);
if (id.startsWith("amatsu_raw:")) {
const parts = id.split(":");
const mType = parts[1];
const query = fromBase64Safe(parts[2]);
const rawMeta = {
"id": id, "type": mType, "name": query + " (Raw Search)",
"poster": `https://dummyimage.com/600x900/1a1a1a/42a5f5.png?text=${encodeURIComponent(query)}\nRaw+Search`,
"background": `https://dummyimage.com/1920x1080/1a1a1a/42a5f5.png?text=${encodeURIComponent(query)}`,
"description": `Dynamically generated metadata for "${query}".`,
};
if (mType === "series" || mType === "anime") {
rawMeta.videos = [];
for (let s = 1; s <= 10; s++) {
for (let e = 1; e <= 100; e++) {
rawMeta.videos.push({
"id": `${id}-${e}`,
"title": `Episode ${e}`,
"season": s,
"episode": e
});
}
}
} else if (mType === "movie") {
rawMeta.videos = [{
"id": id,
"title": query || "Movie",
"released": new Date().toISOString()
}];
rawMeta.behaviorHints = { "defaultVideoId": id };
}
return { "meta": rawMeta, "cacheMaxAge": 86400 };
}
if (!id.startsWith("anilist:")) return { "meta": null };
const aniListId = id.split(":")[1];
if (!aniListId || isNaN(aniListId)) return { "meta": null };
const rawMeta = await getAnimeMeta(aniListId);
if (!rawMeta) return { "meta": null };
const meta = { ...rawMeta };
if (userConfig.useEnglishTitles && meta.englishName) {
meta.name = meta.englishName;
}
meta.id = id;
if (meta.type === "anime" || meta.type === "series") {
meta.type = "anime";
const jikanEps = meta.idMal ? await fetchEpisodeDetails(meta.idMal).catch(() => ({})) : {};
const epMeta = meta.epMeta || {};
const defaultThumb = meta.background || meta.poster || "https://dummyimage.com/600x337/1a1a1a/42a5f5.png?text=AMATSU+EPISODE";
meta.videos = Array.from({ "length": meta.episodes || 12 }, (_, i) => {
const epNum = i + 1;
const jData = jikanEps[epNum] || {};
const epData = epMeta[epNum] || {};
return { "id": `${id}-${epNum}`, "title": jData.title || epData.title || `Episode ${epNum}`, "season": 1, "episode": epNum, "thumbnail": epData.thumbnail || defaultThumb };
});
} else if (meta.type === "movie") {
meta.videos = [{
"id": id,
"title": meta.name || "Movie",
"released": meta.released || new Date().toISOString(),
"thumbnail": meta.poster
}];
meta.behaviorHints = { "defaultVideoId": id };
}
return { "meta": meta, "cacheMaxAge": 604800 };
} catch (e) { return { "meta": null }; }
});
//===============
// STREAM HANDLER (CORE ENGINE)
// Responsible for calculating search strings, querying trackers,
// filtering out wrong seasons/episodes, cross-checking cache status with Debrid,
// and formatting the final JSON returned to Stremio.
//===============
builder.defineStreamHandler(async ({ type, id, config }) => {
try {
console.log(`\n[AMATSU FORENSICS] ===== NEUE SUCHE =====`);
console.log(`[AMATSU FORENSICS] ID: ${id} | Type: ${type}`);
if (!id.startsWith("anilist:") && !id.startsWith("nyaa:") && !id.startsWith("kitsu:") && !id.startsWith("tt") && !id.startsWith("amatsu_raw:")) return { "streams": [] };
const userConfig = parseConfig(config);
//===============
// VALIDATION: Check if a valid playback method is available
//===============
if (!userConfig.rdKey && !userConfig.tbKey && !userConfig.enableP2P) {
console.log(`[PIPELINE] 🛑 ABBRUCH: Weder Debrid-Dienste noch P2P aktiviert.`);
return { "streams": [] };
}
let aniListId = null;
let requestedEp = 1;
let expectedSeason = 1;
let searchTitleFallback = null;
let isRawSearch = false;
const parts = id.split(":");
// ID Unpacking to discover the requested episode and expected season.
if (id.startsWith("kitsu:")) {
try {
const kitsuId = parts[1];
const kRes = await axios.get(`https://kitsu.io/api/edge/anime/${kitsuId}`, { timeout: 4000 });
searchTitleFallback = kRes.data?.data?.attributes?.canonicalTitle || kRes.data?.data?.attributes?.titles?.en_jp;
requestedEp = parseInt(parts[2], 10) || 1;
console.log(`[AMATSU FORENSICS] Kitsu Match erfolgreich: ${searchTitleFallback}`);
} catch (e) { }
} else if (id.startsWith("amatsu_raw:")) {
const mType = parts[1];
let rawPayload = parts[2];
if (rawPayload && rawPayload.includes("-")) {
let subParts = rawPayload.split("-");
searchTitleFallback = fromBase64Safe(subParts[0]);
requestedEp = parseInt(subParts[1], 10) || 1;
} else {
searchTitleFallback = fromBase64Safe(rawPayload);
requestedEp = 1;
}
expectedSeason = 1;
isRawSearch = true;
} else if (id.startsWith("anilist:")) {
let payload = parts[1];
if (payload.includes("-")) {
let subParts = payload.split("-");
aniListId = subParts[0];
requestedEp = parseInt(subParts[1], 10) || 1;
} else {
aniListId = payload;
requestedEp = parts.length > 2 ? parseInt(parts[parts.length - 1], 10) : 1;
}
} else if (id.startsWith("tt")) {
if (parts.length > 2) {
expectedSeason = parseInt(parts[1], 10) || 1;
requestedEp = parseInt(parts[2], 10) || 1;
} else { requestedEp = 1; }
}
const metaTasks = [];
if (id.startsWith("tt")) {
metaTasks.push((async () => {
const imdbId = parts[0];
let name = "";
try {
let res = await axios.get(`https://v3-cinemeta.strem.io/meta/${type}/${imdbId}.json`, { timeout: 4000 });
name = res.data?.meta?.name;
} catch(e) {}
if (!name) {
const otherType = type === "movie" ? "series" : "movie";
try {
let res2 = await axios.get(`https://v3-cinemeta.strem.io/meta/${otherType}/${imdbId}.json`, { timeout: 4000 });
name = res2.data?.meta?.name;
} catch(e) {}
}
return { source: "cinemeta", name: name || "" };
})());
}
if (aniListId) {
metaTasks.push(getAnimeMeta(aniListId).then(meta => ({ "source": "anilist", "meta": meta })).catch(() => null));
}
const metaResults = await Promise.all(metaTasks);
let freshMeta = null;
metaResults.forEach(r => {
if (!r) return;
if (r.source === "cinemeta") searchTitleFallback = r.name;
if (r.source === "anilist") freshMeta = r.meta;
});
// Intercepting requests coming from Cinemeta (like IMDB tt tags) and translating them to Anilist
if (id.startsWith("tt") && searchTitleFallback) {
try {
const searchResults = await searchAnime(searchTitleFallback);
if (searchResults && searchResults.length > 0) {
const matchedId = searchResults[0].id.split(":")[1];
const extraMeta = await getAnimeMeta(matchedId);
if (extraMeta) {
const anilistName = extraMeta.name.toLowerCase();
const cinemetaName = searchTitleFallback.toLowerCase();
if (anilistName.includes(cinemetaName) || cinemetaName.includes(anilistName)) {
freshMeta = extraMeta;
}
}
}
} catch (e) {}
} else if (!freshMeta && searchTitleFallback && !isRawSearch) {
try {
const searchResults = await searchAnime(searchTitleFallback);
if (searchResults && searchResults.length > 0) {
const matchedId = searchResults[0].id.split(":")[1];
freshMeta = await getAnimeMeta(matchedId);
}
} catch (e) {}
}
if (!freshMeta && !searchTitleFallback) {
console.log(`[AMATSU FORENSICS] Abbruch: Keine Metadaten oder Fallback-Titel gefunden.`);
return { "streams": [] };
}
// Contextual season extraction from standard title conventions.
const extractSeason = (t) => {
const nthMatch = t.match(/\b(\d+)(?:st|nd|rd|th)\s+(?:Season|Part|Cour)\b/i);
if (nthMatch) return parseInt(nthMatch[1], 10);
const m = t.match(/\b(?:S|Season|Part|Cour|Dai|Di)\s*0*(\d+)\b/i);
if (m) return parseInt(m[1], 10);
const wordMatch = t.match(/\b(second|third|fourth|fifth|sixth|ii|iii|iv|v|vi)\s+(season|part|cour)\b/i);
if (wordMatch) {
const val = wordMatch[1].toLowerCase();
if (val === "second" || val === "ii") return 2;
if (val === "third" || val === "iii") return 3;
if (val === "fourth" || val === "iv") return 4;
if (val === "fifth" || val === "v") return 5;
if (val === "sixth" || val === "vi") return 6;
}
return null;
};
if (!id.startsWith("tt") && !isRawSearch) {
let detected = null;
const sources = [searchTitleFallback, freshMeta ? freshMeta.name : "", freshMeta ? freshMeta.altName : ""];
for (let s of sources) {
if (s) {
let d = extractSeason(s);
if (d && d > 1) {
detected = d;
break;
}
}
}
if (detected) expectedSeason = detected;
}
const isMovie = type === "movie" || (freshMeta && freshMeta.format === "MOVIE");
const titleList = [];
if (searchTitleFallback) titleList.push(sanitizeSearchQuery(searchTitleFallback));
if (freshMeta) {
if (freshMeta.name) titleList.push(sanitizeSearchQuery(freshMeta.name));
if (freshMeta.altName) titleList.push(sanitizeSearchQuery(freshMeta.altName));
}
const uniqueTitles = [...new Set(titleList.filter(Boolean))];
const searchQueries = new Set();
const baseTitles = new Set();
uniqueTitles.forEach(t => {
const stripped = t.replace(/\b(?:\d+(?:st|nd|rd|th)\s+(?:Season|Part|Cour)|Season\s*\d+|S\d+|Part\s*\d+|Cour\s*\d+|Episode\s*\d+|Ep\s*\d+)\b/ig, "")
.replace(/第\s*\d+\s*(?:季|期|기|話|话|集)/g, "")
.replace(/\s{2,}/g, " ").trim();
if (stripped.length > 4) baseTitles.add(stripped);
});
const validSearchTitles = Array.from(baseTitles);
const primaryTitleToSplit = searchTitleFallback || (freshMeta ? freshMeta.name : null);
if (primaryTitleToSplit) {
const words = sanitizeSearchQuery(primaryTitleToSplit).split(/\s+/);
const w2 = words.slice(0, 2).join(" ");
const w3 = words.slice(0, 3).join(" ");
const w4 = words.slice(0, 4).join(" ");
if (words.length >= 2 && w2.length > 5) searchQueries.add(w2);
if (words.length >= 3 && w3.length > 5) searchQueries.add(w3);
if (words.length >= 4 && w4.length > 5) searchQueries.add(w4);
}
validSearchTitles.forEach(t => searchQueries.add(t));
const sortedQueries = Array.from(searchQueries).sort((a, b) => b.length - a.length);
//===============
// CASCADE SEARCH & FAST FAIL LOGIC
// If an ISP block or Tracker block is detected (taking > 11s), the loop
// aborts immediately to avoid triggering Stremio's hard 15-second timeout,
// ensuring any results gathered up to that point are delivered.
//===============
const fetchAllPossibleTorrents = async () => {
const epStr = requestedEp < 10 ? `0${requestedEp}` : `${requestedEp}`;
const sStr = expectedSeason < 10 ? `0${expectedSeason}` : `${expectedSeason}`;
const deduplicated = new Map();
let isTrackerBlocked = false;
const runTask = async (queryFn) => {
const startTime = Date.now();
try {
const res = await queryFn();
if (res && res.length > 0) {
res.forEach(t => deduplicated.set(t.hash.toLowerCase(), t));
}
} catch (e) {}
const duration = Date.now() - startTime;
// Fast-Fail Detection
if (duration > 11000 && deduplicated.size === 0) {
isTrackerBlocked = true;
console.log(`[AMATSU FAST FAIL] Tracker-Block detektiert. Dauer: ${duration}ms. Breche Kaskade ab.`);
}
};
let isFirstTitle = true;
for (const title of sortedQueries) {
// Respecting the isTrackerBlocked flag
if (deduplicated.size >= 30 || isTrackerBlocked) break;
if (isMovie) {
await runTask(() => enqueueScrape(() => searchNyaaForAnime(`${title}`)));
} else {
await runTask(() => enqueueScrape(() => searchNyaaForAnime(`${title} ${epStr}`)));
if (isTrackerBlocked) break;
if (deduplicated.size < 10) {
await runTask(() => enqueueScrape(() => searchNyaaForAnime(`${title} S${sStr}E${epStr}`)));
}
if (isTrackerBlocked) break;
if (isFirstTitle) {
await runTask(() => enqueueScrape(() => searchNyaaForAnime(`${title} Batch`)));
if (isTrackerBlocked) break;
if (expectedSeason > 1) {
await runTask(() => enqueueScrape(() => searchNyaaForAnime(`${title} S${sStr}`)));
}
}
if (isTrackerBlocked) break;
if (deduplicated.size === 0) {
await runTask(() => enqueueScrape(() => searchNyaaForAnime(`${title}`)));
}
}
isFirstTitle = false;
}
return { torrentsArr: Array.from(deduplicated.values()) };
};
const searchResult = await fetchAllPossibleTorrents();
let torrents = searchResult.torrentsArr;
//===============
// EXPLICIT RESOLUTION & CLEANUP FILTER
// Discards OSTs, manga, irrelevant filetypes, and non-matching resolutions.
// Also drops oversized batches that likely represent multi-season bundles.
//===============
let filterDropCount = 0;
const allowedResolutions = Array.isArray(userConfig.resolutions) && userConfig.resolutions.length > 0
? userConfig.resolutions
: ["8K", "4K", "2K", "1080p", "720p", "480p", "SD"];
torrents = torrents.filter(t => {
if (!isRawSearch && /\b(?:Soundtrack|OST|MP3|CD|Manga|Light Novel|LN|Artbook|Doujinshi|同人誌|同人CG集|Pictures|Images|Novel|Cosplay)\b/i.test(t.title)) {
filterDropCount++; return false;
}
const { res } = extractTags(t.title);
if (!allowedResolutions.includes(res)) {
filterDropCount++; return false;
}
if (isRawSearch) return true;
const isValid = verifyTitleMatch(t.title, validSearchTitles);
if (!isValid) { filterDropCount++; return false; }
const bytes = parseSizeToBytes(t.size);
const isBatch = isSeasonBatch(t.title, expectedSeason);
if (!isMovie && !isBatch && bytes > 20.0 * 1024 * 1024 * 1024) {
filterDropCount++; return false;
}
return true;
});
if (!torrents.length) return { "streams": [], "cacheMaxAge": 60 };
const hashes = torrents.map(t => t.hash.toLowerCase());
const [rdC, tbC, rdA, tbA] = await Promise.all([
userConfig.rdKey ? checkRD(hashes, userConfig.rdKey).catch(() => ({})) : Promise.resolve({}),
(userConfig.tbKey || INTERNAL_TB_KEY) ? checkTorbox(hashes, userConfig.tbKey || INTERNAL_TB_KEY).catch(() => ({})) : Promise.resolve({}),
userConfig.rdKey ? getActiveRD(userConfig.rdKey).catch(() => ({})) : Promise.resolve({}),
userConfig.tbKey ? getActiveTorbox(userConfig.tbKey).catch(() => ({})) : Promise.resolve({})
]);
const flags = { "GER": "🇩🇪", "ITA": "🇮🇹", "FRE": "🇫🇷", "SPA": "🇪🇸", "LAT": "💃🏻", "RUS": "🇷🇺", "POR": "🇵🇹", "ARA": "🇸🇦", "CHI": "🇨🇳", "KOR": "🇰🇷", "HIN": "🇮🇳", "POL": "🇵🇱", "NLD": "🇳🇱", "TUR": "🇹🇷", "VIE": "🇻🇳", "IND": "🇮🇩", "JPN": "🇯🇵", "ENG": "🇬🇧", "MULTI": "🌍" };
const userLangs = Array.isArray(userConfig.language) ? userConfig.language : [userConfig.language || "ENG"];
const streams = [];
let epDropCount = 0;
// Iterates through valid torrents to format final stream objects
torrents.forEach(t => {
const hashLow = t.hash.toLowerCase();
const { res } = extractTags(t.title);
const bytes = parseSizeToBytes(t.size);
const streamLang = extractLanguage(t.title, userLangs);
const flag = flags[streamLang] || "🇬🇧";
const seeders = parseInt(t.seeders, 10) || 0;
let isValidMatch = false;
let isBatch = false;
if (isMovie || isRawSearch) {
isValidMatch = true;
} else {
isBatch = isSeasonBatch(t.title, expectedSeason);
isValidMatch = isBatch || isEpisodeMatch(t.title, requestedEp, expectedSeason);
}
if (!isValidMatch) {
epDropCount++;
return;
}
const batchStr = isBatch ? " | 📦 Batch" : "";
//===============
// P2P STREAM GENERATION
// Attaches active trackers enabling direct torrent streaming via Stremio.
//===============
if (userConfig.enableP2P) {
const p2pName = `AMATSU [📡 P2P]\n🎥 ${res}`;
const p2pDesc = `${flag} Nyaa | 📡 P2P${batchStr}\n📄 ${t.title}\n💾 ${t.size} | 👥 ${seeders} Seeds`;
streams.push({
"name": p2pName,
"description": p2pDesc,
"infoHash": t.hash,
"sources": [
"tracker:http://nyaa.tracker.wf:7777/announce",
"tracker:udp://open.stealth.si:80/announce",
"tracker:udp://tracker.opentrackr.org:1337/announce",
"tracker:udp://exodus.desync.com:6969/announce",
"dht:" + t.hash
],
"behaviorHints": { "bingeGroup": "amatsu_p2p_" + t.hash },
"_bytes": bytes, "_lang": streamLang, "_isCached": false, "_res": res, "_prog": 0, "_seeders": seeders, "_isBatch": isBatch
});
}
//===============
// REAL-DEBRID STREAM GENERATION
// Determines cache status, attaches download progress, and links sub-files.
//===============
if (userConfig.rdKey) {
const filesRD = rdC[hashLow];
const prog = rdA[hashLow];
const tbFiles = tbC[hashLow];
let matchedFile = filesRD ? selectBestVideoFile(filesRD, requestedEp, expectedSeason, isMovie) : null;
const isStremThruCached = filesRD && filesRD.length > 0;
const isRadarCached = tbFiles && tbFiles.length > 0;
const isRDCached = isStremThruCached || isRadarCached;
const isDownloading = prog !== undefined && prog < 100;
if (isStremThruCached && !matchedFile && !isMovie) {
epDropCount++;
} else {
let uiName = `AMATSU [☁️ RD]`;
let streamStatus = "☁️ Download";
if (isStremThruCached) {
uiName = `AMATSU [⚡ RD+]`; streamStatus = "⚡ Cached (StremThru)";
} else if (isRadarCached) {
uiName = `AMATSU [⚡ RD+]`; streamStatus = "⚡ Cached (Radar)";
} else if (isDownloading) {
uiName = `AMATSU [⏳ ${prog}% RD]`; streamStatus = `⏳ ${prog}% Downloading`;
}
const streamDescLine1 = `${flag} Nyaa | ${streamStatus}${batchStr}`;
const streamDescLine2 = `📄 ${t.title}`;
const streamDescLine3 = `💾 ${t.size} | 👥 ${seeders} Seeds`;
const streamPayload = {
"name": uiName + `\n🎥 ${res}`,
"description": streamDescLine1 + "\n" + streamDescLine2 + "\n" + streamDescLine3,
"url": BASE_URL + "/resolve/realdebrid/" + userConfig.rdKey + "/" + t.hash + "/" + requestedEp,
"behaviorHints": { "bingeGroup": "amatsu_rd_" + t.hash, "filename": matchedFile ? matchedFile.name : undefined },
"_bytes": bytes, "_lang": streamLang, "_isCached": isRDCached, "_res": res, "_prog": prog || 0, "_seeders": seeders, "_isBatch": isBatch
};
let subtitles = [];
if (isStremThruCached && filesRD) {
const subFiles = filesRD.filter(f => /\.(srt|vtt|ass|ssa)$/i.test(f.name || f.path || ""));
subFiles.forEach(sub => {
subtitles.push({ id: String(sub.id), url: `${BASE_URL}/sub/realdebrid/${userConfig.rdKey}/${t.hash}/${sub.id}?filename=${encodeURIComponent(sub.name || sub.path || "sub.srt")}`, lang: extractLanguage(sub.name || sub.path || "", userLangs) || "ENG" });
});
}
if (subtitles.length > 0) streamPayload.subtitles = subtitles;
if (!userConfig.hideUncached || isRDCached) streams.push(streamPayload);
}
}
//===============
// TORBOX STREAM GENERATION
// Determines cache status, attaches download progress, and links sub-files.
//===============
if (userConfig.tbKey) {
const files = tbC[hashLow];
const prog = tbA[hashLow];
let matchedFile = files ? selectBestVideoFile(files, requestedEp, expectedSeason, isMovie) : null;
const isCached = files && files.length > 0;
const isDownloading = prog !== undefined && prog < 100;
if (isCached && !matchedFile && !isMovie) {
} else {
let uiName = `AMATSU [☁️ TB]`;
let streamStatus = "☁️ Download";
if (isCached) {
uiName = `AMATSU [⚡ TB]`; streamStatus = "⚡ Cached";
} else if (isDownloading) {
uiName = `AMATSU [⏳ ${prog}% TB]`; streamStatus = `⏳ ${prog}% Downloading`;
}
const streamDescLine1 = `${flag} Nyaa | ${streamStatus}${batchStr}`;
const streamDescLine2 = `📄 ${t.title}`;
const streamDescLine3 = `💾 ${t.size} | 👥 ${seeders} Seeds`;
const streamPayload = {
"name": uiName + `\n🎥 ${res}`,
"description": streamDescLine1 + "\n" + streamDescLine2 + "\n" + streamDescLine3,
"url": BASE_URL + "/resolve/torbox/" + userConfig.tbKey + "/" + t.hash + "/" + requestedEp,
"behaviorHints": { "bingeGroup": "amatsu_tb_" + t.hash, "filename": matchedFile ? matchedFile.name : undefined },
"_bytes": bytes, "_lang": streamLang, "_isCached": isCached, "_res": res, "_prog": prog || 0, "_seeders": seeders, "_isBatch": isBatch
};
let subtitles = [];
if (isCached && files) {
const subFiles = files.filter(f => /\.(srt|vtt|ass|ssa)$/i.test(f.name || f.path || ""));
subFiles.forEach(sub => {
subtitles.push({ id: String(sub.id), url: `${BASE_URL}/sub/torbox/${userConfig.tbKey}/${t.hash}/${sub.id}?filename=${encodeURIComponent(sub.name || sub.path || "sub.srt")}`, lang: extractLanguage(sub.name || sub.path || "", userLangs) || "ENG" });
});
}
if (subtitles.length > 0) streamPayload.subtitles = subtitles;
if (!userConfig.hideUncached || isCached) streams.push(streamPayload);
}
}
});
console.log(`[AMATSU FORENSICS] Episoden-Filter hat ${epDropCount} nicht-passende Einträge gelöscht.`);
console.log(`[AMATSU FORENSICS] Finale Streams an Stremio gesendet: ${streams.length}\n`);
//===============
// 3-PHASE SORTER (SCORING)
// Re-orders the final stream list logically based on:
// Language Priority -> Resolution Preference -> Batch Quality -> Seeders/Size
//===============
return {
"streams": streams.sort((a, b) => {
if (a._prog > 0 && b._prog === 0) return -1;
if (b._prog > 0 && a._prog === 0) return 1;
if (a._isCached !== b._isCached) return b._isCached ? 1 : -1;
const getLangScore = (l) => {
if (userLangs.includes(l)) return 200 - userLangs.indexOf(l);
if (l === "MULTI") return 150;
return 0;
};
const langScoreA = getLangScore(a._lang);
const langScoreB = getLangScore(b._lang);
if (langScoreA !== langScoreB) return langScoreB - langScoreA;
const resMap = { "8K": 8, "4K": 4, "2K": 2, "1080p": 1, "720p": 0.5, "480p": 0.25, "SD": 0 };
const resScoreA = resMap[a._res] || 0;
const resScoreB = resMap[b._res] || 0;
if (resScoreA !== resScoreB) return resScoreB - resScoreA;
const aBatch = a._isBatch && (a._seeders > 0 || a._isCached) ? 1 : 0;
const bBatch = b._isBatch && (b._seeders > 0 || b._isCached) ? 1 : 0;
if (aBatch !== bBatch) return bBatch - aBatch;
if (!a._isCached && !b._isCached) {
if (a._seeders !== b._seeders) return b._seeders - a._seeders;
}
return b._bytes - a._bytes;
}),
"cacheMaxAge": 3600
};
} catch (err) { return { "streams": [] }; }
});
module.exports = { "addonInterface": builder.getInterface(), manifest, parseConfig };