-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
6238 lines (5348 loc) · 255 KB
/
app.js
File metadata and controls
6238 lines (5348 loc) · 255 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, dialog, Menu, shell, Tray } = require('electron');
const express = require('express');
const cors = require('cors');
const path = require('path');
const { spawn, exec } = require('child_process');
const fs = require('fs').promises;
const fsSync = require('fs');
const crypto = require('crypto');
const { promisify } = require('util');
const execAsync = promisify(exec);
const multer = require('multer');
const { EventEmitter } = require('events');
const peerflix = require('peerflix');
const fetch = require('node-fetch');
// Official version manifest (checked on every page load via /api/version-manifest).
// If you fork FireFetch, update this to your repo’s raw URL.
const OFFICIAL_VERSION_MANIFEST_URL = process.env.FIREFETCH_VERSION_MANIFEST_URL
|| 'https://raw.githubusercontent.com/PyroSoftPro/FireFetch/main/public/version-manifest.json';
// Enhanced logging system
class Logger {
constructor() {
this.logFile = null;
this.logStream = null;
this.initPromise = null;
this.debugEnabled = false;
}
setDebugEnabled(enabled) {
this.debugEnabled = !!enabled;
}
async init(logDir) {
if (this.initPromise) return this.initPromise;
this.initPromise = this._initialize(logDir);
return this.initPromise;
}
async _initialize(logDir) {
try {
// Ensure log directory exists
await fs.mkdir(logDir, { recursive: true });
// Create log file with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
this.logFile = path.join(logDir, `firefetch-${timestamp}.log`);
// Create write stream
this.logStream = fsSync.createWriteStream(this.logFile, { flags: 'a' });
// Log session start
this.log('INFO', 'SYSTEM', 'FireFetch logging session started');
this.log('INFO', 'SYSTEM', `Log file: ${this.logFile}`);
this.log('INFO', 'SYSTEM', `Node version: ${process.version}`);
this.log('INFO', 'SYSTEM', `Platform: ${process.platform}`);
// Clean up old log files (keep last 10)
await this.cleanupOldLogs(logDir);
} catch (error) {
console.error('Failed to initialize logger:', error);
}
}
log(level, category, message, data = null) {
// Drop DEBUG logs unless explicitly enabled (default OFF for performance).
if (level === 'DEBUG' && !this.debugEnabled) {
return;
}
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
level,
category,
message,
data: data ? (typeof data === 'object' ? JSON.stringify(data, null, 2) : data) : null
};
// Format for file
let logLine = `[${timestamp}] [${level}] [${category}] ${message}`;
if (data) {
logLine += `\nData: ${logEntry.data}`;
}
logLine += '\n';
// Write to file if available
if (this.logStream) {
this.logStream.write(logLine);
}
// Also log to console with color coding
const consoleMessage = `[${category}] ${message}`;
switch (level) {
case 'ERROR':
console.error(consoleMessage, data || '');
break;
case 'WARN':
console.warn(consoleMessage, data || '');
break;
case 'DEBUG':
console.debug(consoleMessage, data || '');
break;
default:
console.log(consoleMessage, data || '');
}
}
async cleanupOldLogs(logDir) {
try {
const files = await fs.readdir(logDir);
const logFiles = files
.filter(file => file.startsWith('firefetch-') && file.endsWith('.log'))
.map(file => ({
name: file,
path: path.join(logDir, file),
stat: fsSync.statSync(path.join(logDir, file))
}))
.sort((a, b) => b.stat.mtime - a.stat.mtime);
// Keep only the 10 most recent log files
const filesToDelete = logFiles.slice(10);
for (const file of filesToDelete) {
try {
await fs.unlink(file.path);
console.log(`Deleted old log file: ${file.name}`);
} catch (error) {
console.warn(`Failed to delete log file ${file.name}:`, error.message);
}
}
} catch (error) {
console.warn('Failed to cleanup old logs:', error.message);
}
}
error(category, message, data) { this.log('ERROR', category, message, data); }
warn(category, message, data) { this.log('WARN', category, message, data); }
info(category, message, data) { this.log('INFO', category, message, data); }
debug(category, message, data) { this.log('DEBUG', category, message, data); }
close() {
if (this.logStream) {
this.logStream.end();
}
}
}
const logger = new Logger();
// Prevent multiple instances
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
return;
}
// Configuration
const BASE_PORT = 3000;
const MAX_PORT_TRIES = 50; // 3000..3049
let PORT = BASE_PORT; // chosen at runtime (auto-increments if taken)
let mainWindow;
let server;
let tray;
function getBaseUrl() {
return `http://localhost:${PORT}`;
}
async function listenWithPortFallback(expressApp, startPort = BASE_PORT, maxTries = MAX_PORT_TRIES) {
for (let i = 0; i < maxTries; i++) {
const port = startPort + i;
try {
const srv = await new Promise((resolve, reject) => {
const s = expressApp.listen(port, () => resolve(s));
s.once('error', reject);
});
PORT = port;
return srv;
} catch (err) {
const code = err?.code;
// Try the next port if the current one is taken / not bindable.
if (code === 'EADDRINUSE' || code === 'EACCES') continue;
throw err;
}
}
const lastPort = startPort + maxTries - 1;
throw new Error(`No available port found in range ${startPort}-${lastPort}`);
}
// Stream prefetch jobs (used by Search preview to "buffer to end" reliably)
// job: { id, status, filePath, createdAt, startedAt, finishedAt, bytesWritten, error, ffProc, pollTimer }
const streamPrefetchJobs = new Map();
// Determine base path for resources
let basePath;
let depPath;
let resourcesPath;
let userDataPath;
let isPortable = false;
// Debug mode: enables verbose logging. Default OFF for performance.
// Enable via:
// - env var: FIREFETCH_DEBUG=1
// - settings.json: { "debugLogging": true }
const DEBUG_LOGS = process.env.FIREFETCH_DEBUG === '1';
if (app.isPackaged) {
const exeDir = path.dirname(process.execPath);
// Electron Builder "portable" target sets this env var to the real location of the portable exe.
// This is more reliable than guessing based on Temp paths.
const portableExeDir = process.env.PORTABLE_EXECUTABLE_DIR;
if (portableExeDir && fsSync.existsSync(portableExeDir)) {
isPortable = true;
basePath = portableExeDir;
} else if (process.execPath.includes('\\Temp\\') || process.execPath.includes('/tmp/')) {
// Fallback for portable-style self-extracting runs when env vars are missing.
isPortable = true;
// Try to recover the original exe location if a marker exists.
const portableFile = path.join(app.getPath('appData'), app.getName(), '.portable');
if (fsSync.existsSync(portableFile)) {
try {
const content = fsSync.readFileSync(portableFile, 'utf8').trim();
if (content && fsSync.existsSync(content)) {
basePath = path.dirname(content);
}
} catch (e) {
basePath = exeDir;
}
} else {
basePath = exeDir;
}
} else {
basePath = exeDir;
}
// In this app, "userDataPath" is used for logs and other persisted files we keep next to basePath.
userDataPath = basePath;
// In packaged mode, use Electron's resourcesPath (works for installed + portable self-extracting runs).
resourcesPath = process.resourcesPath || path.join(exeDir, 'resources');
// dep folder location:
// - Prefer adjacent dep/ (allows user to override tools next to exe)
// - Else fall back to bundled dep/ inside resources
if (fsSync.existsSync(path.join(basePath, 'dep'))) {
depPath = path.join(basePath, 'dep');
} else if (resourcesPath && fsSync.existsSync(path.join(resourcesPath, 'dep'))) {
depPath = path.join(resourcesPath, 'dep');
} else {
depPath = path.join(basePath, 'dep');
}
} else {
// Development mode
basePath = __dirname;
resourcesPath = __dirname;
userDataPath = __dirname;
depPath = path.join(basePath, 'dep');
}
// Configure directories - always use paths relative to base
const cookiesDir = path.join(basePath, 'cookies');
const downloadsDir = path.join(basePath, 'downloads');
// Configure multer for cookie file uploads
const upload = multer({
dest: cookiesDir,
limits: { fileSize: 1024 * 1024 }, // 1MB limit
fileFilter: (req, file, cb) => {
if (file.mimetype === 'text/plain' || file.originalname.endsWith('.txt')) {
cb(null, true);
} else {
cb(new Error('Invalid file type. Please upload a .txt file'), false);
}
}
});
// Settings management
let settings = {
downloadDir: downloadsDir,
defaultQuality: 'best',
outputFormat: 'mp4',
saveMetadata: true,
connections: 16,
segments: 16,
segmentSize: '1M',
autoPlay: false,
cookieFile: null,
// Queue settings
maxConcurrentDownloads: 3,
queueEnabled: true,
retryAttempts: 2,
retryDelay: 5000,
// Torrent settings
torrentEngine: 'webtorrent', // 'webtorrent' or 'aria2c'
// Debug
debugLogging: false
};
// Get settings file path
function getSettingsPath() {
// Always use the basePath (exe directory for packaged apps)
return path.join(basePath, 'settings.json');
}
// If a persisted JSON file becomes corrupted, quarantine it so the app can recover on next launch.
async function quarantineCorruptJsonFile(filePath, label) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const quarantinedPath = `${filePath}.corrupt-${timestamp}`;
try {
await fs.rename(filePath, quarantinedPath);
console.warn(`[${label}] Corrupt JSON quarantined: ${quarantinedPath}`);
return quarantinedPath;
} catch (err) {
console.warn(`[${label}] Failed to quarantine corrupt JSON (${filePath}):`, err.message);
return null;
}
}
// Load settings from file if exists
async function loadSettings() {
try {
const settingsPath = getSettingsPath();
const data = await fs.readFile(settingsPath, 'utf8');
try {
const parsed = JSON.parse(data);
settings = { ...settings, ...parsed };
} catch (parseErr) {
console.warn('[SETTINGS] settings.json contains invalid JSON. Falling back to defaults.', parseErr.message);
await quarantineCorruptJsonFile(settingsPath, 'SETTINGS');
}
} catch (err) {
if (err.code !== 'ENOENT') {
console.warn('[SETTINGS] Failed to read settings.json. Falling back to defaults.', err.message);
}
}
}
function syncLoggerDebugSetting() {
// Environment variable wins (useful for ad-hoc debugging without touching settings.json)
const enabled = DEBUG_LOGS || !!settings?.debugLogging;
logger.setDebugEnabled(enabled);
}
// Create downloads directory if it doesn't exist
async function ensureDownloadsDir() {
try {
const dir = settings.downloadDir;
await fs.mkdir(dir, { recursive: true });
console.log('Downloads directory:', dir);
} catch (err) {
console.error('Error creating downloads directory:', err);
}
}
// Ensure cookies directory exists
async function ensureCookiesDir() {
try {
await fs.mkdir(cookiesDir, { recursive: true });
console.log('Cookies directory:', cookiesDir);
} catch (err) {
console.error('Error creating cookies directory:', err);
}
}
// Safely resolve a user-provided (possibly relative) path within a base directory.
// Prevents path traversal like "../../Windows/system.ini".
function resolvePathInsideDir(baseDir, userPath) {
const baseAbs = path.resolve(baseDir);
const targetAbs = path.resolve(baseAbs, userPath);
const rel = path.relative(baseAbs, targetAbs);
if (rel.startsWith('..') || path.isAbsolute(rel)) {
const err = new Error('Invalid path');
err.code = 'INVALID_PATH';
throw err;
}
return targetAbs;
}
// Normalize YouTube URLs to extract video ID when playlist parameters are present
function normalizeYouTubeUrl(url) {
try {
const urlObj = new URL(url);
const hostname = urlObj.hostname.toLowerCase();
// Check if this is a YouTube URL
if (!hostname.includes('youtube.com') && !hostname.includes('youtu.be')) {
return url; // Not a YouTube URL, return as-is
}
let videoId = null;
// Handle youtube.com/watch?v=VIDEO_ID format
if (hostname.includes('youtube.com') && urlObj.pathname.includes('/watch')) {
videoId = urlObj.searchParams.get('v');
}
// Handle youtu.be/VIDEO_ID format
else if (hostname.includes('youtu.be')) {
videoId = urlObj.pathname.substring(1); // Remove leading slash
}
// If we found a video ID, reconstruct a clean URL
if (videoId && videoId.length === 11) { // YouTube video IDs are 11 characters
return `https://www.youtube.com/watch?v=${videoId}`;
}
// If no valid video ID found, return original URL
return url;
} catch (error) {
// If URL parsing fails, return original URL
return url;
}
}
// Utility function to detect if URL is a direct file download
function isDirectFileDownload(url) {
try {
const urlObj = new URL(url);
const pathname = urlObj.pathname.toLowerCase();
// Comprehensive list of file extensions that should be downloaded directly
const fileExtensions = [
// Executables & Installers
'.exe', '.msi', '.bat', '.cmd', '.com', '.scr', '.pif',
'.dmg', '.pkg', '.app', '.bundle',
'.deb', '.rpm', '.appimage', '.snap', '.flatpak', '.tar.xz',
'.apk', '.ipa', '.xap', '.aab',
// Archives & Compressed Files
'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.lz', '.z',
'.ace', '.arj', '.cab', '.lha', '.lzh', '.zoo', '.arc', '.pak',
'.sit', '.sitx', '.sea', '.hqx', '.cpt', '.pit', '.pf',
'.tar.gz', '.tar.bz2', '.tar.xz', '.tar.lz', '.tgz', '.tbz2',
// Documents
'.pdf', '.ps', '.eps',
'.doc', '.docx', '.dot', '.dotx', '.docm', '.dotm',
'.xls', '.xlsx', '.xlt', '.xltx', '.xlsm', '.xltm', '.xlsb',
'.ppt', '.pptx', '.pot', '.potx', '.pptm', '.potm', '.ppsx', '.ppsm',
'.odt', '.ods', '.odp', '.odg', '.odf', '.odb', '.odc', '.odm',
'.rtf', '.wpd', '.wps', '.pages', '.numbers', '.key',
'.txt', '.text', '.log', '.md', '.markdown', '.rst', '.asciidoc',
'.csv', '.tsv', '.json', '.xml', '.yaml', '.yml', '.toml', '.ini', '.cfg', '.conf',
// Images
'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.tif',
'.svg', '.webp', '.ico', '.icns', '.cur', '.ani',
'.psd', '.ai', '.eps', '.cdr', '.xcf', '.sketch',
'.raw', '.cr2', '.nef', '.arw', '.dng', '.orf', '.rw2',
'.heic', '.heif', '.avif', '.jp2', '.jpx', '.j2k',
// Audio
'.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a', '.opus',
'.aiff', '.au', '.ra', '.3gp', '.amr', '.awb', '.dss', '.dvf',
'.m4b', '.m4p', '.mmf', '.mpc', '.msv', '.oga', '.raw', '.sln',
'.tta', '.voc', '.vox', '.wv', '.webm', '.8svx', '.cda',
// Video
'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v',
'.3gp', '.3g2', '.asf', '.divx', '.f4v', '.m2v', '.m4p', '.m4v',
'.mj2', '.mjpeg', '.mng', '.mp2', '.mpe', '.mpeg', '.mpg', '.mpv',
'.mts', '.mxf', '.nsv', '.nuv', '.ogm', '.ogv', '.ps', '.rec',
'.rm', '.rmvb', '.tod', '.ts', '.vob', '.vro', '.y4m',
// Fonts
'.ttf', '.otf', '.woff', '.woff2', '.eot', '.fon', '.fnt', '.bdf',
'.pcf', '.snf', '.pfb', '.pfm', '.afm', '.ttc', '.otc',
// 3D Models & CAD
'.obj', '.fbx', '.dae', '.3ds', '.blend', '.max', '.ma', '.mb',
'.c4d', '.lwo', '.lws', '.x3d', '.ply', '.stl', '.off', '.dxf',
'.dwg', '.step', '.stp', '.iges', '.igs', '.sat', '.brep',
// Disk Images & Virtual Machines
'.iso', '.img', '.dmg', '.nrg', '.cue', '.bin', '.mds', '.ccd',
'.vhd', '.vhdx', '.vmdk', '.vdi', '.qcow2', '.raw', '.cow',
'.ova', '.ovf', '.vbox', '.vbox-prev',
// Database
'.db', '.sqlite', '.sqlite3', '.mdb', '.accdb', '.dbf', '.odb',
'.frm', '.myd', '.myi', '.ibd', '.bak', '.sql', '.dump',
// Code & Development
'.c', '.cpp', '.h', '.hpp', '.cc', '.cxx', '.c++',
'.java', '.class', '.jar', '.war', '.ear',
'.py', '.pyc', '.pyo', '.pyd', '.pyw', '.pyz', '.pyzw',
'.js', '.ts', '.jsx', '.tsx', '.vue', '.svelte',
'.php', '.phtml', '.php3', '.php4', '.php5', '.phps',
'.rb', '.rbw', '.gem', '.rake',
'.go', '.rs', '.swift', '.kt', '.kts', '.scala', '.clj', '.cljs',
'.pl', '.pm', '.pod', '.t', '.psgi',
'.sh', '.bash', '.zsh', '.fish', '.csh', '.tcsh', '.ksh',
'.ps1', '.psm1', '.psd1', '.ps1xml', '.psc1', '.pssc',
'.r', '.rdata', '.rds', '.rda',
'.m', '.mat', '.fig', '.p', '.mex',
'.asm', '.s', '.nas', '.inc',
// Web & Markup
'.html', '.htm', '.xhtml', '.mhtml', '.hta',
'.css', '.scss', '.sass', '.less', '.styl',
'.xsl', '.xslt', '.dtd', '.xsd', '.wsdl',
// Ebooks
'.epub', '.mobi', '.azw', '.azw3', '.kf8', '.kfx', '.prc',
'.fb2', '.lit', '.lrf', '.pdb', '.pml', '.rb', '.tcr',
// GIS & Maps
'.shp', '.kml', '.kmz', '.gpx', '.gdb', '.mxd', '.qgs',
'.geojson', '.topojson', '.osm', '.pbf',
// Game Files
'.rom', '.sav', '.st', '.srm', '.fc', '.nes', '.smc', '.sfc',
'.gb', '.gbc', '.gba', '.nds', '.3ds', '.cia', '.wad',
'.pak', '.vpk', '.gcf', '.ncf', '.vdf', '.acf',
// Scientific & Academic
'.nc', '.hdf', '.h5', '.fits', '.fts', '.cdf', '.grib', '.bufr',
'.las', '.laz', '.e57', '.ply', '.xyz', '.pcd',
// Cryptocurrency & Blockchain
'.wallet', '.dat', '.key', '.p12', '.pfx', '.pem', '.crt', '.cer',
// Backup & System
'.bak', '.backup', '.old', '.orig', '.save', '.tmp', '.temp',
'.part', '.crdownload', '.download', '.filepart',
'.dmp', '.core', '.crash', '.etl', '.evtx',
// Misc Binary & Data
'.bin', '.dat', '.data', '.raw', '.hex', '.dump', '.blob',
'.cache', '.lock', '.pid', '.sock', '.fifo', '.device'
];
return fileExtensions.some(ext => pathname.endsWith(ext));
} catch {
return false;
}
}
// URL Resolution Function
async function resolveUrlAndDetermineMethod(url, options = {}) {
const { timeout = 30000, followRedirects = 10, userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } = options;
logger.log('INFO', 'URL_RESOLVER', `Starting URL resolution for: ${url}`);
try {
// Quick check for obvious cases first
if (url.startsWith('magnet:')) {
logger.log('INFO', 'URL_RESOLVER', `Detected magnet link: ${url}`);
return {
originalUrl: url,
resolvedUrl: url,
method: 'aria2c',
type: 'magnet',
title: 'Magnet Link Download',
reason: 'Magnet URI detected'
};
}
// Check if yt-dlp can handle this URL first (faster than HTTP requests)
const ytDlpSupported = await checkYtDlpSupport(url);
if (ytDlpSupported.supported) {
logger.log('INFO', 'URL_RESOLVER', `yt-dlp supports this URL: ${url}`);
return {
originalUrl: url,
resolvedUrl: url,
method: 'yt-dlp',
type: 'video',
title: ytDlpSupported.title || 'Video Download',
reason: `Supported by yt-dlp (${ytDlpSupported.extractor})`
};
}
// Perform HTTP HEAD request to resolve redirects and check content
const resolvedInfo = await performHttpResolution(url, { timeout, followRedirects, userAgent });
// Analyze the resolved URL and response
const analysis = analyzeResolvedUrl(resolvedInfo);
logger.log('INFO', 'URL_RESOLVER', `URL resolved: ${url} -> ${resolvedInfo.finalUrl}, Method: ${analysis.method}, Type: ${analysis.type}`);
return {
originalUrl: url,
resolvedUrl: resolvedInfo.finalUrl,
method: analysis.method,
type: analysis.type,
title: analysis.title,
reason: analysis.reason,
contentType: resolvedInfo.contentType,
contentLength: resolvedInfo.contentLength,
redirectChain: resolvedInfo.redirectChain
};
} catch (error) {
logger.log('ERROR', 'URL_RESOLVER', `Failed to resolve URL: ${url}`, error);
// Fallback: if resolution fails, default to yt-dlp for URLs that look like media sites
const isLikelyVideo = /\b(youtube|youtu\.be|vimeo|dailymotion|twitch|tiktok|instagram|facebook|twitter|reddit)\b/i.test(url);
return {
originalUrl: url,
resolvedUrl: url,
method: isLikelyVideo ? 'yt-dlp' : 'aria2c',
type: isLikelyVideo ? 'video' : 'file',
title: isLikelyVideo ? 'Video Download' : 'File Download',
reason: `Resolution failed, fallback to ${isLikelyVideo ? 'yt-dlp' : 'aria2c'} (${error.message})`,
error: error.message
};
}
}
// Check if yt-dlp supports the URL
async function checkYtDlpSupport(url) {
return new Promise((resolve) => {
// Normalize YouTube URLs to handle playlist parameters correctly
const normalizedUrl = normalizeYouTubeUrl(url);
const ytDlpPath = path.join(depPath, 'yt-dlp.exe');
const args = ['--dump-json', '--no-warnings', '--skip-download', '--no-playlist', normalizedUrl];
let ytDlpProc = null;
let settled = false;
let timeoutId = null;
const finish = (result) => {
if (settled) return;
settled = true;
if (timeoutId) clearTimeout(timeoutId);
resolve(result);
};
timeoutId = setTimeout(() => {
try {
if (ytDlpProc && !ytDlpProc.killed) {
ytDlpProc.kill(); // SIGTERM by default (works cross-platform)
}
} catch (e) {
// Ignore kill errors (e.g. already exited)
}
finish({ supported: false, reason: 'Timeout' });
}, 15000);
ytDlpProc = spawn(ytDlpPath, args);
let output = '';
let errorOutput = '';
ytDlpProc.stdout.on('data', (data) => {
output += data.toString();
});
ytDlpProc.stderr.on('data', (data) => {
errorOutput += data.toString();
});
ytDlpProc.on('error', (err) => {
finish({ supported: false, reason: 'Spawn failed', error: err.message });
});
ytDlpProc.on('close', (code) => {
if (code === 0 && output.trim()) {
try {
const info = JSON.parse(output.trim().split('\n')[0]);
finish({
supported: true,
title: info.title,
extractor: info.extractor || info.ie_key,
duration: info.duration
});
} catch (e) {
finish({ supported: false, reason: 'Invalid JSON response' });
}
} else {
finish({
supported: false,
reason: errorOutput.includes('Unsupported URL') ? 'Unsupported site' : 'Unknown error',
error: errorOutput
});
}
});
});
}
// Perform HTTP resolution with redirect following
async function performHttpResolution(url, options) {
const https = require('https');
const http = require('http');
const { URL } = require('url');
const { timeout, followRedirects, userAgent } = options;
let redirectCount = 0;
let currentUrl = url;
const redirectChain = [url];
return new Promise((resolve, reject) => {
const makeRequest = (requestUrl) => {
const urlObj = new URL(requestUrl);
const isHttps = urlObj.protocol === 'https:';
const client = isHttps ? https : http;
const requestOptions = {
hostname: urlObj.hostname,
port: urlObj.port || (isHttps ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: 'HEAD',
headers: {
'User-Agent': userAgent,
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close'
},
timeout: timeout
};
const req = client.request(requestOptions, (res) => {
const { statusCode, headers } = res;
// Handle redirects
if (statusCode >= 300 && statusCode < 400 && headers.location) {
if (redirectCount >= followRedirects) {
return reject(new Error(`Too many redirects (${redirectCount})`));
}
redirectCount++;
currentUrl = new URL(headers.location, requestUrl).href;
redirectChain.push(currentUrl);
return makeRequest(currentUrl);
}
// Success response
if (statusCode >= 200 && statusCode < 300) {
resolve({
finalUrl: currentUrl,
statusCode,
contentType: headers['content-type'] || '',
contentLength: headers['content-length'] ? parseInt(headers['content-length']) : null,
redirectChain,
headers
});
} else {
reject(new Error(`HTTP ${statusCode}: ${res.statusMessage}`));
}
res.resume(); // Consume response
});
req.on('timeout', () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.on('error', (error) => {
reject(error);
});
req.end();
};
makeRequest(currentUrl);
});
}
// Analyze resolved URL to determine best download method
function analyzeResolvedUrl(resolvedInfo) {
const { finalUrl, contentType, contentLength } = resolvedInfo;
const url = finalUrl.toLowerCase();
const content = contentType.toLowerCase();
// Check for torrent files
if (url.includes('.torrent') || content.includes('application/x-bittorrent')) {
return {
method: 'aria2c',
type: 'torrent',
title: 'Torrent File Download',
reason: 'Torrent file detected'
};
}
// Check for video/audio content types
if (content.includes('video/') || content.includes('audio/')) {
return {
method: 'aria2c',
type: 'file',
title: 'Media File Download',
reason: `Media content type: ${contentType}`
};
}
// Check for large files that are likely downloads
if (contentLength && contentLength > 50 * 1024 * 1024) { // 50MB+
return {
method: 'aria2c',
type: 'file',
title: 'Large File Download',
reason: `Large file detected (${Math.round(contentLength / 1024 / 1024)}MB)`
};
}
// Check for common file extensions in URL
const fileExtensions = ['.zip', '.rar', '.7z', '.tar', '.gz', '.exe', '.msi', '.dmg', '.pkg',
'.deb', '.rpm', '.appimage', '.iso', '.img', '.bin', '.apk', '.ipa'];
for (const ext of fileExtensions) {
if (url.includes(ext)) {
return {
method: 'aria2c',
type: 'file',
title: 'File Download',
reason: `File extension detected: ${ext}`
};
}
}
// Check for direct file downloads based on URL patterns
if (isDirectFileDownload(finalUrl)) {
return {
method: 'aria2c',
type: 'file',
title: 'Direct File Download',
reason: 'Direct file URL pattern detected'
};
}
// Default to yt-dlp for everything else (web pages, streaming sites, etc.)
return {
method: 'yt-dlp',
type: 'video',
title: 'Video/Media Download',
reason: 'Default to yt-dlp for web content'
};
}
// Download Manager Class
class DownloadManager extends EventEmitter {
constructor() {
super();
this.queue = [];
this.activeDownloads = new Map();
this.completedDownloads = [];
this.clients = new Set(); // SSE clients
this.nextId = 1;
// Initialize queue settings
this.queueEnabled = true;
this.maxRetries = 2;
this.lastBroadcast = 0; // For throttled updates
this.minBroadcastIntervalMs = 250; // 4 updates/sec max by default (smooth enough, reduces UI churn)
// Console logging throttling
this.lastConsoleLog = new Map(); // Track last log time per download
this.consoleLogThrottle = 5000; // Only log every 5 seconds per download
}
// Generate unique download ID
generateId() {
return `download_${this.nextId++}_${Date.now()}`;
}
// Throttled console logging to prevent UI lag
throttledLog(downloadId, ...args) {
const now = Date.now();
const lastLog = this.lastConsoleLog.get(downloadId) || 0;
if (now - lastLog >= this.consoleLogThrottle) {
console.log(...args);
this.lastConsoleLog.set(downloadId, now);
}
}
// Clean up console log tracking for completed downloads
cleanupThrottledLogging(downloadId) {
this.lastConsoleLog.delete(downloadId);
}
// Add download to queue
addToQueue(url, format, title = null, resolvedMethod = null, resolvedType = null, metadata = null) {
// Use resolved method if provided, otherwise detect download type
let downloadType;
if (resolvedMethod && resolvedType) {
// Use the resolved method/type from URL resolution
console.log(`[QUEUE] Using resolved method: ${resolvedMethod}, type: ${resolvedType}`);
if (resolvedType === 'magnet') {
downloadType = 'magnet';
} else if (resolvedType === 'torrent') {
downloadType = 'torrent';
} else if (resolvedMethod === 'aria2c') {
downloadType = 'file';
} else {
downloadType = 'video'; // yt-dlp
}
} else {
// Fallback to original detection logic
const isMagnet = url.startsWith('magnet:');
const isTorrent = url.toLowerCase().endsWith('.torrent');
// Check if URL is a direct file download based on extension
const isDirectFile = isDirectFileDownload(url);
if (isMagnet) {
downloadType = 'magnet';
} else if (isTorrent) {
downloadType = 'torrent';
} else if (isDirectFile) {
downloadType = 'file';
} else {
// If not a direct file, assume it's a video/media site and let yt-dlp try to handle it
// yt-dlp supports 1000+ sites, so we default to 'video' and let it determine capability
downloadType = 'video';
}
}
console.log(`[QUEUE] Adding download - URL: ${url}`);
console.log(`[QUEUE] Detection - method: ${resolvedMethod || 'auto'}, type: ${downloadType}`);
const download = {
id: this.generateId(),
url,
format,
title: title || (downloadType === 'video' ? url : `${downloadType.charAt(0).toUpperCase() + downloadType.slice(1)} Download`),
// Optional metadata (useful for nicer UI in Downloads/Queue)
thumbnail: metadata?.thumbnail || null,
webpage_url: metadata?.webpage_url || null,
extractor: metadata?.extractor || null,
status: 'queued',
progress: 0,
speed: null,
eta: null,
size: null,
error: null,
addedAt: new Date(),
startedAt: null,
completedAt: null,
retryCount: 0,
process: null,
downloadType: downloadType,
// Torrent-specific fields (consistent for both magnet and .torrent)
uploadSpeed: null,
seeds: null,
leechers: null,
peers: 0, // Initialize to 0 instead of null for consistent display
ratio: null
};
console.log(`[QUEUE] Created download object:`, {
id: download.id,
url: download.url,
downloadType: download.downloadType,
format: download.format
});
this.queue.push(download);
this.emit('queueUpdated');
this.broadcastUpdate();
this.autoSaveState(); // Save state after adding to queue
// Always process queue if enabled (autoStart should be true by default)
if (this.queueEnabled) {
this.processQueue();
}
return download.id;
}
// Process the queue
processQueue() {
if (!this.queueEnabled) {
console.log('[QUEUE] Queue processing disabled');
return;
}
// Use global settings for max concurrent downloads
const maxConcurrent = settings.maxConcurrentDownloads || 3;
const activeCount = this.activeDownloads.size;
let activeTorrentCount = Array.from(this.activeDownloads.values()).filter(d => d.downloadType === 'torrent' || d.downloadType === 'magnet').length;
console.log(`[QUEUE] Processing queue - Active: ${activeCount}/${maxConcurrent} (${activeTorrentCount} torrents), Queued: ${this.queue.filter(d => d.status === 'queued').length}`);
if (activeCount >= maxConcurrent) {
console.log('[QUEUE] Max concurrent downloads reached');
return;
}
// Limit torrents to prevent resource exhaustion (max 2 concurrent torrents)
const nextTorrent = this.queue.find(d => d.status === 'queued' && (d.downloadType === 'torrent' || d.downloadType === 'magnet'));
if (nextTorrent && activeTorrentCount >= 2) {
console.log('[QUEUE] Max concurrent torrents reached (2), prioritizing video downloads');
// Continue to start video downloads instead
}
// Prioritize video downloads when torrent limit is reached
let queuedDownloads = this.queue.filter(d => d.status === 'queued');
if (activeTorrentCount >= 2) {
// Prioritize video downloads over torrents
queuedDownloads = queuedDownloads.filter(d => d.downloadType !== 'torrent' && d.downloadType !== 'magnet')
.concat(queuedDownloads.filter(d => d.downloadType === 'torrent' || d.downloadType === 'magnet'));