-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathm3u8-proxy.js
More file actions
954 lines (815 loc) · 37.7 KB
/
m3u8-proxy.js
File metadata and controls
954 lines (815 loc) · 37.7 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
/**
* M3U8 直播流代理控制器模块
* 提供 M3U8 索引文件和 TS 片段文件的代理访问功能
* 支持相对链接转换、身份验证、缓存等功能
* @module m3u8-proxy-controller
*/
import {ENV} from '../utils/env.js';
import https from 'https';
import http from 'http';
import {URL} from 'url';
/**
* M3U8 代理控制器插件
* @param {Object} fastify - Fastify实例
* @param {Object} options - 插件选项
* @param {Function} done - 完成回调
*/
export default (fastify, options, done) => {
// 请求缓存
const requestCache = new Map();
// M3U8 索引缓存
const m3u8Cache = new Map();
// 缓存超时时间(5分钟)
const cacheTimeout = 5 * 60 * 1000;
// M3U8 缓存超时时间(30秒,因为直播流更新频繁)
const m3u8CacheTimeout = 30 * 1000;
/**
* 验证身份认证
* @param {Object} request - Fastify请求对象
* @param {Object} reply - Fastify响应对象
* @returns {boolean} 验证是否通过
*/
function verifyAuth(request, reply) {
const requiredAuth = ENV.get('PROXY_AUTH', 'drpys');
const providedAuth = request.query.auth;
if (!providedAuth || providedAuth !== requiredAuth) {
reply.status(401).send({
error: 'Unauthorized',
message: 'Missing or invalid auth parameter',
code: 401
});
return false;
}
return true;
}
/**
* 解码参数 - 支持 base64 解码
* @param {string} param - 需要解码的参数
* @param {boolean} isJson - 是否为 JSON 格式
* @returns {string|Object} 解码后的参数
*/
function decodeParam(param, isJson = false) {
if (!param) return isJson ? {} : '';
let decoded = param;
try {
// 首先尝试 URL 解码
decoded = decodeURIComponent(param);
} catch (e) {
// URL 解码失败,使用原始参数
decoded = param;
}
// 对于 URL 参数,如果不是 http 开头,尝试 base64 解码
if (!isJson && !decoded.startsWith('http://') && !decoded.startsWith('https://')) {
try {
const base64Decoded = Buffer.from(decoded, 'base64').toString('utf8');
if (base64Decoded.startsWith('http://') || base64Decoded.startsWith('https://')) {
decoded = base64Decoded;
}
} catch (e) {
// base64 解码失败,保持原值
}
}
// 对于 headers 参数,如果不是 JSON 格式,尝试 base64 解码
if (isJson && !decoded.startsWith('{') && !decoded.endsWith('}')) {
try {
const base64Decoded = Buffer.from(decoded, 'base64').toString('utf8');
if (base64Decoded.startsWith('{') && base64Decoded.endsWith('}')) {
decoded = base64Decoded;
}
} catch (e) {
// base64 解码失败,保持原值
}
}
// 如果是 JSON 格式,尝试解析
if (isJson) {
try {
return JSON.parse(decoded);
} catch (e) {
console.warn('Failed to parse headers as JSON:', decoded);
return {};
}
}
return decoded;
}
/**
* 获取默认请求头
* @param {Object} request - Fastify 请求对象
* @returns {Object} 默认请求头
*/
function getDefaultHeaders(request) {
const defaultHeaders = {};
// 复制一些重要的请求头
const headersToForward = [
'user-agent',
'accept',
'accept-language',
'accept-encoding',
'referer',
'origin'
];
headersToForward.forEach(header => {
if (request.headers[header]) {
defaultHeaders[header] = request.headers[header];
}
});
// 如果没有 user-agent,设置默认值
if (!defaultHeaders['user-agent']) {
defaultHeaders['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36';
}
return defaultHeaders;
}
/**
* 发起远程请求
* @param {string} url - 远程文件 URL
* @param {Object} headers - 请求头
* @param {string} method - 请求方法
* @param {string} range - Range 头
* @returns {Promise} 请求结果
*/
function makeRemoteRequest(url, headers, method = 'GET', range = null) {
return new Promise((resolve, reject) => {
try {
const urlObj = new URL(url);
const isHttps = urlObj.protocol === 'https:';
const httpModule = isHttps ? https : http;
const requestHeaders = { ...headers };
if (range) {
requestHeaders['range'] = range;
}
const options = {
hostname: urlObj.hostname,
port: urlObj.port || (isHttps ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: method,
headers: requestHeaders,
timeout: 30000 // 30秒超时
};
const req = httpModule.request(options, (res) => {
resolve({
statusCode: res.statusCode,
headers: res.headers,
stream: res
});
});
req.on('error', (error) => {
reject(new Error(`Request failed: ${error.message}`));
});
req.on('timeout', () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.end();
} catch (error) {
reject(new Error(`Invalid URL or request setup: ${error.message}`));
}
});
}
/**
* 获取远程文件内容(文本)
* @param {string} url - 远程文件 URL
* @param {Object} headers - 请求头
* @returns {Promise<string>} 文件内容
*/
function getRemoteContent(url, headers) {
return new Promise(async (resolve, reject) => {
try {
const response = await makeRemoteRequest(url, headers, 'GET');
if (response.statusCode >= 400) {
reject(new Error(`Remote server error: ${response.statusCode}`));
return;
}
let content = '';
response.stream.on('data', chunk => {
content += chunk.toString('utf8');
});
response.stream.on('end', () => {
resolve(content);
});
response.stream.on('error', (error) => {
reject(error);
});
} catch (error) {
reject(error);
}
});
}
/**
* 解析 M3U8 文件内容,转换相对链接为代理链接
* @param {string} content - M3U8 文件内容
* @param {string} baseUrl - 基础 URL
* @param {string} proxyBaseUrl - 代理基础 URL
* @param {string} authCode - 身份验证码
* @returns {string} 处理后的 M3U8 内容
*/
function processM3u8Content(content, baseUrl, proxyBaseUrl, authCode) {
const lines = content.split('\n');
const processedLines = [];
for (let line of lines) {
line = line.trim();
// 跳过空行和注释行(以 # 开头)
if (!line || line.startsWith('#')) {
processedLines.push(line);
continue;
}
// 处理 TS 文件链接
let processedLine = line;
try {
// 判断是否为相对链接
if (!line.startsWith('http://') && !line.startsWith('https://')) {
// 相对链接,需要转换为绝对链接
const absoluteUrl = new URL(line, baseUrl).href;
// 转换为代理链接
const encodedUrl = encodeURIComponent(absoluteUrl);
processedLine = `${proxyBaseUrl}/m3u8-proxy/ts?url=${encodedUrl}&auth=${authCode}`;
} else {
// 绝对链接,直接转换为代理链接
const encodedUrl = encodeURIComponent(line);
processedLine = `${proxyBaseUrl}/m3u8-proxy/ts?url=${encodedUrl}&auth=${authCode}`;
}
} catch (error) {
console.warn(`Failed to process M3U8 line: ${line}`, error);
// 处理失败时保持原链接
processedLine = line;
}
processedLines.push(processedLine);
}
return processedLines.join('\n');
}
/**
* 获取请求的基础 URL(协议 + 主机 + 端口)
* @param {Object} request - Fastify 请求对象
* @returns {string} 基础 URL
*/
function getProxyBaseUrl(request) {
const protocol = request.headers['x-forwarded-proto'] ||
(request.connection.encrypted ? 'https' : 'http');
const host = request.headers['x-forwarded-host'] ||
request.headers.host ||
'localhost:3001';
return `${protocol}://${host}`;
}
/**
* M3U8 代理健康检查接口
* GET /m3u8-proxy/health - 检查 M3U8 代理服务状态
*/
fastify.get('/m3u8-proxy/health', async (request, reply) => {
console.log(`[m3u8ProxyController] Health check request`);
return reply.send({
status: 'ok',
service: 'M3U8 Stream Proxy',
timestamp: new Date().toISOString(),
cache: {
requests: requestCache.size,
m3u8: m3u8Cache.size
}
});
});
/**
* M3U8 索引文件代理接口
* GET /m3u8-proxy/playlist - 代理 M3U8 索引文件
*/
fastify.get('/m3u8-proxy/playlist', async (request, reply) => {
// 验证身份认证
if (!verifyAuth(request, reply)) {
return;
}
const { url: urlParam, headers: headersParam } = request.query;
console.log(`[m3u8ProxyController] M3U8 playlist request for URL: ${urlParam}`);
// 验证必需参数
if (!urlParam) {
return reply.status(400).send({ error: 'Missing required parameter: url' });
}
try {
// 解码 URL 参数
const targetUrl = decodeParam(urlParam, false);
// 验证 URL 格式
if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
return reply.status(400).send({ error: 'Invalid URL: must start with http:// or https://' });
}
// 检查缓存
const cacheKey = `m3u8:${targetUrl}`;
const cached = m3u8Cache.get(cacheKey);
if (cached && (Date.now() - cached.timestamp) < m3u8CacheTimeout) {
console.log(`[m3u8ProxyController] Serving M3U8 from cache: ${targetUrl}`);
reply.header('Content-Type', 'application/vnd.apple.mpegurl');
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
reply.header('Cache-Control', 'no-cache');
return reply.send(cached.content);
}
// 解码 headers 参数
const customHeaders = decodeParam(headersParam, true);
// 合并默认请求头和自定义请求头
const defaultHeaders = getDefaultHeaders(request);
const requestHeaders = { ...defaultHeaders, ...customHeaders };
try {
// 获取 M3U8 文件内容
const m3u8Content = await getRemoteContent(targetUrl, requestHeaders);
// 获取代理基础 URL
const proxyBaseUrl = getProxyBaseUrl(request);
// 处理 M3U8 内容,转换链接
const processedContent = processM3u8Content(
m3u8Content,
targetUrl,
proxyBaseUrl,
request.query.auth
);
// 缓存处理后的内容
m3u8Cache.set(cacheKey, {
content: processedContent,
timestamp: Date.now()
});
// 设置响应头
reply.header('Content-Type', 'application/vnd.apple.mpegurl');
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
reply.header('Cache-Control', 'no-cache');
return reply.send(processedContent);
} catch (requestError) {
console.error('[m3u8ProxyController] M3U8 request error:', requestError);
return reply.status(502).send({
error: `Failed to fetch M3U8 playlist: ${requestError.message}`
});
}
} catch (error) {
console.error('[m3u8ProxyController] M3U8 request processing error:', error);
return reply.status(500).send({ error: error.message });
}
});
/**
* TS 文件代理接口
* GET /m3u8-proxy/ts - 代理 TS 片段文件
*/
fastify.route({
method: ['GET', 'HEAD'],
url: '/m3u8-proxy/ts',
handler: async (request, reply) => {
// 验证身份认证
if (!verifyAuth(request, reply)) {
return;
}
const { url: urlParam, headers: headersParam } = request.query;
console.log(`[m3u8ProxyController] ${request.method} TS request for URL: ${urlParam}`);
// 验证必需参数
if (!urlParam) {
return reply.status(400).send({ error: 'Missing required parameter: url' });
}
try {
// 解码 URL 参数
const targetUrl = decodeParam(urlParam, false);
// 验证 URL 格式
if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
return reply.status(400).send({ error: 'Invalid URL: must start with http:// or https://' });
}
// 解码 headers 参数
const customHeaders = decodeParam(headersParam, true);
// 合并默认请求头和自定义请求头
const defaultHeaders = getDefaultHeaders(request);
const requestHeaders = { ...defaultHeaders, ...customHeaders };
// 处理 Range 请求
const range = request.headers.range;
try {
// 发起远程请求
const remoteResponse = await makeRemoteRequest(
targetUrl,
requestHeaders,
request.method,
range
);
// 检查远程响应状态
if (remoteResponse.statusCode >= 400) {
return reply.status(remoteResponse.statusCode).send({
error: `Remote server error: ${remoteResponse.statusCode}`
});
}
// 设置响应状态码
reply.status(remoteResponse.statusCode);
// 转发重要的响应头
const headersToForward = [
'content-type',
'content-length',
'content-range',
'accept-ranges',
'last-modified',
'etag',
'cache-control',
'expires'
];
headersToForward.forEach(header => {
if (remoteResponse.headers[header]) {
reply.header(header, remoteResponse.headers[header]);
}
});
// 设置 CORS 头
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
reply.header('Access-Control-Allow-Headers', 'Range, Content-Type');
// 对于 HEAD 请求,只返回头部信息
if (request.method === 'HEAD') {
return reply.send();
}
// 对于 GET 请求,返回文件流
return reply.send(remoteResponse.stream);
} catch (requestError) {
console.error('[m3u8ProxyController] TS request error:', requestError);
return reply.status(502).send({
error: `Failed to fetch TS file: ${requestError.message}`
});
}
} catch (error) {
console.error('[m3u8ProxyController] TS request processing error:', error);
return reply.status(500).send({ error: error.message });
}
}
});
/**
* 缓存管理接口
* DELETE /m3u8-proxy/cache - 清理缓存
*/
fastify.delete('/m3u8-proxy/cache', async (request, reply) => {
// 验证身份认证
if (!verifyAuth(request, reply)) {
return;
}
console.log(`[m3u8ProxyController] Cache clear request`);
try {
// 非VERCEL环境可在设置中心控制此功能是否开启
if (!process.env.VERCEL) {
if (!Number(process.env.allow_file_cache_clear)) {
return reply.status(403).send({ error: 'Cache clear is not allowed by owner' });
}
}
const requestCacheCount = requestCache.size;
const m3u8CacheCount = m3u8Cache.size;
// 清理缓存
requestCache.clear();
m3u8Cache.clear();
return reply.send({
success: true,
message: 'Cache cleared successfully',
cleared: {
requests: requestCacheCount,
m3u8: m3u8CacheCount
}
});
} catch (error) {
console.error('[m3u8ProxyController] Cache clear error:', error);
return reply.status(500).send({ error: error.message });
}
});
/**
* M3U8 代理状态接口
* GET /m3u8-proxy/status - 获取代理服务状态
*/
fastify.get('/m3u8-proxy/status', async (request, reply) => {
console.log(`[m3u8ProxyController] Status request`);
try {
return reply.send({
service: 'M3U8 Stream Proxy Controller',
version: '1.0.0',
status: 'running',
cache: {
requests: requestCache.size,
m3u8: m3u8Cache.size,
requestTimeout: cacheTimeout,
m3u8Timeout: m3u8CacheTimeout
},
features: [
'M3U8 playlist proxying',
'TS segment proxying',
'Relative URL conversion',
'Base64 parameter decoding',
'Range request support',
'Custom headers support',
'CORS support',
'Authentication protection',
'Smart caching'
],
endpoints: [
'GET /m3u8-proxy/health - Health check (no auth required)',
'GET /m3u8-proxy/proxy?url=<file_url>&auth=<auth_code>&headers=<custom_headers> - Unified proxy for M3U8 and TS files',
'HEAD /m3u8-proxy/proxy?url=<file_url>&auth=<auth_code>&headers=<custom_headers> - Get file headers via unified proxy',
'GET /m3u8-proxy/playlist?url=<m3u8_url>&auth=<auth_code>&headers=<custom_headers> - Proxy M3U8 playlist',
'GET /m3u8-proxy/ts?url=<ts_url>&auth=<auth_code>&headers=<custom_headers> - Proxy TS segment',
'HEAD /m3u8-proxy/ts?url=<ts_url>&auth=<auth_code>&headers=<custom_headers> - Get TS segment headers',
'DELETE /m3u8-proxy/cache?auth=<auth_code> - Clear cache',
'GET /m3u8-proxy/status - Get service status (no auth required)'
],
auth: {
required: true,
parameter: 'auth',
description: 'Authentication code required for protected endpoints'
}
});
} catch (error) {
console.error('[m3u8ProxyController] Status request error:', error);
return reply.status(500).send({ error: error.message });
}
});
/**
* 智能文件类型检测
* @param {string} url - 文件 URL
* @param {string} contentType - 响应的 Content-Type
* @param {string} content - 文件内容(可选)
* @returns {string} 文件类型:'m3u8' 或 'ts' 或 'unknown'
*/
function detectFileType(url, contentType = '', content = '') {
// 1. 基于 URL 扩展名检测
const urlLower = url.toLowerCase();
if (urlLower.includes('.m3u8')) {
return 'm3u8';
}
if (urlLower.includes('.ts')) {
return 'ts';
}
// 2. 基于 Content-Type 检测
const contentTypeLower = contentType.toLowerCase();
if (contentTypeLower.includes('application/vnd.apple.mpegurl') ||
contentTypeLower.includes('application/x-mpegurl')) {
return 'm3u8';
}
if (contentTypeLower.includes('video/mp2t') ||
contentTypeLower.includes('application/octet-stream')) {
return 'ts';
}
// 3. 基于内容特征检测(仅对文本内容)
if (content && typeof content === 'string') {
const contentTrimmed = content.trim();
if (contentTrimmed.startsWith('#EXTM3U') ||
contentTrimmed.includes('#EXT-X-VERSION') ||
contentTrimmed.includes('#EXTINF')) {
return 'm3u8';
}
}
return 'unknown';
}
/**
* 统一代理接口
* GET/HEAD /m3u8-proxy/proxy - 智能代理 M3U8 和 TS 文件
*
* 参数:
* - url: 目标文件 URL(支持 base64 编码)
* - auth: 认证码
* - headers: 自定义请求头(JSON 格式,支持 base64 编码)
*
* 功能:
* 1. 自动检测文件类型(M3U8 或 TS)
* 2. 对 M3U8 文件进行相对路径转换
* 3. 对 TS 文件进行直接代理
* 4. 支持嵌套 M3U8 文件处理
*/
fastify.route({
method: ['GET', 'HEAD'],
url: '/m3u8-proxy/proxy',
handler: async (request, reply) => {
// 验证身份认证
if (!verifyAuth(request, reply)) {
return;
}
const { url: urlParam, headers: headersParam } = request.query;
console.log(`[m3u8ProxyController] ${request.method} unified proxy request for URL: ${urlParam}`);
// 验证必需参数
if (!urlParam) {
return reply.status(400).send({ error: 'Missing required parameter: url' });
}
try {
// 解码 URL 参数
const targetUrl = decodeParam(urlParam, false);
// 验证 URL 格式
if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
return reply.status(400).send({ error: 'Invalid URL: must start with http:// or https://' });
}
// 解码 headers 参数
const customHeaders = decodeParam(headersParam, true);
// 合并默认请求头和自定义请求头
const defaultHeaders = getDefaultHeaders(request);
const requestHeaders = { ...defaultHeaders, ...customHeaders };
// 首先进行 HEAD 请求来检测文件类型
let fileType = 'unknown';
let remoteResponse;
let headRequestFailed = false;
try {
// 发起 HEAD 请求获取文件信息
const headResponse = await makeRemoteRequest(targetUrl, requestHeaders, 'HEAD');
if (headResponse.statusCode >= 400) {
console.warn(`[m3u8ProxyController] HEAD request failed with ${headResponse.statusCode}, falling back to GET`);
headRequestFailed = true;
// HEAD 请求失败,继续使用 GET 请求,不直接返回错误
} else {
// 检测文件类型
const contentType = headResponse.headers['content-type'] || '';
fileType = detectFileType(targetUrl, contentType);
console.log(`[m3u8ProxyController] Detected file type: ${fileType} for URL: ${targetUrl}`);
// 如果是 HEAD 请求且检测到是 TS 文件,直接返回头信息
if (request.method === 'HEAD' && fileType === 'ts') {
// 设置响应头
Object.entries(headResponse.headers).forEach(([key, value]) => {
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
reply.header(key, value);
}
});
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
return reply.status(headResponse.statusCode).send();
}
}
} catch (headError) {
console.warn(`[m3u8ProxyController] HEAD request failed, falling back to GET: ${headError.message}`);
headRequestFailed = true;
// HEAD 请求失败,继续使用 GET 请求
}
// 如果无法通过 HEAD 确定类型,或者需要获取内容,或者 HEAD 请求失败,发起 GET 请求
if (fileType === 'unknown' || fileType === 'm3u8' || request.method === 'GET' || headRequestFailed) {
const range = request.headers.range;
try {
// 如果是 HEAD 请求失败的回退,使用 GET 方法
const requestMethod = (request.method === 'HEAD' && headRequestFailed) ? 'GET' : request.method;
remoteResponse = await makeRemoteRequest(
targetUrl,
requestHeaders,
requestMethod,
range
);
if (remoteResponse.statusCode >= 400) {
console.error(`[m3u8ProxyController] Remote server error: ${remoteResponse.statusCode} for URL: ${targetUrl}`);
console.error(`[m3u8ProxyController] Remote response headers:`, remoteResponse.headers);
// 尝试读取错误响应内容
let errorContent = '';
try {
const chunks = [];
remoteResponse.stream.on('data', chunk => chunks.push(chunk));
await new Promise((resolve, reject) => {
remoteResponse.stream.on('end', resolve);
remoteResponse.stream.on('error', reject);
});
errorContent = Buffer.concat(chunks).toString('utf8').substring(0, 500);
console.error(`[m3u8ProxyController] Remote error content:`, errorContent);
} catch (e) {
console.error(`[m3u8ProxyController] Failed to read error content:`, e.message);
}
return reply.status(remoteResponse.statusCode).send({
error: `Remote server error: ${remoteResponse.statusCode}`,
url: targetUrl,
details: errorContent || 'No additional details available'
});
}
// 如果之前未能确定文件类型,现在基于响应头再次检测
if (fileType === 'unknown') {
const contentType = remoteResponse.headers['content-type'] || '';
fileType = detectFileType(targetUrl, contentType);
}
} catch (requestError) {
console.error('[m3u8ProxyController] Remote request error:', requestError);
return reply.status(502).send({
error: `Failed to fetch remote file: ${requestError.message}`
});
}
}
// 根据文件类型进行不同处理
if (fileType === 'm3u8') {
// M3U8 文件处理
console.log(`[m3u8ProxyController] Processing as M3U8 file: ${targetUrl}`);
// 检查 M3U8 缓存
const cacheKey = `m3u8:${targetUrl}`;
const cached = m3u8Cache.get(cacheKey);
if (cached && (Date.now() - cached.timestamp) < m3u8CacheTimeout) {
console.log(`[m3u8ProxyController] Serving M3U8 from cache: ${targetUrl}`);
reply.header('Content-Type', 'application/vnd.apple.mpegurl');
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
reply.header('Cache-Control', 'no-cache');
// 对于 HEAD 请求,只返回头信息,不返回内容
if (request.method === 'HEAD') {
return reply.status(200).send();
} else {
return reply.send(cached.content);
}
}
// 获取 M3U8 文件内容 - 使用 Promise 处理异步流
const m3u8Content = await new Promise((resolve, reject) => {
const chunks = [];
remoteResponse.stream.on('data', (chunk) => {
chunks.push(chunk);
});
remoteResponse.stream.on('end', () => {
const content = Buffer.concat(chunks).toString('utf8');
resolve(content);
});
remoteResponse.stream.on('error', (error) => {
reject(error);
});
});
// 基于内容再次确认文件类型
const confirmedType = detectFileType(targetUrl, remoteResponse.headers['content-type'] || '', m3u8Content);
if (confirmedType === 'm3u8') {
// 获取代理基础 URL
const proxyBaseUrl = getProxyBaseUrl(request);
// 处理 M3U8 内容,转换链接为统一代理接口
const processedContent = processM3u8ContentUnified(
m3u8Content,
targetUrl,
proxyBaseUrl,
request.query.auth
);
// 缓存处理后的内容
m3u8Cache.set(cacheKey, {
content: processedContent,
timestamp: Date.now()
});
// 设置响应头
reply.header('Content-Type', 'application/vnd.apple.mpegurl');
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
reply.header('Cache-Control', 'no-cache');
// 对于 HEAD 请求,只返回头信息,不返回内容
if (request.method === 'HEAD') {
return reply.status(200).send();
} else {
return reply.send(processedContent);
}
} else {
// 如果确认不是 M3U8 文件,按二进制文件处理
console.log(`[m3u8ProxyController] File confirmed as non-M3U8, treating as binary: ${targetUrl}`);
// 设置响应头
Object.entries(remoteResponse.headers).forEach(([key, value]) => {
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
reply.header(key, value);
}
});
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
// 对于 HEAD 请求,只返回头信息,不返回内容
if (request.method === 'HEAD') {
return reply.status(remoteResponse.statusCode).send();
} else {
return reply.status(remoteResponse.statusCode).send(m3u8Content);
}
}
} else {
// TS 文件或其他二进制文件处理
console.log(`[m3u8ProxyController] Processing as ${fileType} file: ${targetUrl}`);
// 设置响应头
Object.entries(remoteResponse.headers).forEach(([key, value]) => {
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
reply.header(key, value);
}
});
reply.header('Access-Control-Allow-Origin', '*');
reply.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
// 对于 HEAD 请求,只返回头信息,不返回内容
if (request.method === 'HEAD') {
reply.status(remoteResponse.statusCode);
return reply.send();
} else {
// 直接流式传输
reply.status(remoteResponse.statusCode);
return reply.send(remoteResponse.stream);
}
}
} catch (error) {
console.error('[m3u8ProxyController] Unified proxy error:', error);
return reply.status(500).send({ error: error.message });
}
}
});
/**
* 处理 M3U8 内容,转换链接为统一代理接口
* @param {string} content - M3U8 文件内容
* @param {string} baseUrl - 基础 URL
* @param {string} proxyBaseUrl - 代理基础 URL
* @param {string} authCode - 认证码
* @returns {string} 处理后的 M3U8 内容
*/
function processM3u8ContentUnified(content, baseUrl, proxyBaseUrl, authCode) {
const lines = content.split('\n');
const processedLines = [];
for (let line of lines) {
line = line.trim();
// 跳过注释行和空行
if (line.startsWith('#') || line === '') {
processedLines.push(line);
continue;
}
// 处理 URL 行
let targetUrl = line;
// 如果是相对路径,转换为绝对路径
if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
try {
const base = new URL(baseUrl);
targetUrl = new URL(targetUrl, base).href;
} catch (error) {
console.warn(`[m3u8ProxyController] Failed to resolve relative URL: ${line}`);
processedLines.push(line);
continue;
}
}
// 编码目标 URL
const encodedUrl = encodeURIComponent(targetUrl);
// 生成统一代理链接
const proxyUrl = `${proxyBaseUrl}/m3u8-proxy/proxy?url=${encodedUrl}&auth=${authCode}`;
processedLines.push(proxyUrl);
}
return processedLines.join('\n');
}
done();
};