-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cjs
More file actions
2001 lines (1765 loc) · 63 KB
/
main.cjs
File metadata and controls
2001 lines (1765 loc) · 63 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
const { app, BrowserWindow, ipcMain, net } = require('electron/main');
const path = require('node:path');
const fs = require('node:fs');
const { getMpvBinaryPath } = require('./src/mpv-path');
const { mpvController } = require('./src/mpv-controller');
const { getDisplayContext } = require('./src/display-detector');
const { parseTorrentMetadata, parseTorrentName, sortTorrentsByQuality } = require('./src/torrent-metadata');
const { computeAdvisoryScore, computeAdvisoryScores, enrichTorrentsWithAdvisory } = require('./src/advisory-scorer');
const { selectTorrent } = require('./src/llm-torrent-selector');
// Load .env into process.env (main process only)
try {
const envPath = path.join(__dirname, '.env');
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8');
for (const line of content.split('\n')) {
const m = line.match(/^\s*([^#=]+)=(.*)$/);
if (m) process.env[m[1].trim()] = m[2].trim().replace(/^["']|["']$/g, '');
}
}
} catch (_) {}
let mainWindow = null;
let wtClient = null;
let wtServer = null;
let serverBaseUrl = null;
let currentTorrent = null;
let progressInterval = null;
let downloadsUpdateInterval = null;
const VIDEO_EXTENSIONS = ['.mp4', '.mkv', '.webm', '.avi', '.mov'];
const TORRENT_READY_TIMEOUT = 60000; // 60 seconds to wait for torrent metadata
// ─────────────────────────────────────────────────────────────────────────────
// Download Manager - State & Persistence
// ─────────────────────────────────────────────────────────────────────────────
// Active torrents being downloaded/seeded: Map<infoHash, { torrent, meta, status }>
const activeTorrents = new Map();
// Persisted download data
let downloadsData = {}; // { [infoHash]: { title, subtitle, thumbnail, progress, status, ... } }
let appSettings = { seedRatio: 1.0 };
// Paths for persistence
let appDataDir = null;
let downloadsDir = null;
let settingsPath = null;
let downloadsDataPath = null;
function ensureAppDataDirs() {
appDataDir = path.join(app.getPath('userData'), 'FuckNetflix');
downloadsDir = path.join(app.getPath('downloads'), 'FuckNetflix');
settingsPath = path.join(appDataDir, 'settings.json');
downloadsDataPath = path.join(appDataDir, 'downloads.json');
// Create directories if they don't exist
if (!fs.existsSync(appDataDir)) {
fs.mkdirSync(appDataDir, { recursive: true });
}
if (!fs.existsSync(downloadsDir)) {
fs.mkdirSync(downloadsDir, { recursive: true });
}
}
function loadSettings() {
try {
if (fs.existsSync(settingsPath)) {
const data = fs.readFileSync(settingsPath, 'utf8');
appSettings = { ...appSettings, ...JSON.parse(data) };
}
} catch (_) {
// Use defaults
}
}
function saveSettings() {
try {
fs.writeFileSync(settingsPath, JSON.stringify(appSettings, null, 2));
} catch (_) {
// Ignore write errors
}
}
function loadDownloadsData() {
try {
if (fs.existsSync(downloadsDataPath)) {
const data = fs.readFileSync(downloadsDataPath, 'utf8');
downloadsData = JSON.parse(data);
}
} catch (_) {
downloadsData = {};
}
}
function saveDownloadsData() {
try {
fs.writeFileSync(downloadsDataPath, JSON.stringify(downloadsData, null, 2));
} catch (_) {
// Ignore write errors
}
}
function updateDownloadData(infoHash, updates) {
if (!downloadsData[infoHash]) {
downloadsData[infoHash] = {};
}
Object.assign(downloadsData[infoHash], updates);
saveDownloadsData();
}
function getDownloadsList() {
const list = [];
// Add active torrents
for (const [infoHash, active] of activeTorrents) {
const t = active.torrent;
const meta = active.meta || {};
const isPaused = active.status === 'paused';
const isSeeding = t.progress >= 1 && !isPaused;
list.push({
infoHash,
title: meta.title || t.name || 'Unknown',
subtitle: meta.subtitle || '',
thumbnail: meta.thumbnail || null,
status: isPaused ? 'paused' : isSeeding ? 'seeding' : 'downloading',
progress: t.progress,
downloaded: t.downloaded,
uploaded: t.uploaded,
length: t.length,
downloadSpeed: t.downloadSpeed,
uploadSpeed: t.uploadSpeed,
seedRatio: t.downloaded > 0 ? t.uploaded / t.downloaded : 0,
numPeers: t.numPeers,
});
}
// Add completed downloads from persisted data (not currently active)
for (const [infoHash, data] of Object.entries(downloadsData)) {
if (!activeTorrents.has(infoHash) && data.status === 'completed') {
list.push({
infoHash,
title: data.title || 'Unknown',
subtitle: data.subtitle || '',
thumbnail: data.thumbnail || null,
status: 'completed',
progress: 1,
downloaded: data.downloaded || 0,
uploaded: data.uploaded || 0,
length: data.length || 0,
downloadSpeed: 0,
uploadSpeed: 0,
filePath: data.filePath || null,
});
}
}
return list;
}
function sendDownloadsUpdate() {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('downloads-update', getDownloadsList());
}
}
/**
* Resume incomplete downloads from persisted data on app startup.
* Re-adds magnets to WebTorrent for downloads that were in progress.
*/
async function resumeIncompleteDownloads() {
if (!wtClient || !downloadsDir) return;
for (const [infoHash, data] of Object.entries(downloadsData)) {
// Skip completed downloads or those without a magnet
if (data.status === 'completed' || !data.magnet) continue;
// Skip if already active (shouldn't happen on startup, but safety check)
if (activeTorrents.has(infoHash)) continue;
try {
// Re-add the torrent to WebTorrent
const torrent = wtClient.add(data.magnet, { path: downloadsDir }, (t) => {
const file = pickVideoFile(t.files);
if (!file) {
t.destroy();
return;
}
// Track this resumed download
activeTorrents.set(t.infoHash, {
torrent: t,
meta: {
title: data.title,
subtitle: data.subtitle,
thumbnail: data.thumbnail,
},
status: t.progress >= 1 ? 'seeding' : 'downloading',
});
// Update persisted data with resumed status
updateDownloadData(t.infoHash, {
status: t.progress >= 1 ? 'completed' : 'downloading',
});
// Handle completion
t.on('done', () => {
const active = activeTorrents.get(t.infoHash);
if (active) {
active.status = 'seeding';
}
updateDownloadData(t.infoHash, {
status: 'completed',
completedAt: Date.now(),
filePath: path.join(downloadsDir, file.path),
downloaded: t.downloaded,
length: t.length,
});
sendDownloadsUpdate();
checkSeedRatio(t);
});
// Track upload progress for seed ratio
t.on('upload', () => {
checkSeedRatio(t);
});
sendDownloadsUpdate();
});
// Handle torrent-level errors (e.g., invalid magnet, network issues)
if (torrent && typeof torrent.on === 'function') {
torrent.on('error', (err) => {
console.error(`Failed to resume download ${infoHash}:`, err.message);
// Remove from active torrents on error
activeTorrents.delete(infoHash);
sendDownloadsUpdate();
});
}
} catch (err) {
console.error(`Error resuming download ${infoHash}:`, err.message);
}
}
}
function startDownloadsUpdateInterval() {
stopDownloadsUpdateInterval();
downloadsUpdateInterval = setInterval(sendDownloadsUpdate, 1000);
}
function stopDownloadsUpdateInterval() {
if (downloadsUpdateInterval) {
clearInterval(downloadsUpdateInterval);
downloadsUpdateInterval = null;
}
}
const YTS_TRACKERS = [
'udp://open.demonii.com:1337/announce',
'udp://tracker.openbittorrent.com:80',
'udp://tracker.coppersurfer.tk:6969',
'udp://glotorrents.pw:6969/announce',
'udp://tracker.opentrackr.org:1337/announce',
'udp://torrent.gresille.org:80/announce',
'udp://p4p.arenabg.com:1337',
'udp://tracker.leechers-paradise.org:6969',
];
function buildYtsMagnet(hash, title) {
const dn = encodeURIComponent(title || 'movie');
const tr = YTS_TRACKERS.map((t) => 'tr=' + encodeURI(t)).join('&');
return `magnet:?xt=urn:btih:${hash}&dn=${dn}&${tr}`;
}
const API_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0',
Accept: 'application/json',
};
const YTS_BASE_URLS = [
'https://yts.mx',
'https://yts.lt',
'https://yts.ag',
'https://yts.am',
'https://yts.gg',
'https://yts.bz',
];
async function netFetchJson(url) {
const res = await net.fetch(url, { headers: API_HEADERS });
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
/**
* Wrapper for network requests with retry logic and exponential backoff
* @param {function} fetchFn - Async function that performs the fetch
* @param {object} options - Retry options
* @param {number} options.maxRetries - Maximum number of retry attempts (default: 3)
* @param {number} options.baseDelay - Base delay in ms for exponential backoff (default: 1000)
* @param {number} options.maxDelay - Maximum delay between retries (default: 10000)
* @param {function} options.onRetry - Callback called before each retry (attempt, maxRetries, error)
* @param {function} options.shouldRetry - Function to determine if error is retryable (default: true for network errors)
* @returns {Promise<any>} - Result of the fetch function
*/
async function fetchWithRetry(fetchFn, options = {}) {
const {
maxRetries = 3,
baseDelay = 1000,
maxDelay = 10000,
onRetry = null,
shouldRetry = (err) => {
// Retry on network errors, timeouts, and 5xx server errors
const message = err.message || '';
return (
message.includes('fetch') ||
message.includes('network') ||
message.includes('ECONNREFUSED') ||
message.includes('ETIMEDOUT') ||
message.includes('ENOTFOUND') ||
message.includes('timeout') ||
message.includes('aborted') ||
/Request failed: 5\d\d/.test(message)
);
},
} = options;
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fetchFn();
} catch (err) {
lastError = err;
// Check if we should retry this error
if (!shouldRetry(err) || attempt >= maxRetries) {
break;
}
// Calculate delay with exponential backoff and jitter
const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
const jitter = Math.random() * 0.3 * exponentialDelay; // 0-30% jitter
const delay = Math.min(exponentialDelay + jitter, maxDelay);
// Notify about retry
if (onRetry) {
onRetry(attempt, maxRetries, err);
}
// Wait before retrying
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
// Enhance error message for common network issues
if (lastError) {
const message = lastError.message || '';
if (message.includes('ENOTFOUND') || message.includes('ECONNREFUSED')) {
lastError.userMessage = 'Unable to connect. Please check your internet connection.';
lastError.isNetworkError = true;
} else if (message.includes('timeout') || message.includes('aborted')) {
lastError.userMessage = 'Request timed out. The server may be slow or unreachable.';
lastError.isNetworkError = true;
} else if (/Request failed: 5\d\d/.test(message)) {
lastError.userMessage = 'Server temporarily unavailable. Please try again later.';
lastError.isNetworkError = true;
}
}
throw lastError;
}
/**
* Check if the system appears to be offline
* @returns {boolean}
*/
function isOfflineError(err) {
const message = (err?.message || '').toLowerCase();
return (
message.includes('enotfound') ||
message.includes('econnrefused') ||
message.includes('network') ||
message.includes('offline')
);
}
async function ytsFetch(path) {
let lastErr = null;
// Try each YTS mirror with retry logic
for (const base of YTS_BASE_URLS) {
try {
const data = await fetchWithRetry(
async () => {
const url = base + path;
return await netFetchJson(url);
},
{
maxRetries: 2, // Quick retries per mirror before moving to next
baseDelay: 500,
maxDelay: 2000,
}
);
if (data.status === 'ok') return data;
lastErr = new Error(data.status_message || 'YTS error');
} catch (err) {
lastErr = err;
// Continue to next mirror
}
}
// Enhance error message for user
if (lastErr) {
if (isOfflineError(lastErr)) {
lastErr.userMessage = 'Unable to reach movie database. Please check your internet connection.';
} else {
lastErr.userMessage = 'Movie database temporarily unavailable. Please try again.';
}
lastErr.isNetworkError = true;
}
throw lastErr || new Error('YTS unreachable');
}
async function searchMovies(query) {
const q = encodeURIComponent(String(query).trim());
const path = `/api/v2/list_movies.json?query_term=${q}&limit=20`;
const data = await ytsFetch(path);
const movies = data.data?.movies ?? [];
return movies.map((m) => ({
id: m.id,
title: m.title ?? m.title_long ?? '',
year: m.year,
rating: m.rating,
cover: m.medium_cover_image || m.small_cover_image,
}));
}
async function getMovieDetails(movieId) {
const path = `/api/v2/movie_details.json?movie_id=${movieId}`;
const data = await ytsFetch(path);
return data.data?.movie ?? null;
}
function pickMovieTorrent(torrents) {
if (!torrents?.length) return null;
const preferred = torrents.find((t) => (t.quality || '').toLowerCase() === '720p');
return preferred || torrents[0];
}
/**
* Pick the best torrent from YTS results using LLM with fallback
* @param {Array} torrents - Array of YTS torrent objects
* @param {string} title - Movie title for context
* @returns {Promise<object|null>} Selected torrent or null
*/
async function pickMovieTorrentWithLlm(torrents, title) {
if (!torrents?.length) return null;
try {
// Convert YTS format to unified format for LLM
const unifiedTorrents = torrents.map((t) => ({
title: `${title} ${t.quality} ${t.type || ''}`.trim(),
seeders: t.seeds || 0,
peers: t.peers || 0,
size: t.size || 'Unknown',
quality: t.quality,
hash: t.hash,
}));
const selection = await selectTorrent(unifiedTorrents, { title });
if (selection && selection.selectedIndex >= 0 && selection.selectedIndex < torrents.length) {
console.log('[LLM Selection YTS]', selection.reasoning);
return torrents[selection.selectedIndex];
}
// Fall back to heuristic
return pickMovieTorrent(torrents);
} catch (error) {
console.error('[LLM] YTS selection failed, using fallback:', error.message);
return pickMovieTorrent(torrents);
}
}
async function searchTvShows(query) {
const q = encodeURIComponent(String(query).trim());
const url = `https://api.tvmaze.com/search/shows?q=${q}`;
const list = await netFetchJson(url);
return (list || []).map((item) => {
const show = item.show || item;
const imdb = show.externals?.imdb || null;
return {
id: show.id,
name: show.name || '',
imdbId: imdb ? imdb.replace(/^tt/, '') : null,
image: show.image?.medium || show.image?.original,
};
});
}
async function getEztvTorrents(imdbId) {
const id = String(imdbId).replace(/^tt/, '');
const url = `https://eztvx.to/api/get-torrents?imdb_id=${id}&limit=100`;
const data = await netFetchJson(url);
const torrents = data.torrents ?? [];
return torrents.map((t) => ({
id: t.id,
title: t.title || t.filename || '',
season: t.season,
episode: t.episode,
magnetUrl: t.magnet_url,
seeds: t.seeds,
peers: t.peers,
}));
}
// ─────────────────────────────────────────────────────────────────────────────
// Unified Torrent API (Torrent-API-Py) - aggregates multiple torrent sites
// Supported: 1337x, tgx (Torrent Galaxy), piratebay, kickass, limetorrent,
// torrentfunk, glodls, bitsearch, magnetdl, torlock, yts, nyaasi
//
// IMPORTANT: Only 1337x supports search_by_category=true!
// Other sites have categories for recent/trending only, NOT for search.
// See: https://github.com/Ryuk-me/Torrent-Api-py#supported-methods-and-categories
// ─────────────────────────────────────────────────────────────────────────────
const TORRENT_API_BASE = 'https://torrent-api-py-nx0x.onrender.com';
const TORRENT_API_TIMEOUT = 8000; // 8 seconds per request
// Sites that support search_by_category (can use /api/v1/category endpoint)
const CATEGORY_SEARCH_SITES = ['1337x'];
// General search sites (use /api/v1/search endpoint - no category filtering)
// These sites work well but don't support category-filtered search
const GENERAL_SITES = ['tgx', 'piratebay', 'kickass', 'limetorrent', 'torrentfunk', 'magnetdl', 'torlock', 'bitsearch', 'glodls'];
/**
* Search a single site on the unified torrent API.
* @param {string} site - Site name (e.g. '1337x', 'tgx', 'piratebay')
* @param {string} query - Search query
* @param {object} options - { category?: string, limit?: number }
* @returns {Promise<Array>}
*/
async function searchSingleSite(site, query, options = {}) {
const { category, limit = 15 } = options;
const q = encodeURIComponent(String(query).trim());
if (!q) return [];
let url;
if (category) {
// Use category endpoint for better filtering
url = `${TORRENT_API_BASE}/api/v1/category?site=${site}&query=${q}&category=${category}&limit=${limit}`;
} else {
url = `${TORRENT_API_BASE}/api/v1/search?site=${site}&query=${q}&limit=${limit}`;
}
try {
// Use fetchWithRetry for resilience against transient failures
const result = await fetchWithRetry(
async () => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), TORRENT_API_TIMEOUT);
try {
const res = await net.fetch(url, {
headers: API_HEADERS,
signal: controller.signal,
});
if (!res.ok) {
throw new Error(`Request failed: ${res.status}`);
}
return await res.json();
} finally {
clearTimeout(timeoutId);
}
},
{
maxRetries: 2,
baseDelay: 500,
maxDelay: 2000,
// Only retry on network/timeout errors, not on 4xx responses
shouldRetry: (err) => {
const msg = err.message || '';
return msg.includes('aborted') || msg.includes('timeout') ||
msg.includes('ECONNREFUSED') || msg.includes('ETIMEDOUT') ||
/Request failed: 5\d\d/.test(msg);
},
}
);
const data = result.data ?? [];
return data
.filter((t) => t.magnet)
.map((t) => ({
magnet: t.magnet,
title: t.name || t.title || '',
seeders: parseInt(t.seeders, 10) || 0,
size: t.size || '',
source: site,
}));
} catch (_) {
// Return empty array on failure - parallel searches will continue
return [];
}
}
/**
* Search multiple sites in parallel for movies.
* @param {string} query - Movie title (optionally with year)
* @param {number} limit - Results per site
* @returns {Promise<Array>}
*/
async function searchMovieSources(query, limit = 10) {
const searches = [
// Category-filtered searches (only 1337x supports this)
...CATEGORY_SEARCH_SITES.map((site) => searchSingleSite(site, query, { category: 'movies', limit })),
// General searches (all other sites - no category filtering available)
...GENERAL_SITES.map((site) => searchSingleSite(site, query, { limit })),
];
const results = await Promise.all(searches);
return results.flat();
}
/**
* Search multiple sites in parallel for TV shows.
* @param {string} query - Show name or "ShowName S01E05"
* @param {number} limit - Results per site
* @returns {Promise<Array>}
*/
async function searchTvSources(query, limit = 15) {
const searches = [
// Category-filtered searches (only 1337x supports this)
...CATEGORY_SEARCH_SITES.map((site) => searchSingleSite(site, query, { category: 'tv', limit })),
// General searches (all other sites - no category filtering available)
...GENERAL_SITES.map((site) => searchSingleSite(site, query, { limit })),
];
const results = await Promise.all(searches);
return results.flat();
}
/**
* Legacy function for backward compatibility - searches all sites.
* @param {string} query - Search query
* @param {object} options - { site?: string, limit?: number }
* @returns {Promise<Array>}
*/
async function searchUnifiedApi(query, options = {}) {
const { site, limit = 10 } = options;
if (site) {
return searchSingleSite(site, query, { limit });
}
// Search all sites in parallel
const allSites = [...new Set([...CATEGORY_SEARCH_SITES, ...GENERAL_SITES])];
const searches = allSites.map((s) => searchSingleSite(s, query, { limit: Math.ceil(limit / 2) }));
const results = await Promise.all(searches);
return results.flat();
}
/**
* Pick the best torrent from results for a movie.
* Prefers 1080p > 720p > highest seeders, with minimum seeder threshold.
* @param {Array} results - Array of torrent results
* @returns {object|null}
*/
function pickBestUnifiedTorrent(results) {
if (!results?.length) return null;
// Filter out very low seeder torrents (likely dead)
const viable = results.filter((t) => t.seeders >= 1);
if (!viable.length) return results[0]; // Fall back to any result
// Prefer 1080p with good seeds
const hd1080 = viable.filter((t) => /1080p/i.test(t.title));
if (hd1080.length) {
return hd1080.reduce((best, curr) => (curr.seeders > (best?.seeders || 0) ? curr : best), null);
}
// Then 720p
const hd720 = viable.filter((t) => /720p/i.test(t.title));
if (hd720.length) {
return hd720.reduce((best, curr) => (curr.seeders > (best?.seeders || 0) ? curr : best), null);
}
// Otherwise highest seeders
return viable.reduce((best, curr) => (curr.seeders > (best?.seeders || 0) ? curr : best), null);
}
/**
* Pick the best torrent using LLM with fallback to heuristic method
* @param {Array} results - Array of torrent results
* @param {object} options - Selection options (title, contentType)
* @returns {Promise<object|null>} Selected torrent or null
*/
async function pickBestTorrentWithLlm(results, options = {}) {
if (!results?.length) return null;
try {
// Try LLM selection first
const selection = await selectTorrent(results, options);
// Check if LLM returned a valid selection
if (selection && selection.selectedIndex >= 0 && selection.selectedIndex < results.length) {
console.log('[LLM Selection]', selection.reasoning);
if (selection.warnings?.length > 0) {
console.log('[LLM Warnings]', selection.warnings);
}
return results[selection.selectedIndex];
}
// LLM returned -1 or invalid index, fall back to heuristic
console.log('[LLM] No suitable torrent selected, using fallback heuristic');
return pickBestUnifiedTorrent(results);
} catch (error) {
// LLM failed, fall back to heuristic
console.error('[LLM] Selection failed, using fallback heuristic:', error.message);
return pickBestUnifiedTorrent(results);
}
}
/**
* Parse season/episode from a torrent title (e.g. "Show.Name.S01E05.720p")
* Also handles formats like "1x05", "Season 1 Episode 5"
* @param {string} title
* @returns {{season: number, episode: number}|null}
*/
function parseSeasonEpisode(title) {
// Standard S01E05 format
let match = title.match(/S(\d{1,2})E(\d{1,2})/i);
if (match) {
return { season: parseInt(match[1], 10), episode: parseInt(match[2], 10) };
}
// Alternative 1x05 format
match = title.match(/(\d{1,2})x(\d{1,2})/i);
if (match) {
return { season: parseInt(match[1], 10), episode: parseInt(match[2], 10) };
}
// "Season 1 Episode 5" format
match = title.match(/Season\s*(\d{1,2}).*Episode\s*(\d{1,2})/i);
if (match) {
return { season: parseInt(match[1], 10), episode: parseInt(match[2], 10) };
}
return null;
}
// OpenSubtitles REST API
const OPENSUBTITLES_BASE = 'https://api.opensubtitles.com/api/v1';
function openSubtitlesHeaders() {
const key = process.env.open_subtitles_api_key || '';
return {
'Api-Key': key,
'User-Agent': 'FuckNetflix/1.0',
Accept: 'application/json',
'Content-Type': 'application/json',
};
}
async function openSubtitlesSearch(meta) {
if (!meta || typeof meta !== 'object') return { error: 'No metadata provided for subtitle search.' };
const key = process.env.open_subtitles_api_key;
if (!key) return { error: 'OpenSubtitles API key not set (open_subtitles_api_key in .env).' };
const params = new URLSearchParams();
params.set('languages', 'en');
params.set('order_by', 'download_count');
if (meta.imdbId) {
const id = String(meta.imdbId).replace(/^tt/, '').replace(/\D/g, '');
if (id) params.set('imdb_id', id.padStart(7, '0'));
}
if (!params.has('imdb_id') && meta.title) {
const q = meta.year ? `${meta.title} ${meta.year}` : meta.title;
params.set('query', q);
}
if (!params.has('imdb_id') && !params.has('query')) {
return { error: 'Need imdbId or title to search subtitles.' };
}
if (meta.type === 'episode') {
params.set('type', 'episode');
if (meta.season != null) params.set('season_number', String(meta.season));
if (meta.episode != null) params.set('episode_number', String(meta.episode));
} else {
params.set('type', 'movie');
}
const url = `${OPENSUBTITLES_BASE}/subtitles?${params.toString()}`;
// Use retry logic for subtitle search
let json;
try {
json = await fetchWithRetry(
async () => {
const res = await net.fetch(url, { headers: openSubtitlesHeaders() });
if (!res.ok) {
const text = await res.text();
const err = new Error(`OpenSubtitles search failed: ${res.status} ${text.slice(0, 200)}`);
err.status = res.status;
throw err;
}
return await res.json();
},
{
maxRetries: 2,
baseDelay: 1000,
maxDelay: 3000,
shouldRetry: (err) => {
// Retry on network errors and 5xx, but not on 4xx (client errors)
const msg = err.message || '';
const status = err.status;
return !status || status >= 500 ||
msg.includes('ECONNREFUSED') || msg.includes('ETIMEDOUT') ||
msg.includes('timeout') || msg.includes('network');
},
}
);
} catch (err) {
if (isOfflineError(err)) {
return { error: 'Unable to search subtitles. Please check your internet connection.' };
}
return { error: err.message || 'Subtitle search failed.' };
}
const data = json.data || [];
// Deduplicate: one entry per language (keep best by download_count; already ordered)
const byLang = new Map();
for (const item of data) {
const attrs = item.attributes || {};
const lang = (attrs.language || '').toLowerCase();
if (!lang || byLang.has(lang)) continue;
const files = attrs.files || [];
const file = files[0];
if (!file || file.file_id == null) continue;
byLang.set(lang, {
language: lang,
file_id: file.file_id,
file_name: file.file_name || `${lang}.srt`,
download_count: attrs.download_count ?? 0,
});
}
return { subtitles: [...byLang.values()] };
}
async function openSubtitlesDownload(fileId) {
const key = process.env.open_subtitles_api_key;
if (!key) return { error: 'OpenSubtitles API key not set.' };
// Get download link with retry
let json;
try {
json = await fetchWithRetry(
async () => {
const res = await net.fetch(`${OPENSUBTITLES_BASE}/download`, {
method: 'POST',
headers: openSubtitlesHeaders(),
body: JSON.stringify({ file_id: Number(fileId) }),
});
if (!res.ok) {
const text = await res.text();
const err = new Error(`OpenSubtitles download failed: ${res.status} ${text.slice(0, 200)}`);
err.status = res.status;
throw err;
}
return await res.json();
},
{
maxRetries: 2,
baseDelay: 1000,
maxDelay: 3000,
shouldRetry: (err) => {
const status = err.status;
return !status || status >= 500;
},
}
);
} catch (err) {
if (isOfflineError(err)) {
return { error: 'Unable to download subtitles. Please check your internet connection.' };
}
return { error: err.message || 'Subtitle download failed.' };
}
const link = json.link;
if (!link) return { error: 'No download link in response.' };
// Download the actual subtitle file with retry
try {
const result = await fetchWithRetry(
async () => {
const fileRes = await net.fetch(link);
if (!fileRes.ok) {
throw new Error(`Subtitle file fetch failed: ${fileRes.status}`);
}
return await fileRes.arrayBuffer();
},
{
maxRetries: 2,
baseDelay: 500,
maxDelay: 2000,
}
);
const buf = Buffer.from(result);
const base64 = buf.toString('base64');
const file_name = json.file_name || 'subtitles.srt';
return { content: base64, file_name };
} catch (err) {
if (isOfflineError(err)) {
return { error: 'Unable to download subtitle file. Please check your internet connection.' };
}
return { error: err.message || 'Subtitle file download failed.' };
}
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
},
});
// Load the built React app from renderer-dist/
mainWindow.loadFile(path.join(__dirname, 'renderer-dist', 'index.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
}
function pickVideoFile(files) {
const videoFiles = files.filter((file) => {
const name = (file.name || '').toLowerCase();
return VIDEO_EXTENSIONS.some((ext) => name.endsWith(ext));
});
if (videoFiles.length === 0) return null;
return videoFiles.reduce((a, b) => (a.length > b.length ? a : b));
}
function buildStreamUrl(torrent, file) {
const filePath = file.path.replace(/\\/g, '/').split('/').map(encodeURIComponent).join('/');
return `${serverBaseUrl}/webtorrent/${torrent.infoHash}/${filePath}`;
}
function stopProgressUpdates() {
if (progressInterval) {
clearInterval(progressInterval);
progressInterval = null;
}
currentTorrent = null;
}
function startProgressUpdates(torrent) {
stopProgressUpdates();
currentTorrent = torrent;
const send = () => {
if (!mainWindow || mainWindow.isDestroyed() || !currentTorrent) return;
mainWindow.webContents.send('torrent-progress', {
progress: currentTorrent.progress,
downloaded: currentTorrent.downloaded,
length: currentTorrent.length,
downloadSpeed: currentTorrent.downloadSpeed,
timeRemaining: currentTorrent.timeRemaining,
});
};
torrent.on('download', send);
progressInterval = setInterval(send, 500);
send();
}
async function setupWebTorrent() {
const { default: WebTorrent } = await import('webtorrent');
wtClient = new WebTorrent();
wtServer = wtClient.createServer();
await new Promise((resolve) => {
wtServer.server.listen(0, '127.0.0.1', () => {
const port = wtServer.server.address().port;
serverBaseUrl = `http://127.0.0.1:${port}`;
resolve();
});
});
}
ipcMain.handle('search', async (_event, query, type) => {
try {
const q = (query || '').trim();
if (!q) return { error: 'Enter a search term.' };
if (type === 'movies') {
const movies = await searchMovies(q);
return { type: 'movies', results: movies };
}
if (type === 'tv') {
const shows = await searchTvShows(q);
return { type: 'tv', results: shows };
}