-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
386 lines (330 loc) Β· 13.9 KB
/
server.js
File metadata and controls
386 lines (330 loc) Β· 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
const express = require('express');
const axios = require('axios');
const ytdl = require('@distube/ytdl-core');
const fs = require('fs');
const path = require('path');
const http = require('http');
const WebSocket = require('ws');
const os = require('os');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const PORT = 3000;
const downloads = new Map();
// Middleware
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.static(path.join(__dirname, 'src/renderer')));
// Request Logger
app.use((req, res, next) => {
console.log(`[${new Date().toLocaleTimeString()}] ${req.method} ${req.url}`);
next();
});
// WebSocket for real-time updates
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log('Received:', message);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
// Broadcast to all connected clients
function broadcast(data) {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
}
// Routes
app.get('/api/downloads', (req, res) => {
const downloadList = Array.from(downloads.values());
res.json(downloadList);
});
app.post('/api/download', async (req, res) => {
const { url, filename, savePath, chunks = 4 } = req.body;
const downloadId = Date.now().toString();
const download = {
id: downloadId,
url,
filename,
savePath: savePath || path.join(os.homedir(), 'Downloads'),
progress: 0,
speed: 0,
status: 'downloading',
totalSize: 0,
downloadedSize: 0,
chunks,
createdAt: new Date().toISOString()
};
downloads.set(downloadId, download);
// Start download
startDownload(download);
res.json(download);
});
app.post('/api/download/:id/pause', (req, res) => {
const download = downloads.get(req.params.id);
if (download) {
download.status = 'paused';
download.cancelToken?.cancel('Download paused by user');
broadcast({ type: 'download-update', download });
res.json(download);
} else {
res.status(404).json({ error: 'Download not found' });
}
});
app.post('/api/download/:id/resume', (req, res) => {
const download = downloads.get(req.params.id);
if (download) {
download.status = 'downloading';
startDownload(download);
broadcast({ type: 'download-update', download });
res.json(download);
} else {
res.status(404).json({ error: 'Download not found' });
}
});
app.delete('/api/download/:id', (req, res) => {
const download = downloads.get(req.params.id);
if (download) {
download.cancelToken?.cancel('Download cancelled by user');
const filePath = path.join(download.savePath, download.filename);
if (fs.existsSync(filePath)) {
try {
fs.unlinkSync(filePath);
} catch (err) {
console.error('Error deleting file:', err);
}
}
downloads.delete(req.params.id);
broadcast({ type: 'download-deleted', id: req.params.id });
res.json({ success: true });
} else {
res.status(404).json({ error: 'Download not found' });
}
});
// Download function
async function startDownload(download) {
const isYouTube = ytdl.validateURL(download.url);
if (isYouTube) {
return handleYouTubeDownload(download);
}
try {
const cancelTokenSource = axios.CancelToken.source();
download.cancelToken = cancelTokenSource;
const startTime = Date.now();
let lastLoaded = 0;
let lastTime = startTime;
const response = await axios({
method: 'GET',
url: download.url,
responseType: 'stream',
cancelToken: cancelTokenSource.token,
onDownloadProgress: (progressEvent) => {
const currentDownload = downloads.get(download.id);
if (currentDownload && currentDownload.status === 'downloading') {
const currentTime = Date.now();
const timeDiff = (currentTime - lastTime) / 1000; // seconds
const loadedDiff = progressEvent.loaded - lastLoaded;
// Calculate speed in KB/s
const speed = timeDiff > 0 ? (loadedDiff / 1024) / timeDiff : 0;
currentDownload.downloadedSize = progressEvent.loaded;
currentDownload.totalSize = progressEvent.total || progressEvent.loaded;
currentDownload.progress = progressEvent.total
? Math.round((progressEvent.loaded / progressEvent.total) * 100)
: 0;
currentDownload.speed = Math.round(speed);
lastLoaded = progressEvent.loaded;
lastTime = currentTime;
// Broadcast progress
broadcast({ type: 'download-progress', download: currentDownload });
}
}
});
// Ensure directory exists
const downloadDir = download.savePath;
if (!fs.existsSync(downloadDir)) {
fs.mkdirSync(downloadDir, { recursive: true });
}
const filePath = path.join(downloadDir, download.filename);
const writer = fs.createWriteStream(filePath);
response.data.pipe(writer);
writer.on('finish', () => {
const currentDownload = downloads.get(download.id);
if (currentDownload) {
currentDownload.status = 'completed';
currentDownload.progress = 100;
currentDownload.speed = 0;
broadcast({ type: 'download-complete', download: currentDownload });
}
});
writer.on('error', (error) => {
const currentDownload = downloads.get(download.id);
if (currentDownload) {
currentDownload.status = 'error';
currentDownload.error = error.message;
currentDownload.speed = 0;
broadcast({ type: 'download-error', download: currentDownload });
}
});
} catch (error) {
if (!axios.isCancel(error)) {
const currentDownload = downloads.get(download.id);
if (currentDownload) {
currentDownload.status = 'error';
currentDownload.error = error.message;
currentDownload.speed = 0;
broadcast({ type: 'download-error', download: currentDownload });
}
}
}
}
const { spawn } = require('child_process');
async function handleYouTubeDownload(download) {
try {
// 1. Get info first to get the title asynchronously
let titleData = 'youtube_video';
try {
titleData = await new Promise((resolve, reject) => {
const titleProcess = spawn('yt-dlp', [
'--get-title',
'--no-check-certificate',
'--force-ipv4',
'--no-cache-dir',
'--extractor-args', 'youtube:player-client=web_creator,ios,web;formats=missing_pot',
download.url
]);
let result = '';
const timeout = setTimeout(() => {
titleProcess.kill();
resolve('youtube_video');
}, 20000); // 20s timeout
titleProcess.stdout.on('data', (data) => { result += data.toString(); });
titleProcess.on('close', (code) => {
clearTimeout(timeout);
if (code === 0 && result.trim()) resolve(result.trim());
else resolve('youtube_video');
});
});
} catch (e) {
console.warn('Title fetch failed, using fallback.');
}
download.filename = `${titleData.replace(/[^a-z0-9]/gi, '_')}.mp4`;
console.log(`π Prepared filename: ${download.filename}`);
const downloadDir = download.savePath;
if (!fs.existsSync(downloadDir)) fs.mkdirSync(downloadDir, { recursive: true });
const filePath = path.join(downloadDir, download.filename);
// 2. Start the process with Super Robust Mode (Native Downloader)
// We disabled aria2c for YouTube because it often causes 'fragment missing' errors on VPNs
const process = spawn('yt-dlp', [
'-f', 'bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4] / bv*+ba/b',
'--newline',
'--no-playlist',
'--no-check-certificate',
'--force-ipv4',
'--no-cache-dir',
'--socket-timeout', '30',
'--retries', '20',
'--fragment-retries', '20',
'--extractor-args', 'youtube:player-client=web_creator,ios,web;formats=missing_pot',
'--user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'--progress-template', 'IDM:%(progress._percent_str)s|%(progress._speed_str)s|%(progress._total_bytes_estimate_str)s',
'-o', filePath,
download.url
]);
let lastProgressLog = -1;
process.stdout.on('data', (data) => {
const line = data.toString();
if (line.includes('IDM:')) {
const parts = line.split('IDM:')[1].split('|');
const percentStr = parts[0].replace('%', '').trim();
const percent = parseFloat(percentStr);
const speedStr = parts[1];
const estimateSizeStr = parts[2];
download.progress = Math.round(percent);
download.status = 'downloading';
// Parse speed
if (speedStr.includes('k')) download.speed = parseFloat(speedStr);
else if (speedStr.includes('M')) download.speed = parseFloat(speedStr) * 1024;
else download.speed = parseFloat(speedStr) || 0;
// Parse total size estimate if possible
if (estimateSizeStr && estimateSizeStr !== 'NA') {
if (estimateSizeStr.includes('MiB')) download.totalSize = parseFloat(estimateSizeStr) * 1024 * 1024;
else if (estimateSizeStr.includes('GiB')) download.totalSize = parseFloat(estimateSizeStr) * 1024 * 1024 * 1024;
else if (estimateSizeStr.includes('KiB')) download.totalSize = parseFloat(estimateSizeStr) * 1024;
else download.totalSize = parseFloat(estimateSizeStr) || 0;
download.downloadedSize = (download.totalSize * (percent / 100));
}
broadcast({ type: 'download-progress', download });
// Log every 10%
if (Math.floor(percent / 10) > lastProgressLog) {
lastProgressLog = Math.floor(percent / 10);
console.log(`β³ Download progress [${download.id}]: ${download.progress}% @ ${speedStr}`);
}
}
});
process.stderr.on('data', (data) => {
const msg = data.toString();
if (msg.includes('ERROR')) {
console.error(`β YT-DLP ERROR [${download.id}]:`, msg.trim());
} else {
// Warnings/Progress logs
if (!msg.includes('%')) console.log(`β οΈ YT-DLP Info [${download.id}]:`, msg.trim());
}
});
process.on('close', (code) => {
if (code === 0) {
console.log(`β
Download completed successfully [${download.id}]: ${download.filename}`);
download.status = 'completed';
download.progress = 100;
download.speed = 0;
broadcast({ type: 'download-complete', download });
} else {
console.error(`β YT-DLP process exited with code ${code} [${download.id}]`);
download.status = 'error';
download.error = `yt-dlp exited with code ${code}. YouTube might be blocking the request.`;
broadcast({ type: 'download-error', download });
}
});
} catch (err) {
console.error('YouTube/YT-DLP Error:', err);
download.status = 'error';
download.error = `Download failed: ${err.message}`;
broadcast({ type: 'download-error', download });
}
}
// Start server
server.listen(PORT, () => {
console.log('\nπ Linux IDM Web Server Started!');
console.log('ββββββββββββββββββββββββββββββββββββββββ');
console.log(`\nβ
Server running at: http://localhost:${PORT}`);
console.log(`\nπ Default download location: ${path.join(os.homedir(), 'Downloads')}`);
console.log('\nπ‘ Open your browser and navigate to the URL above');
console.log('\nββββββββββββββββββββββββββββββββββββββββ\n');
// Try to open browser automatically (skip if running in background)
const isBackground = process.argv.includes('--background');
if (!isBackground) {
const open = require('child_process').exec;
const url = `http://localhost:${PORT}`;
const start = process.platform === 'darwin' ? 'open' :
process.platform === 'win32' ? 'start' : 'xdg-open';
setTimeout(() => {
open(`${start} ${url}`, (error) => {
if (error) {
console.log('π‘ Please manually open: http://localhost:3000');
}
});
}, 1000);
}
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\n\nπ Shutting down Linux IDM...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});