-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathaddon.js
More file actions
2191 lines (1910 loc) ยท 102 KB
/
addon.js
File metadata and controls
2191 lines (1910 loc) ยท 102 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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ================================================================================
// Nuvio Streams Addon for Stremio
// ================================================================================
//
// GOOGLE ANALYTICS SETUP:
// 1. Go to https://analytics.google.com/ and create a new GA4 property
// 2. Get your Measurement ID (format: G-XXXXXXXXXX)
// 3. Replace 'G-XXXXXXXXXX' in views/index.html with your actual Measurement ID
// 4. The addon will automatically track:
// - Addon installations (install_addon_clicked)
// - Manifest copies (copy_manifest_clicked)
// - Provider configurations (apply_providers_clicked)
// - Cookie configurations (set_cookie_clicked)
// - Tutorial access (cookie_tutorial_opened)
// - Stream requests (will be added to server-side logging)
//
// ================================================================================
const { addonBuilder } = require('stremio-addon-sdk');
require('dotenv').config(); // Ensure environment variables are loaded
const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto'); // For hashing cookies
const Redis = require('ioredis');
// Add Redis client if enabled
const USE_REDIS_CACHE = process.env.USE_REDIS_CACHE === 'true';
let redis = null;
let redisKeepAliveInterval = null; // Variable to manage the keep-alive interval
if (USE_REDIS_CACHE) {
try {
console.log(`[Redis Cache] Initializing Redis in addon.js. REDIS_URL from env: ${process.env.REDIS_URL ? 'exists and has value' : 'MISSING or empty'}`);
if (!process.env.REDIS_URL) {
throw new Error("REDIS_URL environment variable is not set or is empty.");
}
// Check if this is a local Redis instance or remote
const isLocal = process.env.REDIS_URL.includes('localhost') || process.env.REDIS_URL.includes('127.0.0.1');
redis = new Redis(process.env.REDIS_URL, {
maxRetriesPerRequest: 5,
retryStrategy(times) {
const delay = Math.min(times * 500, 5000);
// Added verbose logging for each retry attempt
console.warn(`[Redis Cache] Retry strategy activated. Attempt #${times}, will retry in ${delay}ms`);
return delay;
},
reconnectOnError: function (err) {
const targetError = 'READONLY';
const shouldReconnect = err.message.includes(targetError);
// Added detailed logging for reconnectOnError decisions
console.warn(`[Redis Cache] reconnectOnError invoked due to error: "${err.message}". Decided to reconnect: ${shouldReconnect}`);
return shouldReconnect;
},
// TLS is optional - only use if explicitly specified with rediss:// protocol
tls: process.env.REDIS_URL.startsWith('rediss://') ? {} : undefined,
enableOfflineQueue: true,
enableReadyCheck: true,
autoResubscribe: true,
autoResendUnfulfilledCommands: true,
lazyConnect: false
});
redis.on('error', (err) => {
console.error(`[Redis Cache] Connection error: ${err.message}`);
// --- BEGIN: Clear Keep-Alive on Error ---
if (redisKeepAliveInterval) {
clearInterval(redisKeepAliveInterval);
redisKeepAliveInterval = null;
}
// --- END: Clear Keep-Alive on Error ---
});
redis.on('connect', () => {
console.log('[Redis Cache] Successfully connected to Upstash Redis');
// --- BEGIN: Redis Keep-Alive ---
if (redisKeepAliveInterval) {
clearInterval(redisKeepAliveInterval);
}
redisKeepAliveInterval = setInterval(() => {
if (redis && redis.status === 'ready') {
redis.ping((err) => {
if (err) {
console.error('[Redis Cache Keep-Alive] Ping failed:', err.message);
}
});
}
}, 4 * 60 * 1000); // 4 minutes
// --- END: Redis Keep-Alive ---
});
// --- BEGIN: Additional Redis connection lifecycle logging ---
redis.on('reconnecting', (delay) => {
console.warn(`[Redis Cache] Reconnecting... next attempt in ${delay}ms (current status: ${redis.status})`);
});
redis.on('close', () => {
console.warn('[Redis Cache] Connection closed.');
});
redis.on('end', () => {
console.error('[Redis Cache] Connection ended. No further reconnection attempts will be made.');
});
redis.on('ready', () => {
console.log('[Redis Cache] Connection is ready and commands can now be processed.');
});
// --- END: Additional Redis connection lifecycle logging ---
console.log('[Redis Cache] Upstash Redis client initialized');
} catch (err) {
console.error(`[Redis Cache] Failed to initialize Redis: ${err.message}`);
console.log('[Redis Cache] Will use file-based cache as fallback');
}
}
// (Removed) Cuevana, HollyMovieHD, Xprime provider flags
// NEW: Read environment variable for VidZee
const ENABLE_VIDZEE_PROVIDER = process.env.ENABLE_VIDZEE_PROVIDER !== 'false'; // Defaults to true
console.log(`[addon.js] VidZee provider fetching enabled: ${ENABLE_VIDZEE_PROVIDER}`);
// NEW: Read environment variable for MP4Hydra
const ENABLE_MP4HYDRA_PROVIDER = process.env.ENABLE_MP4HYDRA_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] MP4Hydra provider fetching enabled: ${ENABLE_MP4HYDRA_PROVIDER}`);
// (Removed) HiAnime provider flag
// NEW: Read environment variable for UHDMovies
const ENABLE_UHDMOVIES_PROVIDER = process.env.ENABLE_UHDMOVIES_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] UHDMovies provider fetching enabled: ${ENABLE_UHDMOVIES_PROVIDER}`);
// (Removed) AnimePahe provider flag
// NEW: Read environment variable for MoviesMod
const ENABLE_MOVIESMOD_PROVIDER = process.env.ENABLE_MOVIESMOD_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] MoviesMod provider fetching enabled: ${ENABLE_MOVIESMOD_PROVIDER}`);
// NEW: Read environment variable for TopMovies
const ENABLE_TOPMOVIES_PROVIDER = process.env.ENABLE_TOPMOVIES_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] TopMovies provider fetching enabled: ${ENABLE_TOPMOVIES_PROVIDER}`);
// NEW: Read environment variable for SoaperTV
const ENABLE_SOAPERTV_PROVIDER = process.env.ENABLE_SOAPERTV_PROVIDER !== 'false'; // Defaults to true
console.log(`[addon.js] SoaperTV provider fetching enabled: ${ENABLE_SOAPERTV_PROVIDER}`);
// NEW: Read environment variable for MoviesDrive
const ENABLE_MOVIESDRIVE_PROVIDER = process.env.ENABLE_MOVIESDRIVE_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] MoviesDrive provider fetching enabled: ${ENABLE_MOVIESDRIVE_PROVIDER}`);
// NEW: Read environment variable for 4KHDHub
const ENABLE_4KHDHUB_PROVIDER = process.env.ENABLE_4KHDHUB_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] 4KHDHub provider fetching enabled: ${ENABLE_4KHDHUB_PROVIDER}`);
// NEW: Read environment variable for HDHub4u
const ENABLE_HDHUB4U_PROVIDER = process.env.ENABLE_HDHUB4U_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] HDHub4u provider fetching enabled: ${ENABLE_HDHUB4U_PROVIDER}`);
// NEW: Read environment variable for Vixsrc
const ENABLE_VIXSRC_PROVIDER = process.env.ENABLE_VIXSRC_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] Vixsrc provider fetching enabled: ${ENABLE_VIXSRC_PROVIDER}`);
// NEW: Read environment variable for MovieBox
const ENABLE_MOVIEBOX_PROVIDER = process.env.ENABLE_MOVIEBOX_PROVIDER !== 'false'; // Defaults to true if not set or not 'false'
console.log(`[addon.js] MovieBox provider fetching enabled: ${ENABLE_MOVIEBOX_PROVIDER}`);
// External provider service configuration
const USE_EXTERNAL_PROVIDERS = process.env.USE_EXTERNAL_PROVIDERS === 'true';
const EXTERNAL_UHDMOVIES_URL = USE_EXTERNAL_PROVIDERS ? process.env.EXTERNAL_UHDMOVIES_URL : null;
const EXTERNAL_TOPMOVIES_URL = USE_EXTERNAL_PROVIDERS ? process.env.EXTERNAL_TOPMOVIES_URL : null;
const EXTERNAL_MOVIESMOD_URL = USE_EXTERNAL_PROVIDERS ? process.env.EXTERNAL_MOVIESMOD_URL : null;
console.log(`[addon.js] External providers: ${USE_EXTERNAL_PROVIDERS ? 'enabled' : 'disabled'}`);
if (USE_EXTERNAL_PROVIDERS) {
console.log(`[addon.js] External UHDMovies URL: ${EXTERNAL_UHDMOVIES_URL || 'Not configured (using local)'}`);
// (Removed) External DramaDrip URL log
console.log(`[addon.js] External TopMovies URL: ${EXTERNAL_TOPMOVIES_URL || 'Not configured (using local)'}`);
console.log(`[addon.js] External MoviesMod URL: ${EXTERNAL_MOVIESMOD_URL || 'Not configured (using local)'}`);
} else {
console.log(`[addon.js] All providers will use local implementations`);
}
// NEW: Stream caching config
const STREAM_CACHE_DIR = process.env.VERCEL ? path.join('/tmp', '.streams_cache') : path.join(__dirname, '.streams_cache');
const STREAM_CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes
const ENABLE_STREAM_CACHE = process.env.DISABLE_STREAM_CACHE !== 'true'; // Enabled by default
console.log(`[addon.js] Stream links caching ${ENABLE_STREAM_CACHE ? 'enabled' : 'disabled'}`);
console.log(`[addon.js] Redis caching ${redis ? 'available' : 'not available'}`);
const { getSoaperTvStreams } = require('./providers/soapertv.js'); // Import from soapertv.js
const { getStreamContent } = require('./providers/vidsrcextractor.js'); // Import from vidsrcextractor.js
const { getVidZeeStreams } = require('./providers/VidZee.js'); // NEW: Import from VidZee.js
const { getMP4HydraStreams } = require('./providers/MP4Hydra.js'); // NEW: Import from MP4Hydra.js
const { getUHDMoviesStreams } = require('./providers/uhdmovies.js'); // NEW: Import from uhdmovies.js
const { getMoviesModStreams } = require('./providers/moviesmod.js'); // NEW: Import from moviesmod.js
const { getTopMoviesStreams } = require('./providers/topmovies.js'); // NEW: Import from topmovies.js
const { getMoviesDriveStreams } = require('./providers/moviesdrive.js'); // NEW: Import from moviesdrive.js
const { get4KHDHubStreams } = require('./providers/4khdhub.js'); // NEW: Import from 4khdhub.js
const { getHDHub4uStreams } = require('./providers/hdhub4u.js'); // NEW: Import from hdhub4u.js
const { getVixsrcStreams } = require('./providers/vixsrc.js'); // NEW: Import from vixsrc.js
const { getMovieBoxStreams } = require('./providers/moviebox.js'); // NEW: Import from moviebox.js
const axios = require('axios'); // For external provider requests
// Helper function to make requests to external provider services
async function fetchFromExternalProvider(baseUrl, providerName, tmdbId, type, season = null, episode = null) {
try {
const endpoint = `/api/streams/${providerName.toLowerCase()}/${tmdbId}`;
const url = `${baseUrl.replace(/\/$/, '')}${endpoint}`;
// Build query parameters
const queryParams = new URLSearchParams({ type });
if (season !== null) queryParams.append('season', season);
if (episode !== null) queryParams.append('episode', episode);
const fullUrl = `${url}?${queryParams.toString()}`;
console.log(`[External Provider] Making request to: ${fullUrl}`);
const response = await axios.get(fullUrl, {
timeout: 30000, // 30 second timeout
headers: {
'User-Agent': 'NuvioStreamsAddon/1.0'
}
});
if (response.data && response.data.success) {
return response.data.streams || [];
} else {
console.error(`[External Provider] Request failed:`, response.data?.error || 'Unknown error');
return [];
}
} catch (error) {
console.error(`[External Provider] Error making request to ${baseUrl}/api/streams/${providerName.toLowerCase()}/${tmdbId}:`, error.message);
return [];
}
}
// --- Analytics Configuration ---
const GA_MEASUREMENT_ID = process.env.GA_MEASUREMENT_ID;
const GA_API_SECRET = process.env.GA_API_SECRET;
const ANALYTICS_ENABLED = GA_MEASUREMENT_ID && GA_API_SECRET;
if (ANALYTICS_ENABLED) {
console.log(`[Analytics] GA4 Measurement Protocol is enabled. Tracking to ID: ${GA_MEASUREMENT_ID}`);
} else {
console.log('[Analytics] GA4 Measurement Protocol is disabled. Set GA_MEASUREMENT_ID and GA_API_SECRET to enable.');
}
// --- Constants ---
const TMDB_API_URL = 'https://api.themoviedb.org/3';
const TMDB_API_KEY = process.env.TMDB_API_KEY;
const MAX_RETRIES = 3;
const RETRY_DELAY_MS = 1000;
// Default to proxy/direct mode with Showbox.js
console.log('Using proxy/direct mode with Showbox.js');
const scraper = require('./providers/Showbox.js');
// Destructure the required functions from the selected scraper
const { getStreamsFromTmdbId, convertImdbToTmdb, sortStreamsByQuality } = scraper;
const manifest = require('./manifest.json');
// Initialize the addon
const builder = new addonBuilder(manifest);
// --- Helper Functions ---
// NEW: Helper function to parse quality strings into numerical values
function parseQuality(qualityString) {
if (!qualityString || typeof qualityString !== 'string') {
return 0; // Default for unknown or undefined
}
const q = qualityString.toLowerCase();
if (q.includes('4k') || q.includes('2160')) return 2160;
if (q.includes('1440')) return 1440;
if (q.includes('1080')) return 1080;
if (q.includes('720')) return 720;
if (q.includes('576')) return 576;
if (q.includes('480')) return 480;
if (q.includes('360')) return 360;
if (q.includes('240')) return 240;
// Handle kbps by extracting number, e.g., "2500k" -> 2.5 (lower than p values)
const kbpsMatch = q.match(/(\d+)k/);
if (kbpsMatch && kbpsMatch[1]) {
return parseInt(kbpsMatch[1], 10) / 1000; // Convert to a small number relative to pixel heights
}
if (q.includes('hd')) return 720; // Generic HD
if (q.includes('sd')) return 480; // Generic SD
// Lower quality tags
if (q.includes('cam') || q.includes('camrip')) return 100;
if (q.includes('ts') || q.includes('telesync')) return 200;
if (q.includes('scr') || q.includes('screener')) return 300;
if (q.includes('dvdscr')) return 350;
if (q.includes('r5') || q.includes('r6')) return 400;
if (q.includes('org')) return 4320; // Treat original uploads as higher than 4K
return 0; // Default for anything else not recognized
}
// NEW: Helper function to parse size strings into a number (in MB)
function parseSize(sizeString) {
if (!sizeString || typeof sizeString !== 'string') {
return 0;
}
const match = sizeString.match(/([0-9.,]+)\s*(GB|MB|KB)/i);
if (!match) {
return 0;
}
const sizeValue = parseFloat(match[1].replace(/,/g, ''));
const unit = match[2].toUpperCase();
if (unit === 'GB') {
return sizeValue * 1024;
} else if (unit === 'MB') {
return sizeValue;
} else if (unit === 'KB') {
return sizeValue / 1024;
}
return 0;
}
// NEW: Helper function to filter streams by minimum quality
function filterStreamsByQuality(streams, minQualitySetting, providerName) {
if (!minQualitySetting || minQualitySetting.toLowerCase() === 'all') {
console.log(`[${providerName}] No minimum quality filter applied (set to 'all' or not specified).`);
return streams; // No filtering needed
}
const minQualityNumeric = parseQuality(minQualitySetting);
if (minQualityNumeric === 0 && minQualitySetting.toLowerCase() !== 'all') { // Check if minQualitySetting was something unrecognized
console.warn(`[${providerName}] Minimum quality setting '${minQualitySetting}' was not recognized. No filtering applied.`);
return streams;
}
console.log(`[${providerName}] Filtering streams. Minimum quality: ${minQualitySetting} (Parsed as: ${minQualityNumeric}). Original count: ${streams.length}`);
const filteredStreams = streams.filter(stream => {
const streamQualityNumeric = parseQuality(stream.quality);
return streamQualityNumeric >= minQualityNumeric;
});
console.log(`[${providerName}] Filtered count: ${filteredStreams.length}`);
return filteredStreams;
}
// NEW: Helper function to filter streams by excluding specific codecs
function filterStreamsByCodecs(streams, excludeCodecSettings, providerName) {
if (!excludeCodecSettings || Object.keys(excludeCodecSettings).length === 0) {
console.log(`[${providerName}] No codec exclusions applied.`);
return streams; // No filtering needed
}
const excludeDV = excludeCodecSettings.excludeDV === true;
const excludeHDR = excludeCodecSettings.excludeHDR === true;
if (!excludeDV && !excludeHDR) {
console.log(`[${providerName}] No codec exclusions enabled.`);
return streams;
}
console.log(`[${providerName}] Filtering streams. Exclude DV: ${excludeDV}, Exclude HDR: ${excludeHDR}. Original count: ${streams.length}`);
const filteredStreams = streams.filter(stream => {
if (!stream.codecs || !Array.isArray(stream.codecs)) {
return true; // Keep streams without codec information
}
// Check for DV exclusion
if (excludeDV && stream.codecs.includes('DV')) {
console.log(`[${providerName}] Excluding stream with DV codec: ${stream.title || stream.url}`);
return false;
}
// Check for HDR exclusion (including HDR, HDR10, HDR10+)
if (excludeHDR && (stream.codecs.includes('HDR') || stream.codecs.includes('HDR10') || stream.codecs.includes('HDR10+'))) {
console.log(`[${providerName}] Excluding stream with HDR codec: ${stream.title || stream.url}`);
return false;
}
return true; // Keep the stream
});
console.log(`[${providerName}] After codec filtering count: ${filteredStreams.length}`);
return filteredStreams;
}
// NEW: Helper function that combines both quality and codec filtering
function applyAllStreamFilters(streams, providerName, minQualitySetting, excludeCodecSettings) {
// Apply quality filtering first
let filteredStreams = filterStreamsByQuality(streams, minQualitySetting, providerName);
// Then apply codec filtering
filteredStreams = filterStreamsByCodecs(filteredStreams, excludeCodecSettings, providerName);
return filteredStreams;
}
async function fetchWithRetry(url, options, maxRetries = MAX_RETRIES) {
const { default: fetchFunction } = await import('node-fetch'); // Dynamically import
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetchFunction(url, options); // Use the dynamically imported function
if (!response.ok) {
let errorBody = '';
try {
errorBody = await response.text();
} catch (e) { /* ignore */ }
throw new Error(`HTTP error! Status: ${response.status} ${response.statusText}. Body: ${errorBody.substring(0, 200)}`);
}
return response;
} catch (error) {
lastError = error;
console.warn(`Fetch attempt ${attempt}/${maxRetries} failed for ${url}: ${error.message}`);
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS * Math.pow(2, attempt - 1)));
}
}
}
console.error(`All fetch attempts failed for ${url}. Last error:`, lastError.message);
throw lastError;
}
// --- NEW: Google Analytics Event Sending Function ---
async function sendAnalyticsEvent(eventName, eventParams) {
if (!ANALYTICS_ENABLED) {
return;
}
// Use a dynamically generated client_id for each event to ensure anonymity
const clientId = crypto.randomBytes(16).toString("hex");
const analyticsData = {
client_id: clientId,
events: [{
name: eventName,
params: {
// GA4 standard parameters for better reporting
session_id: crypto.randomBytes(16).toString("hex"),
engagement_time_msec: '100',
...eventParams
},
}],
};
try {
const { default: fetchFunction } = await import('node-fetch');
// Use a proper timeout and catch any network errors to prevent crashes
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000); // 5 second timeout
// Fire-and-forget with proper error handling
fetchFunction(`https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}&api_secret=${GA_API_SECRET}`, {
method: 'POST',
body: JSON.stringify(analyticsData),
signal: controller.signal
}).catch(err => {
console.warn(`[Analytics] Network error sending event: ${err.message}`);
}).finally(() => {
clearTimeout(timeout);
});
console.log(`[Analytics] Sent event: ${eventName} for "${eventParams.content_title || 'N/A'}"`);
} catch (error) {
console.warn(`[Analytics] Failed to send event: ${error.message}`);
}
}
// Helper function for fetching with a timeout
function fetchWithTimeout(promise, timeoutMs, providerName) {
return new Promise((resolve) => { // Always resolve to prevent Promise.all from rejecting
let timer = null;
const timeoutPromise = new Promise(r => {
timer = setTimeout(() => {
console.log(`[${providerName}] Request timed out after ${timeoutMs}ms. Returning empty array.`);
r({ streams: [], provider: providerName, error: new Error('Timeout') }); // Resolve with an object indicating timeout
}, timeoutMs);
});
Promise.race([promise, timeoutPromise])
.then((result) => {
clearTimeout(timer);
// Ensure the result is an object with a streams array, even if the original promise resolved with just an array
if (Array.isArray(result)) {
resolve({ streams: result, provider: providerName });
} else if (result && typeof result.streams !== 'undefined') {
resolve(result); // Already in the expected format (e.g. from timeoutPromise)
} else {
// This case might happen if the promise resolves with something unexpected
console.warn(`[${providerName}] Resolved with unexpected format. Returning empty array. Result:`, result);
resolve({ streams: [], provider: providerName });
}
})
.catch(error => {
clearTimeout(timer);
console.error(`[${providerName}] Error fetching streams: ${error.message}. Returning empty array.`);
resolve({ streams: [], provider: providerName, error }); // Resolve with an object indicating error
});
});
}
// Define function to get streams from VidSrc
async function getVidSrcStreams(tmdbId, mediaType, seasonNum = null, episodeNum = null) {
try {
console.log(`[VidSrc] Attempting to fetch streams for TMDB ID: ${tmdbId}, Type: ${mediaType}, Season: ${seasonNum}, Episode: ${episodeNum}`);
// Convert TMDB ID to IMDb ID for VidSrc
// This is a simplified example - you might need to implement proper TMDB to IMDb conversion
// For now, assuming we have access to the IMDb ID from the caller
let imdbId;
if (tmdbId.startsWith('tt')) {
imdbId = tmdbId; // Already an IMDb ID
} else {
// You would need to implement this conversion
// For example, using the convertTmdbToImdb function if available
// imdbId = await convertTmdbToImdb(tmdbId, mediaType);
console.log(`[VidSrc] TMDB ID conversion not implemented yet. Skipping...`);
return [];
}
// Format the ID according to VidSrc requirements
let vidsrcId;
if (mediaType === 'movie') {
vidsrcId = imdbId;
} else if (mediaType === 'tv' && seasonNum !== null && episodeNum !== null) {
vidsrcId = `${imdbId}:${seasonNum}:${episodeNum}`;
} else {
console.log(`[VidSrc] Invalid parameters for TV show. Need season and episode numbers.`);
return [];
}
// Call the getStreamContent function from vidsrcextractor.js
const typeForVidSrc = mediaType === 'movie' ? 'movie' : 'series';
const results = await getStreamContent(vidsrcId, typeForVidSrc);
if (!results || results.length === 0) {
console.log(`[VidSrc] No streams found for ${vidsrcId}.`);
return [];
}
// Process the results into the standard stream format
const streams = [];
for (const result of results) {
if (result.streams && result.streams.length > 0) {
for (const streamInfo of result.streams) {
const quality = streamInfo.quality.includes('x')
? streamInfo.quality.split('x')[1] + 'p' // Convert "1280x720" to "720p"
: streamInfo.quality; // Keep as is for kbps or unknown
streams.push({
title: result.name || "VidSrc Stream",
url: streamInfo.url,
quality: quality,
provider: "VidSrc",
// You can add additional metadata if needed
size: "Unknown size",
languages: ["Unknown"],
subtitles: [],
// If the referer is needed for playback
headers: result.referer ? { referer: result.referer } : undefined
});
}
}
}
console.log(`[VidSrc] Successfully extracted ${streams.length} streams.`);
return streams;
} catch (error) {
console.error(`[VidSrc] Error fetching streams:`, error.message);
return [];
}
}
// --- Stream Caching Functions ---
// Ensure stream cache directory exists
const ensureStreamCacheDir = async () => {
if (!ENABLE_STREAM_CACHE) return;
try {
await fs.mkdir(STREAM_CACHE_DIR, { recursive: true });
console.log(`[Stream Cache] Cache directory ensured at ${STREAM_CACHE_DIR}`);
} catch (error) {
if (error.code !== 'EEXIST') {
console.warn(`[Stream Cache] Warning: Could not create cache directory ${STREAM_CACHE_DIR}: ${error.message}`);
}
}
};
// Initialize stream cache directory on startup
ensureStreamCacheDir().catch(err => console.error(`[Stream Cache] Error creating cache directory: ${err.message}`));
// Generate cache key for a provider's streams
const getStreamCacheKey = (provider, type, id, seasonNum = null, episodeNum = null, region = null, cookie = null) => {
// Basic key parts
let key = `streams_${provider}_${type}_${id}`;
// Add season/episode for TV series
if (seasonNum !== null && episodeNum !== null) {
key += `_s${seasonNum}e${episodeNum}`;
}
// For ShowBox with custom cookie/region, add those to the cache key
if (provider.toLowerCase() === 'showbox' && (region || cookie)) {
key += '_custom';
if (region) key += `_${region}`;
if (cookie) {
// Hash the cookie to avoid storing sensitive info in filenames
const cookieHash = crypto.createHash('md5').update(cookie).digest('hex').substring(0, 10);
key += `_${cookieHash}`;
}
}
return key;
};
// Get cached streams for a provider - Hybrid approach (Redis first, then file)
const getStreamFromCache = async (provider, type, id, seasonNum = null, episodeNum = null, region = null, cookie = null) => {
if (!ENABLE_STREAM_CACHE) return null;
// Exclude ShowBox and PStream from cache entirely
try {
if (provider && ['showbox', 'pstream'].includes(String(provider).toLowerCase())) {
return null;
}
} catch (_) { }
const cacheKey = getStreamCacheKey(provider, type, id, seasonNum, episodeNum, region, cookie);
// Try Redis first if available
if (redis) {
try {
const data = await redis.get(cacheKey);
if (data) {
const cached = JSON.parse(data);
// Check if cache is expired (redundant with Redis TTL, but for safety)
if (cached.expiry && Date.now() > cached.expiry) {
console.log(`[Redis Cache] EXPIRED for ${provider}: ${cacheKey}`);
await redis.del(cacheKey);
return null;
}
// Check for failed status - retry on next request
if (cached.status === 'failed') {
console.log(`[Redis Cache] RETRY for previously failed ${provider}: ${cacheKey}`);
return null;
}
console.log(`[Redis Cache] HIT for ${provider}: ${cacheKey}`);
return cached.streams;
}
} catch (error) {
console.warn(`[Redis Cache] READ ERROR for ${provider}: ${cacheKey}: ${error.message}`);
console.log('[Redis Cache] Falling back to file cache');
// Fall back to file cache on Redis error
}
}
// File cache fallback
const fileCacheKey = cacheKey + '.json';
const cachePath = path.join(STREAM_CACHE_DIR, fileCacheKey);
try {
const data = await fs.readFile(cachePath, 'utf-8');
const cached = JSON.parse(data);
// Check if cache is expired
if (cached.expiry && Date.now() > cached.expiry) {
console.log(`[File Cache] EXPIRED for ${provider}: ${fileCacheKey}`);
await fs.unlink(cachePath).catch(() => { }); // Delete expired cache
return null;
}
// Check for failed status - retry on next request
if (cached.status === 'failed') {
console.log(`[File Cache] RETRY for previously failed ${provider}: ${fileCacheKey}`);
return null;
}
console.log(`[File Cache] HIT for ${provider}: ${fileCacheKey}`);
return cached.streams;
} catch (error) {
if (error.code !== 'ENOENT') {
console.warn(`[File Cache] READ ERROR for ${provider}: ${fileCacheKey}: ${error.message}`);
}
return null;
}
};
// Save streams to cache - Hybrid approach (Redis + file)
const saveStreamToCache = async (provider, type, id, streams, status = 'ok', seasonNum = null, episodeNum = null, region = null, cookie = null, ttlMs = null) => {
if (!ENABLE_STREAM_CACHE) return;
// Exclude ShowBox and PStream from cache entirely
try {
if (provider && ['showbox', 'pstream'].includes(String(provider).toLowerCase())) {
return;
}
} catch (_) { }
const cacheKey = getStreamCacheKey(provider, type, id, seasonNum, episodeNum, region, cookie);
const effectiveTtlMs = ttlMs !== null ? ttlMs : STREAM_CACHE_TTL_MS; // Use provided TTL or default
const cacheData = {
streams: streams,
status: status,
expiry: Date.now() + effectiveTtlMs, // Use effective TTL
timestamp: Date.now()
};
let redisSuccess = false;
// Try Redis first if available
if (redis) {
try {
// PX sets expiry in milliseconds
await redis.set(cacheKey, JSON.stringify(cacheData), 'PX', effectiveTtlMs); // Use effective TTL
console.log(`[Redis Cache] SAVED for ${provider}: ${cacheKey} (${streams.length} streams, status: ${status}, TTL: ${effectiveTtlMs / 1000}s)`);
redisSuccess = true;
} catch (error) {
console.warn(`[Redis Cache] WRITE ERROR for ${provider}: ${cacheKey}: ${error.message}`);
console.log('[Redis Cache] Falling back to file cache');
}
}
// Also save to file cache as backup, or if Redis failed
try {
const fileCacheKey = cacheKey + '.json';
const cachePath = path.join(STREAM_CACHE_DIR, fileCacheKey);
await fs.writeFile(cachePath, JSON.stringify(cacheData), 'utf-8');
// Only log if Redis didn't succeed to avoid redundant logging
if (!redisSuccess) {
console.log(`[File Cache] SAVED for ${provider}: ${fileCacheKey} (${streams.length} streams, status: ${status}, TTL: ${effectiveTtlMs / 1000}s)`);
}
} catch (error) {
console.warn(`[File Cache] WRITE ERROR for ${provider}: ${cacheKey}.json: ${error.message}`);
}
};
// Define stream handler for movies
builder.defineStreamHandler(async (args) => {
const requestStartTime = Date.now(); // Start total request timer
const providerTimings = {}; // Object to store timings
const formatDuration = (ms) => {
if (ms < 1000) {
return `${ms}ms`;
}
const totalSeconds = ms / 1000;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
let str = "";
if (minutes > 0) {
str += `${minutes}m `;
}
if (seconds > 0 || minutes === 0) {
let secStr = seconds.toFixed(2);
if (secStr.endsWith('.00')) {
secStr = secStr.substring(0, secStr.length - 3);
}
str += `${secStr}s`;
}
return str.trim();
};
const { type, id, config: sdkConfig } = args;
// Read config from global set by server.js middleware
// Use getRequestConfig() (AsyncLocalStorage) for thread safety, fall back to global legacy variable
const requestSpecificConfig = (global.getRequestConfig ? global.getRequestConfig() : null) || global.currentRequestConfig || {};
// Mask sensitive fields for logs
const maskedForLog = (() => {
try {
const clone = JSON.parse(JSON.stringify(requestSpecificConfig));
if (clone.cookie) clone.cookie = '[PRESENT: ****]';
if (clone.cookies && Array.isArray(clone.cookies)) clone.cookies = `[${clone.cookies.length} cookies]`;
if (clone.scraper_api_key) clone.scraper_api_key = '[PRESENT: ****]';
if (clone.chosenFebboxBaseCookieForRequest) clone.chosenFebboxBaseCookieForRequest = '[PRESENT: ****]';
return clone;
} catch (_) {
return { masked: true };
}
})();
console.log(`[addon.js] Read from global.currentRequestConfig: ${JSON.stringify(maskedForLog)}`);
// NEW: Get minimum quality preferences
const minQualitiesPreferences = requestSpecificConfig.minQualities || {};
if (Object.keys(minQualitiesPreferences).length > 0) {
console.log(`[addon.js] Minimum quality preferences: ${JSON.stringify(minQualitiesPreferences)}`);
} else {
console.log(`[addon.js] No minimum quality preferences set by user.`);
}
// NEW: Get codec exclude preferences
const excludeCodecsPreferences = requestSpecificConfig.excludeCodecs || {};
if (Object.keys(excludeCodecsPreferences).length > 0) {
console.log(`[addon.js] Codec exclude preferences: ${JSON.stringify(excludeCodecsPreferences)}`);
} else {
console.log(`[addon.js] No codec exclude preferences set by user.`);
}
console.log("--- FULL ARGS OBJECT (from SDK) ---");
console.log(JSON.stringify(args, null, 2));
console.log("--- SDK ARGS.CONFIG (still logging for comparison) ---");
console.log(JSON.stringify(sdkConfig, null, 2)); // Log the original sdkConfig
console.log("---------------------------------");
// Helper to get flag emoji from URL hostname
const getFlagEmojiForUrl = (url) => {
try {
const hostname = new URL(url).hostname;
// Match common patterns like xx, xxN, xxNN at the start of a part of the hostname
const match = hostname.match(/^([a-zA-Z]{2,3})[0-9]{0,2}(?:[.-]|$)/i);
if (match && match[1]) {
const countryCode = match[1].toLowerCase();
const flagMap = {
'us': '๐บ๐ธ', 'usa': '๐บ๐ธ',
'gb': '๐ฌ๐ง', 'uk': '๐ฌ๐ง',
'ca': '๐จ๐ฆ',
'de': '๐ฉ๐ช',
'fr': '๐ซ๐ท',
'nl': '๐ณ๐ฑ',
'hk': '๐ญ๐ฐ',
'sg': '๐ธ๐ฌ',
'jp': '๐ฏ๐ต',
'au': '๐ฆ๐บ',
'in': '๐ฎ๐ณ',
// Add more as needed
};
return flagMap[countryCode] || ''; // Return empty string if no match
}
} catch (e) {
// Invalid URL or other error
}
return ''; // Default to empty string
};
// Use values from requestSpecificConfig (derived from global)
let userRegionPreference = requestSpecificConfig.region || null;
let userCookie = requestSpecificConfig.cookie || null; // Already decoded by server.js
let userScraperApiKey = requestSpecificConfig.scraper_api_key || null; // NEW: Get ScraperAPI Key
// Combine single cookie + cookies array into unified list for ShowBox
// This ensures both single cookie and multi-cookie setups work
const cookiesFromArray = Array.isArray(requestSpecificConfig.cookies) ? requestSpecificConfig.cookies : [];
const allCookies = [];
// Add single cookie first (priority)
if (userCookie && userCookie.trim()) {
allCookies.push(userCookie.trim());
}
// Add cookies from array (deduplicate)
for (const c of cookiesFromArray) {
if (c && c.trim() && !allCookies.includes(c.trim())) {
allCookies.push(c.trim());
}
}
if (allCookies.length > 0) {
console.log(`[addon.js] Combined ${allCookies.length} unique cookie(s) for ShowBox`);
}
// Log the request information in a more detailed way
console.log(`Stream request for Stremio type: '${type}', id: '${id}'`);
let selectedProvidersArray = null;
if (requestSpecificConfig.providers) {
selectedProvidersArray = requestSpecificConfig.providers.split(',').map(p => p.trim().toLowerCase());
}
// Detect presence of cookies (single or array)
const hasCookiesArray = cookiesFromArray.length > 0;
const hasAnyCookies = allCookies.length > 0;
console.log(`Effective request details: ${JSON.stringify({
regionPreference: userRegionPreference || 'none',
hasCookie: hasAnyCookies,
cookieCount: allCookies.length,
selectedProviders: selectedProvidersArray ? selectedProvidersArray.join(', ') : 'all'
})}`);
if (userRegionPreference) {
console.log(`[addon.js] Using region from global config: ${userRegionPreference}`);
} else {
console.log(`[addon.js] No region preference found in global config.`);
}
if (hasAnyCookies) {
const cookieSource = userCookie ? 'single' : 'array';
console.log(`[addon.js] Using personal cookie(s): ${allCookies.length} cookie(s) available (source: ${cookieSource})`);
} else {
console.log(`[addon.js] No cookie found in global config.`);
}
if (selectedProvidersArray) {
console.log(`[addon.js] Using providers from global config: ${selectedProvidersArray.join(', ')}`);
} else {
console.log('[addon.js] No specific providers selected by user in global config, will attempt all.');
}
if (type !== 'movie' && type !== 'series' && type !== 'tv') {
return { streams: [] };
}
let tmdbId;
let tmdbTypeFromId;
let seasonNum = null;
let episodeNum = null;
let initialTitleFromConversion = null;
let isAnimation = false; // <--- New flag to track if content is animation
const idParts = id.split(':');
if (idParts[0] === 'tmdb') {
tmdbId = idParts[1];
tmdbTypeFromId = type === 'movie' ? 'movie' : 'tv';
console.log(` Received TMDB ID directly: ${tmdbId} for type ${tmdbTypeFromId}`);
// Check for season and episode
if (idParts.length >= 4 && (type === 'series' || type === 'tv')) {
seasonNum = parseInt(idParts[2], 10);
episodeNum = parseInt(idParts[3], 10);
console.log(` Parsed season ${seasonNum}, episode ${episodeNum} from Stremio ID`);
}
} else if (id.startsWith('tt')) {
console.log(` Received IMDb ID: ${id}. Attempting to convert to TMDB ID.`);
const imdbParts = id.split(':');
let baseImdbId = id; // Default to full ID for movies
if (imdbParts.length >= 3 && (type === 'series' || type === 'tv')) {
seasonNum = parseInt(imdbParts[1], 10);
episodeNum = parseInt(imdbParts[2], 10);
baseImdbId = imdbParts[0]; // Use only the IMDb ID part for conversion
console.log(` Parsed season ${seasonNum}, episode ${episodeNum} from IMDb ID parts`);
}
// Pass userRegionPreference and expected type to convertImdbToTmdb
const conversionResult = await convertImdbToTmdb(baseImdbId, userRegionPreference, type);
if (conversionResult && conversionResult.tmdbId && conversionResult.tmdbType) {
tmdbId = conversionResult.tmdbId;
tmdbTypeFromId = conversionResult.tmdbType;
initialTitleFromConversion = conversionResult.title; // Capture title from conversion
console.log(` Successfully converted IMDb ID ${baseImdbId} to TMDB ${tmdbTypeFromId} ID ${tmdbId} (${initialTitleFromConversion || 'No title returned'})`);
} else {
console.log(` Failed to convert IMDb ID ${baseImdbId} to TMDB ID.`);
return { streams: [] };
}
} else {
console.log(` Unrecognized ID format: ${id}`);
return { streams: [] };
}
if (!tmdbId || !tmdbTypeFromId) {
console.log(' Could not determine TMDB ID or type after processing Stremio ID.');
return { streams: [] };
}
let movieOrSeriesTitle = initialTitleFromConversion;
let movieOrSeriesYear = null;
let seasonTitle = null;
if (tmdbId && TMDB_API_KEY) {
try {
let detailsUrl;
if (tmdbTypeFromId === 'movie') {
detailsUrl = `${TMDB_API_URL}/movie/${tmdbId}?api_key=${TMDB_API_KEY}&language=en-US`;
} else { // 'tv'
detailsUrl = `${TMDB_API_URL}/tv/${tmdbId}?api_key=${TMDB_API_KEY}&language=en-US`;
}
console.log(`Fetching details from TMDB: ${detailsUrl}`);
const tmdbDetailsResponse = await fetchWithRetry(detailsUrl, {});
if (!tmdbDetailsResponse.ok) throw new Error(`TMDB API error: ${tmdbDetailsResponse.status}`);
const tmdbDetails = await tmdbDetailsResponse.json();
if (tmdbTypeFromId === 'movie') {
if (!movieOrSeriesTitle) movieOrSeriesTitle = tmdbDetails.title;
movieOrSeriesYear = tmdbDetails.release_date ? tmdbDetails.release_date.substring(0, 4) : null;
} else { // 'tv'
if (!movieOrSeriesTitle) movieOrSeriesTitle = tmdbDetails.name;
movieOrSeriesYear = tmdbDetails.first_air_date ? tmdbDetails.first_air_date.substring(0, 4) : null;
}
console.log(` Fetched/Confirmed TMDB details: Title='${movieOrSeriesTitle}', Year='${movieOrSeriesYear}'`);
// NEW: Fetch season-specific title for TV shows
if (tmdbTypeFromId === 'tv' && seasonNum) {
const seasonDetailsUrl = `${TMDB_API_URL}/tv/${tmdbId}/season/${seasonNum}?api_key=${TMDB_API_KEY}&language=en-US`;
console.log(`Fetching season details from TMDB: ${seasonDetailsUrl}`);
try {
const seasonDetailsResponse = await fetchWithRetry(seasonDetailsUrl, {});
if (seasonDetailsResponse.ok) {