-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathmediaProxy.js
More file actions
594 lines (512 loc) · 21.9 KB
/
mediaProxy.js
File metadata and controls
594 lines (512 loc) · 21.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import {base64Decode, md5} from '../libs_drpy/crypto-util.js';
import '../utils/random-http-ua.js'
import {keysToLowerCase} from '../utils/utils.js';
import {ENV} from "../utils/env.js";
import chunkStream, {testSupport} from '../utils/chunk.js';
import createAxiosInstance from '../utils/createAxiosAgent.js';
// 全局资源管理器
const globalResourceManager = {
activeStreams: new Set(),
activeRequests: new Set(),
addStream: function(stream) {
this.activeStreams.add(stream);
stream.on('close', () => this.activeStreams.delete(stream));
stream.on('end', () => this.activeStreams.delete(stream));
stream.on('error', () => this.activeStreams.delete(stream));
},
addRequest: function(requestId) {
this.activeRequests.add(requestId);
},
removeRequest: function(requestId) {
this.activeRequests.delete(requestId);
},
cleanup: function() {
// 清理所有活跃的流
this.activeStreams.forEach(stream => {
if (stream && !stream.destroyed) {
stream.destroy();
}
});
this.activeStreams.clear();
this.activeRequests.clear();
},
getStats: function() {
return {
activeStreams: this.activeStreams.size,
activeRequests: this.activeRequests.size,
memoryUsage: process.memoryUsage()
};
}
};
// 定期清理和内存监控
setInterval(() => {
const stats = globalResourceManager.getStats();
if (stats.activeStreams > 50 || stats.activeRequests > 100) {
console.warn('[MediaProxy] High resource usage detected:', stats);
}
// 强制垃圾回收(如果可用)
if (global.gc && stats.memoryUsage.heapUsed > 500 * 1024 * 1024) { // 500MB
global.gc();
console.log('[MediaProxy] Forced garbage collection due to high memory usage');
}
}, 30000); // 每30秒检查一次
const maxSockets = 32; // 减少最大连接数以防止连接池过大
const _axios = createAxiosInstance({
maxSockets: maxSockets,
rejectUnauthorized: true, // 不忽略证书错误
keepAlive: true,
keepAliveMsecs: 30000, // 30秒保持连接
maxFreeSockets: 10, // 最大空闲连接数
timeout: 30000, // 30秒超时
freeSocketTimeout: 15000, // 空闲连接超时时间
},
);
export default (fastify, options, done) => {
// 用法同 https://github.com/Zhu-zi-a/mediaProxy
fastify.all('/mediaProxy', async (request, reply) => {
const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
globalResourceManager.addRequest(requestId);
// 请求完成时清理
const cleanup = () => {
globalResourceManager.removeRequest(requestId);
};
// 监听请求结束事件
request.raw.on('close', cleanup);
request.raw.on('aborted', cleanup);
reply.raw.on('finish', cleanup);
reply.raw.on('close', cleanup);
const {thread = 1, form = 'urlcode', url, header, size = '128K', randUa = 0} = request.query;
// console.log('url:', url)
// console.log('header:', header)
// Check if the URL parameter is missing
if (!url) {
cleanup();
return reply.code(400).send({error: 'Missing required parameter: url'});
}
try {
// Decode URL and headers based on the form type
const decodedUrl = form === 'base64' ? base64Decode(url) : url;
const decodedHeader = header
? JSON.parse(form === 'base64' ? base64Decode(header) : header)
: {};
// Call the proxy function, passing the decoded URL and headers
// return await proxyStreamMediaMulti(decodedUrl, decodedHeader, request, reply, thread, size, randUa);
// return await chunkStream(request, reply, decodedUrl, ids[1], Object.assign({Cookie: cookie}, baseHeader));
if (ENV.get('play_proxy_mode', '1') !== '2') { // 2磁盘加速 其他都是内存加速
console.log('[mediaProxy] proxyStreamMediaMulti 内存加速:chunkSize:', sizeToBytes(size));
return await proxyStreamMediaMulti(decodedUrl, decodedHeader, request, reply, thread, size, randUa);
} else {
console.log('[mediaProxy] chunkStream 磁盘加速 chunkSize:', sizeToBytes('256K'));
return await chunkStream(request, reply, decodedUrl, md5(decodedUrl), decodedHeader,
Object.assign({chunkSize: 1024 * 256, poolSize: 5, timeout: 1000 * 10}, {
// chunkSize: sizeToBytes(size),
poolSize: thread
})
);
}
} catch (error) {
// fastify.log.error(error);
fastify.log.error(error.message);
cleanup();
if (!reply.sent && !reply.raw.destroyed) {
reply.code(500).send({error: error.message});
}
}
});
done();
};
// Helper function for range-based chunk downloading
async function fetchStream(url, userHeaders, start, end, randUa) {
let stream = null;
const headers = keysToLowerCase({
...userHeaders,
});
// 添加accept属性防止获取网页源码编码不正确问题
if (!Object.keys(headers).includes('accept')) {
headers['accept'] = '*/*';
}
try {
const response = await _axios.get(url, {
headers: {
...headers,
...randUa ? {
'User-Agent': randomUa.generateUa(1, {
// device: ['mobile', 'pc'],
device: ['pc'],
mobileOs: ['android']
})
} : {},
Range: `bytes=${start}-${end}`,
},
responseType: 'stream',
timeout: 30000, // 30秒超时
});
stream = response.data;
// 添加错误处理监听器
stream.on('error', (error) => {
console.error(`[fetchStream] Stream error for range ${start}-${end}:`, error.message);
if (!stream.destroyed) {
stream.destroy();
}
});
// 添加超时处理
const timeoutId = setTimeout(() => {
if (!stream.destroyed) {
console.warn(`[fetchStream] Stream timeout for range ${start}-${end}`);
stream.destroy();
}
}, 60000); // 60秒超时
// 清理超时定时器
stream.on('end', () => clearTimeout(timeoutId));
stream.on('close', () => clearTimeout(timeoutId));
stream.on('error', () => clearTimeout(timeoutId));
return {stream: stream, headers: response.headers};
} catch (error) {
console.error(`[fetchStream] Error fetching range ${start}-${end}:`, error.message);
// 确保流被正确销毁
if (stream && !stream.destroyed) {
stream.destroy();
}
throw error;
}
}
async function proxyStreamMedia(mediaUrl, reqHeaders, request, reply, randUa = 0) {
let responseStream = null;
const eventListeners = [];
// 添加事件监听器的辅助函数
const addListener = (target, event, listener) => {
eventListeners.push({target, event, listener});
target.on(event, listener);
};
// 清理所有事件监听器的函数
const cleanupListeners = () => {
eventListeners.forEach(({target, event, listener}) => {
if (target && typeof target.removeListener === 'function') {
target.removeListener(event, listener);
}
});
eventListeners.length = 0;
};
try {
// 随机生成 UA(如果启用 randUa 参数)
const randHeaders = randUa
? Object.assign({}, reqHeaders, {
'User-Agent': randomUa.generateUa(1, {
// device: ['mobile', 'pc'],
device: ['pc'],
mobileOs: ['android']
})
})
: reqHeaders;
const headers = keysToLowerCase({
...randHeaders,
});
// 添加accept属性防止获取网页源码编码不正确问题
if (!Object.keys(headers).includes('accept')) {
headers['accept'] = '*/*';
}
const response = await _axios.get(mediaUrl, {
headers: headers,
responseType: 'stream',
timeout: 30000, // 30秒超时
});
responseStream = response.data;
// 将流添加到全局资源管理器
globalResourceManager.addStream(responseStream);
// 设置响应头
Object.entries(response.headers).forEach(([key, value]) => {
if (!['transfer-encoding', 'content-length'].includes(key.toLowerCase())) {
reply.raw.setHeader(key, value);
}
});
// 处理 range 请求
const range = request.headers.range;
if (range) {
const contentLength = parseInt(response.headers['content-length'], 10);
const [startStr, endStr] = range.replace(/bytes=/, '').split('-');
const start = parseInt(startStr, 10);
const end = endStr ? parseInt(endStr, 10) : contentLength - 1;
reply.raw.setHeader('Content-Range', `bytes ${start}-${end}/${contentLength}`);
reply.raw.setHeader('Content-Length', end - start + 1);
reply.raw.writeHead(206); // 206 Partial Content
} else {
reply.raw.writeHead(200);
}
// 监听客户端断开连接
const onAbort = () => {
console.log('[proxyStreamMedia] Client aborted the connection');
if (responseStream && !responseStream.destroyed) {
responseStream.destroy();
}
cleanupListeners();
};
addListener(request.raw, 'aborted', onAbort);
addListener(request.raw, 'close', onAbort);
// 流错误处理
const onStreamError = (error) => {
console.error('[proxyStreamMedia] Stream error:', error.message);
cleanupListeners();
if (!reply.sent && !reply.raw.destroyed) {
reply.code(500).send({error: error.message});
}
};
addListener(responseStream, 'error', onStreamError);
// 流结束处理
const onStreamEnd = () => {
console.log('[proxyStreamMedia] Stream ended successfully');
cleanupListeners();
};
addListener(responseStream, 'end', onStreamEnd);
addListener(responseStream, 'close', onStreamEnd);
// 检查连接状态
if (request.raw.aborted || request.raw.destroyed) {
console.log('[proxyStreamMedia] Connection already aborted');
if (responseStream && !responseStream.destroyed) {
responseStream.destroy();
}
return;
}
// 流式传输数据
responseStream.pipe(reply.raw);
} catch (error) {
console.error('[proxyStreamMedia] Error:', error.message);
// 清理资源
if (responseStream && !responseStream.destroyed) {
responseStream.destroy();
}
cleanupListeners();
if (!reply.sent && !reply.raw.destroyed) {
reply.code(500).send({error: error.message});
}
}
}
async function proxyStreamMediaMulti(mediaUrl, reqHeaders, request, reply, thread, size, randUa = 0) {
// 资源清理管理器
const resourceManager = {
streams: [],
eventListeners: [],
cleanup: function() {
// 清理所有流
this.streams.forEach(stream => {
if (stream && !stream.destroyed) {
stream.destroy();
}
});
this.streams = [];
// 清理所有事件监听器
this.eventListeners.forEach(({target, event, listener}) => {
if (target && typeof target.removeListener === 'function') {
target.removeListener(event, listener);
}
});
this.eventListeners = [];
},
addStream: function(stream) {
this.streams.push(stream);
},
addEventListener: function(target, event, listener) {
this.eventListeners.push({target, event, listener});
target.on(event, listener);
}
};
try {
let initialHeaders;
let contentLength;
// 随机生成 UA(如果启用 randUa 参数)
const randHeaders = randUa
? Object.assign({}, reqHeaders, {
'User-Agent': randomUa.generateUa(1, {
// device: ['mobile', 'pc'],
device: ['pc'],
mobileOs: ['android']
})
})
: reqHeaders;
const headers = keysToLowerCase({
...randHeaders,
});
// 添加accept属性防止获取网页源码编码不正确问题
if (!Object.keys(headers).includes('accept')) {
headers['accept'] = '*/*';
}
// 检查请求头中是否包含 Cookie
const hasCookie = Object.keys(randHeaders).some(key => key.toLowerCase() === 'cookie');
// console.log(`[proxyStreamMediaMulti] Checking for Cookie in headers: ${hasCookie}`);
let testStream = null;
try {
if (!hasCookie) {
// 优先尝试 HEAD 请求
// console.log('[proxyStreamMediaMulti] Attempting HEAD request to fetch content-length...');
const headResponse = await _axios.head(mediaUrl, {headers: headers});
initialHeaders = headResponse.headers;
contentLength = parseInt(initialHeaders['content-length'], 10);
console.log(`[proxyStreamMediaMulti] HEAD request successful, content-length: ${contentLength}`);
} else {
throw new Error('Skipping HEAD request due to Cookie in headers.');
}
} catch (headError) {
console.error('[proxyStreamMediaMulti] HEAD request failed or skipped:', headError.message);
// 使用 HTTP Range 请求获取 content-length
try {
// console.log('[proxyStreamMediaMulti] Attempting Range GET request to fetch content-length...');
const rangeHeaders = {...headers, Range: 'bytes=0-1'};
const rangeResponse = await _axios.get(mediaUrl, {
headers: rangeHeaders,
responseType: 'stream',
});
initialHeaders = rangeResponse.headers;
testStream = rangeResponse.data;
// 从 Content-Range 提取总大小
const contentRange = initialHeaders['content-range'];
if (contentRange) {
const match = contentRange.match(/\/(\d+)$/);
if (match) {
contentLength = parseInt(match[1], 10);
console.log(`[proxyStreamMediaMulti] Range GET request successful, content-length: ${contentLength}`);
}
}
// 立即销毁流,防止下载文件内容
if (testStream && !testStream.destroyed) {
testStream.destroy();
}
testStream = null;
} catch (rangeError) {
console.error('[proxyStreamMediaMulti] Range GET request failed:', rangeError.message);
console.log('[proxyStreamMediaMulti] headers:', headers);
// 使用 GET 请求获取 content-length
// console.log('[proxyStreamMediaMulti] Falling back to full GET request to fetch content-length...');
const getResponse = await _axios.get(mediaUrl, {
headers: headers,
responseType: 'stream',
});
initialHeaders = getResponse.headers;
contentLength = parseInt(initialHeaders['content-length'], 10);
console.log(`[proxyStreamMediaMulti] Full GET request successful, content-length: ${contentLength}`);
testStream = getResponse.data;
// 立即销毁流,防止下载文件内容
if (testStream && !testStream.destroyed) {
testStream.destroy();
}
testStream = null;
}
}
// 确保 content-length 有效
if (!contentLength) {
throw new Error('Failed to get the total content length.');
}
// 设置响应头,排除不必要的头部
Object.entries(initialHeaders).forEach(([key, value]) => {
if (!['transfer-encoding', 'content-length'].includes(key.toLowerCase())) {
reply.raw.setHeader(key, value);
}
});
reply.raw.setHeader('Accept-Ranges', 'bytes');
// 解析 range 请求头
const range = request.headers.range || 'bytes=0-';
const [startStr, endStr] = range.replace(/bytes=/, '').split('-');
let start = parseInt(startStr, 10);
let end = endStr ? parseInt(endStr, 10) : contentLength - 1;
// 校正 range 范围
if (start < 0) start = 0;
if (end >= contentLength) end = contentLength - 1;
if (start >= end) {
reply.code(416).header('Content-Range', `bytes */${contentLength}`).send();
console.log('[proxyStreamMediaMulti] Invalid range, sending 416 response.');
return;
}
// 设置 Content-Range 和 Content-Length 响应头
reply.raw.setHeader('Content-Range', `bytes ${start}-${end}/${contentLength}`);
reply.raw.setHeader('Content-Length', end - start + 1);
reply.raw.writeHead(206); // 206 Partial Content
// console.log(`[proxyStreamMediaMulti] Serving range: ${start}-${end}`);
// 计算每块的大小并划分子范围
const chunkSize = sizeToBytes(size);
const totalChunks = Math.ceil((end - start + 1) / chunkSize);
const threadCount = Math.min(thread, totalChunks);
const ranges = Array.from({length: threadCount}, (_, i) => {
const subStart = start + (i * (end - start + 1)) / threadCount;
const subEnd = Math.min(subStart + (end - start + 1) / threadCount - 1, end);
return {start: Math.floor(subStart), end: Math.floor(subEnd)};
});
// console.log(`[proxyStreamMediaMulti] Splitting range into ${ranges.length} threads...`);
// 并发获取数据块
const fetchChunks = ranges.map(range =>
fetchStream(mediaUrl, randHeaders, range.start, range.end, randUa)
);
let streams;
try {
streams = await Promise.all(fetchChunks);
} catch (fetchError) {
console.error('[proxyStreamMediaMulti] Error fetching streams:', fetchError.message);
throw fetchError;
}
// 将所有流添加到资源管理器
streams.forEach(({stream}) => {
resourceManager.addStream(stream);
globalResourceManager.addStream(stream);
});
// 设置全局中断处理
const globalAbortHandler = () => {
console.log('[proxyStreamMediaMulti] Client connection aborted, cleaning up resources');
resourceManager.cleanup();
};
// 添加中断监听器到资源管理器
resourceManager.addEventListener(request.raw, 'aborted', globalAbortHandler);
resourceManager.addEventListener(request.raw, 'close', globalAbortHandler);
// 按顺序发送数据块
let cnt = 0;
for (const {stream} of streams) {
cnt += 1;
// console.log(`[proxyStreamMediaMulti] Streaming chunk ${cnt}...`);
try {
// 检查连接状态
if (request.raw.aborted || request.raw.destroyed) {
console.log(`[proxyStreamMediaMulti] Connection aborted before chunk ${cnt}`);
break;
}
for await (const chunk of stream) {
if (request.raw.aborted || request.raw.destroyed) {
// console.log(`[proxyStreamMediaMulti] Chunk ${cnt} aborted.`);
break;
}
// 安全写入数据
if (!reply.raw.destroyed && !reply.raw.writableEnded) {
reply.raw.write(chunk);
} else {
console.log(`[proxyStreamMediaMulti] Response stream closed during chunk ${cnt}`);
break;
}
}
} catch (error) {
console.error(`[proxyStreamMediaMulti] Error during streaming chunk ${cnt}:`, error.message);
// 不要抛出错误,继续处理下一个chunk
}
}
console.log('[proxyStreamMediaMulti] All chunks streamed successfully.');
// 安全结束响应
if (!reply.raw.destroyed && !reply.raw.writableEnded) {
reply.raw.end();
}
} catch (error) {
console.error('[proxyStreamMediaMulti] Error:', error.message);
// 确保资源清理
resourceManager.cleanup();
if (!reply.sent && !reply.raw.destroyed) {
reply.code(500).send({error: error.message});
}
} finally {
// 最终清理
resourceManager.cleanup();
}
}
// Helper function to convert size string (e.g., '128K', '1M') to bytes
function sizeToBytes(size) {
const sizeMap = {
K: 1024,
M: 1024 * 1024,
G: 1024 * 1024 * 1024
};
const unit = size[size.length - 1].toUpperCase();
const number = parseInt(size, 10);
return number * (sizeMap[unit] || 1);
}