-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2419 lines (2049 loc) · 70.1 KB
/
server.js
File metadata and controls
2419 lines (2049 loc) · 70.1 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 express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const fs = require('fs');
const os = require('os');
const multer = require('multer');
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
const rtmpServer = require('./rtmp-server');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
// 创建上传目录
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
// 配置 multer 文件上传
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
// 生成唯一文件名
const uniqueName = `${uuidv4()}${path.extname(file.originalname)}`;
cb(null, uniqueName);
}
});
const upload = multer({
storage,
// 不设置文件大小限制
fileFilter: (req, file, cb) => {
// 允许的格式 (视频 + 字幕)
const allowedTypes = /mp4|webm|mkv|avi|mov|m4v|ogg|ogv|flv|wmv|ts|srt|ass|ssa|sub|idx/;
const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase().replace('.', ''));
// 字幕文件的 mimetype 经常识别不准,所以主要靠扩展名
const mimetype = file.mimetype.startsWith('video/') ||
file.mimetype.includes('text/') ||
file.mimetype.includes('app'); // application/x-subrip etc.
if (extname) { // 主要信赖扩展名
cb(null, true);
} else {
cb(new Error('不支持的文件格式'));
}
}
});
// 自定义 MIME 类型
const mimeTypes = {
'.mp4': 'video/mp4',
'.m4v': 'video/mp4',
'.mov': 'video/mp4', // MOV 使用 mp4 mime 类型可以更好兼容
'.webm': 'video/webm',
'.ogv': 'video/ogg',
'.ogg': 'video/ogg',
'.mkv': 'video/x-matroska',
'.avi': 'video/x-msvideo',
'.flv': 'video/x-flv',
'.wmv': 'video/x-ms-wmv',
'.ts': 'video/mp2t',
'.m3u8': 'application/x-mpegURL'
};
// JSON 请求体解析中间件
app.use(express.json());
// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
// 上传文件服务 - 设置正确的 MIME 类型
app.use('/uploads', (req, res, next) => {
const ext = path.extname(req.path).toLowerCase();
if (mimeTypes[ext]) {
res.setHeader('Content-Type', mimeTypes[ext]);
}
// 允许范围请求(用于视频 seek)
res.setHeader('Accept-Ranges', 'bytes');
next();
}, express.static(uploadsDir));
// 存储房间信息
const rooms = new Map();
// 房间数据结构
class Room {
constructor(id, hostName, roomName = null, password = null) {
this.id = id;
this.hostName = hostName;
this.name = roomName || `${hostName}的放映室`; // 房间名称
this.password = password || null; // 房间密码 (null = 公开)
this.videoUrl = '';
this.subtitleUrl = null; // 字幕 URL
this.videoState = {
isPlaying: false,
currentTime: 0,
playbackRate: 1,
lastUpdated: Date.now()
};
this.users = new Map(); // socketId -> { name, joinedAt, isHost }
this.messages = [];
this.createdAt = Date.now();
// 权限配置
this.settings = {
allowAllChangeVideo: false, // 是否允许所有人更换视频
allowAllChangeSubtitle: false, // 是否允许所有人更换字幕
allowAllControl: true, // 是否允许所有人控制播放
allowAllStream: false, // 是否允许所有人推流直播
waitForAll: false // 是否等待所有人缓冲完成后再播放
};
// 跟踪 B 站下载的文件(用于清理)
this.bilibiliFiles = [];
// 房主的用户 ID (用于重连恢复权限)
this.hostUserId = null;
// 屏幕共享状态
this.screenShareState = {
isSharing: false,
sharerId: null,
sharerName: null
};
// 直播推流状态
this.liveStreamState = {
isStreaming: false,
streamerId: null,
streamerName: null,
streamKey: null,
hlsUrl: null,
startedAt: null
};
}
// 检查是否需要密码
get hasPassword() {
return this.password !== null && this.password !== '';
}
// 验证密码
verifyPassword(inputPassword) {
if (!this.hasPassword) return true;
return this.password === inputPassword;
}
/**
* 添加用户
* @param {string} socketId - Socket 连接 ID
* @param {string} name - 用户名
* @param {string} userId - 用户唯一标识 (前端生成)
*/
addUser(socketId, name, userId) {
this.users.set(socketId, {
name,
userId, // 绑定 userId
joinedAt: Date.now()
});
// 如果没有房主,或者该用户就是房主(重连)
if (!this.hostUserId) {
this.hostUserId = userId;
}
}
/**
* 移除用户
* @param {string} socketId
*/
removeUser(socketId) {
const user = this.users.get(socketId);
this.users.delete(socketId);
// 只有当房间彻底没人时,才重置房主
// 这样房主刷新页面 (socketId 变了但 userId 没变) 回来后还是房主
if (this.users.size === 0) {
this.hostUserId = null;
}
}
/**
* 检查是否是房主
*/
isHost(socketId) {
const user = this.users.get(socketId);
return user && user.userId === this.hostUserId;
}
getUserList() {
const list = [];
this.users.forEach((user, socketId) => {
list.push({
id: socketId,
userId: user.userId, // 返回 userId 供前端判断
name: user.name,
isHost: user.userId === this.hostUserId
});
});
return list;
}
addMessage(socketId, userName, text) {
const message = {
id: uuidv4(),
userId: socketId,
userName,
text,
timestamp: Date.now()
};
this.messages.push(message);
// 只保留最近100条消息
if (this.messages.length > 100) {
this.messages.shift();
}
return message;
}
updateUserName(socketId, newName) {
const user = this.users.get(socketId);
if (user) {
user.name = newName;
return true;
}
return false;
}
updateSettings(newSettings) {
this.settings = { ...this.settings, ...newSettings };
}
transferHost(newHostSocketId) {
const user = this.users.get(newHostSocketId);
if (user) {
this.hostUserId = user.userId;
return true;
}
return false;
}
}
// ============ 并行分片转码配置 ============
// 使用系统 PATH 中的 ffmpeg/ffprobe
const ffprobePath = 'ffprobe';
const ffmpegPath = 'ffmpeg';
// 每个分片的时长 (秒) - 5分钟
const SEGMENT_DURATION = 300;
// 最大并行进程数 (基于 CPU 核心数)
const MAX_PARALLEL_WORKERS = Math.max(2, Math.floor(os.cpus().length / 2));
console.log(`并行转码配置: 每片 ${SEGMENT_DURATION}s, 最大 ${MAX_PARALLEL_WORKERS} 并行进程`);
// ============ 转码进度追踪 ============
// 存储转码进度 { uploadId -> { filename, stage, progress, message, ... } }
const transcodeProgress = new Map();
/**
* 发送转码进度到前端
*/
function emitProgress(uploadId, data) {
const progressData = {
uploadId,
filename: data.filename || '',
stage: data.stage || 'processing', // 'analyzing', 'transcoding', 'merging', 'complete', 'error'
progress: data.progress || 0, // 0-100
message: data.message || '',
segmentInfo: data.segmentInfo || null, // { current, total, completed }
...data
};
transcodeProgress.set(uploadId, progressData);
// 广播给所有连接的客户端
io.emit('transcode-progress', progressData);
console.log(`[进度] ${uploadId}: ${progressData.stage} - ${progressData.progress}% - ${progressData.message}`);
}
/**
* 获取视频时长 (秒)
*/
async function getVideoDuration(filePath) {
const cmd = `${ffprobePath} -v error -show_entries format=duration -of csv=p=0 "${filePath}"`;
try {
const { stdout } = await execAsync(cmd);
const duration = parseFloat(stdout.trim());
if (isNaN(duration)) throw new Error('Invalid duration');
return duration;
} catch (err) {
console.error('获取视频时长失败:', err.message);
return 0;
}
}
/**
* 获取音轨信息
*/
async function getAudioStreams(filePath) {
const cmd = `${ffprobePath} -v error -select_streams a -show_entries stream=index,codec_name:stream_tags=title,language -of json "${filePath}"`;
try {
const { stdout } = await execAsync(cmd);
const data = JSON.parse(stdout);
return data.streams || [];
} catch (err) {
console.error('获取音轨信息失败:', err.message);
return [];
}
}
/**
* 获取视频编码格式
*/
async function getVideoCodec(filePath) {
const cmd = `${ffprobePath} -v error -select_streams v:0 -show_entries stream=codec_name -of csv=p=0 "${filePath}"`;
try {
const { stdout } = await execAsync(cmd);
return stdout.trim();
} catch (err) {
console.error('获取视频编码失败:', err.message);
return 'unknown';
}
}
/**
* 获取音频编码格式
*/
async function getAudioCodec(filePath) {
const cmd = `${ffprobePath} -v error -select_streams a:0 -show_entries stream=codec_name -of csv=p=0 "${filePath}"`;
try {
const { stdout } = await execAsync(cmd);
return stdout.trim();
} catch (err) {
console.error('获取音频编码失败:', err.message);
return 'unknown';
}
}
/**
* 检测是否可以使用 stream copy (无需重新编码)
*/
async function canUseStreamCopy(filePath) {
const [videoCodec, audioCodec] = await Promise.all([
getVideoCodec(filePath),
getAudioCodec(filePath)
]);
// H.264/HEVC + AAC 可以直接复制到 HLS
const videoOk = ['h264', 'hevc'].includes(videoCodec.toLowerCase());
const audioOk = ['aac', 'mp3'].includes(audioCodec.toLowerCase());
console.log(`[编码检测] 视频: ${videoCodec}, 音频: ${audioCodec}, 可 stream copy: ${videoOk && audioOk}`);
return {
canCopy: videoOk && audioOk,
videoCodec,
audioCodec
};
}
/**
* 转码单个分片 (支持 stream copy 模式)
* @param {Object} opts - 转码选项
* @returns {Promise<{success: boolean, segmentIndex: number, tsFiles: string[]}>}
*/
async function transcodeSegment(opts) {
const { inputPath, hlsDir, segmentIndex, startTime, duration, mapArgs, useStreamCopy = false } = opts;
const startTimeStr = formatTime(startTime);
const segmentPrefix = `seg_${segmentIndex}`;
const playlistPath = path.join(hlsDir, `stream_${segmentIndex}.m3u8`);
// 根据是否使用 stream copy 选择编码参数
let codecArgs;
if (useStreamCopy) {
// Stream copy: 直接复制流,不重新编码 (极快)
codecArgs = `-c:v copy -c:a copy`;
console.log(`[分片 ${segmentIndex}] 使用 stream copy 模式`);
} else {
// 重新编码: 使用 ultrafast 预设 (比原来的 veryfast 更快)
codecArgs = `-c:v libx264 -preset ultrafast -crf 23 ` +
`-g 48 -keyint_min 48 -sc_threshold 0 ` +
`-force_key_frames "expr:gte(t,n_forced*2)" ` +
`-c:a aac -b:a 128k -ac 2`;
}
const ffmpegCmd = `${ffmpegPath} -y -threads 0 ` +
`-ss ${startTimeStr} -t ${duration} -i "${inputPath}" ${mapArgs} ` +
`-output_ts_offset ${startTime} ` +
`${codecArgs} ` +
`-f hls -hls_time 2 -hls_list_size 0 ` +
`-hls_segment_type mpegts ` +
`-hls_flags independent_segments ` +
`-hls_segment_filename "${hlsDir}/${segmentPrefix}_%04d.ts" ` +
`"${playlistPath}"`;
console.log(`[分片 ${segmentIndex}] 开始转码: ${startTimeStr} 时长 ${duration}s`);
try {
await execAsync(ffmpegCmd, { maxBuffer: 1024 * 1024 * 50 });
// 获取生成的 ts 文件列表
const tsFiles = fs.readdirSync(hlsDir)
.filter(f => f.startsWith(segmentPrefix) && f.endsWith('.ts'))
.sort();
console.log(`[分片 ${segmentIndex}] 转码完成, 生成 ${tsFiles.length} 个 ts 文件`);
return { success: true, segmentIndex, tsFiles, playlistPath };
} catch (err) {
console.error(`[分片 ${segmentIndex}] 转码失败:`, err.message);
return { success: false, segmentIndex, tsFiles: [], error: err.message };
}
}
/**
* 合并所有分片的 m3u8 播放列表
*/
function mergeHlsPlaylists(hlsDir, segmentResults, audioStreams) {
// 读取所有分片的 m3u8 并合并
let allSegments = [];
let targetDuration = 4;
for (const result of segmentResults) {
if (!result.success) continue;
const playlistContent = fs.readFileSync(result.playlistPath, 'utf-8');
const lines = playlistContent.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// 提取 EXTINF 和 ts 文件
if (line.startsWith('#EXTINF:')) {
const duration = parseFloat(line.split(':')[1].split(',')[0]);
targetDuration = Math.max(targetDuration, Math.ceil(duration));
const tsFile = lines[i + 1]?.trim();
if (tsFile && tsFile.endsWith('.ts')) {
allSegments.push({ extinf: line, tsFile });
}
}
}
}
// 生成合并后的主播放列表
let masterContent = '#EXTM3U\n';
masterContent += '#EXT-X-VERSION:3\n';
masterContent += `#EXT-X-TARGETDURATION:${targetDuration}\n`;
masterContent += '#EXT-X-MEDIA-SEQUENCE:0\n';
masterContent += '#EXT-X-PLAYLIST-TYPE:VOD\n\n';
for (const seg of allSegments) {
masterContent += `${seg.extinf}\n${seg.tsFile}\n`;
}
masterContent += '#EXT-X-ENDLIST\n';
// 写入 stream_v.m3u8 (视频+默认音轨)
const streamPlaylist = path.join(hlsDir, 'stream_v.m3u8');
fs.writeFileSync(streamPlaylist, masterContent);
// 生成 master.m3u8
let masterPlaylist = '#EXTM3U\n';
masterPlaylist += '#EXT-X-VERSION:3\n\n';
// 音轨信息
if (audioStreams.length > 1) {
audioStreams.forEach((stream, i) => {
const name = stream.tags?.title || stream.tags?.language || `Audio${i + 1}`;
const isDefault = i === 0 ? 'YES' : 'NO';
masterPlaylist += `#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="${name}",DEFAULT=${isDefault},AUTOSELECT=YES,URI="stream_v.m3u8"\n`;
});
}
masterPlaylist += '#EXT-X-STREAM-INF:BANDWIDTH=2000000,AUDIO="audio"\n';
masterPlaylist += 'stream_v.m3u8\n';
const masterPath = path.join(hlsDir, 'master.m3u8');
fs.writeFileSync(masterPath, masterPlaylist);
// 清理分片播放列表
for (const result of segmentResults) {
if (result.playlistPath && fs.existsSync(result.playlistPath)) {
fs.unlinkSync(result.playlistPath);
}
}
return masterPath;
}
/**
* 格式化时间为 HH:MM:SS 格式
*/
function formatTime(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
}
// API 路由
app.get('/api/room/:roomId', (req, res) => {
const room = rooms.get(req.params.roomId);
if (room) {
res.json({
exists: true,
userCount: room.users.size,
hostName: room.hostName,
name: room.name,
hasPassword: room.hasPassword
});
} else {
res.json({ exists: false });
}
});
// 获取所有房间列表 (大厅)
app.get('/api/rooms', (req, res) => {
const roomList = [];
rooms.forEach((room, id) => {
// 只显示有用户的房间
if (room.users.size > 0) {
roomList.push({
id,
name: room.name,
hostName: room.hostName,
userCount: room.users.size,
hasPassword: room.hasPassword,
createdAt: room.createdAt
});
}
});
// 按创建时间倒序排序
roomList.sort((a, b) => b.createdAt - a.createdAt);
res.json({
success: true,
rooms: roomList
});
});
// 广播房间列表更新
function broadcastRoomUpdate() {
const roomList = [];
rooms.forEach((room, id) => {
// 只显示有用户的房间
if (room.users.size > 0) {
roomList.push({
id,
name: room.name,
hostName: room.hostName,
userCount: room.users.size,
hasPassword: room.hasPassword,
createdAt: room.createdAt
});
}
});
// 按创建时间倒序排序
roomList.sort((a, b) => b.createdAt - a.createdAt);
io.emit('room-list-update', {
rooms: roomList
});
}
// ============ 通用视频解析 API ============
const videoParser = require('./parsers');
const https = require('https');
// 检查解析器状态
app.get('/api/parser/status', async (req, res) => {
try {
const ytdlpStatus = await videoParser.checkYtdlpAvailable();
res.json({
success: true,
parsers: {
ytdlp: ytdlpStatus.available,
ytdlpVersion: ytdlpStatus.version || null,
bilibili: true
},
supportedSites: videoParser.SUPPORTED_SITES
});
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// 获取视频信息(预览)
app.post('/api/parser/info', async (req, res) => {
const { url } = req.body;
if (!url) {
return res.status(400).json({ success: false, error: '缺少 URL' });
}
// 检查是否是 B站
if (url.includes('bilibili.com') || url.includes('b23.tv')) {
return res.json({
success: false,
redirect: 'bilibili',
error: 'B站视频请使用专用解析按钮'
});
}
try {
const info = await videoParser.getVideoInfo(url);
res.json({ success: true, data: info });
} catch (err) {
console.error('[视频解析] 获取信息失败:', err.message);
res.status(500).json({ success: false, error: err.message });
}
});
// 解析视频(获取播放地址或下载)
app.post('/api/parser/parse', async (req, res) => {
const { url, roomId, quality, forceDownload } = req.body;
if (!url) {
return res.status(400).json({ success: false, error: '缺少 URL' });
}
// 检测是否是 B站(使用专用解析器)
const parser = videoParser.detectParser(url);
if (parser === 'bilibili') {
return res.json({
success: false,
redirect: 'bilibili',
error: 'B站视频请使用专用解析按钮'
});
}
try {
const result = await videoParser.parseVideo(url, {
roomId,
quality,
forceDownload,
outputDir: uploadsDir,
onProgress: (progress) => {
// 通过 Socket.IO 推送进度
if (roomId) {
io.in(roomId).emit('parser-progress', {
url,
...progress
});
}
}
});
// 如果是下载到本地的视频,记录到房间(用于清理)
if (result.type === 'local' && roomId && result.filename) {
const room = rooms.get(roomId);
if (room) {
if (!room.parserFiles) room.parserFiles = [];
room.parserFiles.push(result.filename);
}
}
res.json({ success: true, data: result });
} catch (err) {
console.error('[视频解析] 失败:', err.message);
if (roomId) {
io.in(roomId).emit('parser-progress', {
url,
stage: 'error',
progress: 0,
message: err.message
});
}
res.status(500).json({ success: false, error: err.message });
}
});
// 视频流代理(处理防盗链和 CORS)
app.get('/api/parser/proxy', async (req, res) => {
const { url, referer } = req.query;
if (!url) {
return res.status(400).json({ error: '缺少视频 URL' });
}
try {
const urlObj = new URL(url);
const protocol = urlObj.protocol === 'https:' ? https : http;
const headers = {
'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',
'Referer': referer || urlObj.origin,
'Origin': urlObj.origin
};
// 转发 Range 请求
if (req.headers.range) {
headers['Range'] = req.headers.range;
}
const proxyReq = protocol.request({
hostname: urlObj.hostname,
port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: 'GET',
headers
}, (proxyRes) => {
res.status(proxyRes.statusCode);
// 设置 CORS 头
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Range');
// 判断是否是 m3u8 文件
const contentType = proxyRes.headers['content-type'] || '';
const isM3u8 = url.includes('.m3u8') || contentType.includes('mpegurl') || contentType.includes('m3u8');
if (isM3u8) {
// 收集 m3u8 内容并重写其中的 URL
let data = '';
proxyRes.setEncoding('utf8');
proxyRes.on('data', chunk => data += chunk);
proxyRes.on('end', () => {
const baseUrl = url.substring(0, url.lastIndexOf('/') + 1);
const proxyBase = `/api/parser/proxy?referer=${encodeURIComponent(referer || urlObj.origin)}&url=`;
// 重写相对路径和绝对路径
const rewritten = data.split('\n').map(line => {
line = line.trim();
if (!line || line.startsWith('#')) {
// 处理 #EXT-X-KEY 等标签中的 URI
if (line.includes('URI="')) {
return line.replace(/URI="([^"]+)"/g, (match, uri) => {
if (uri.startsWith('http://') || uri.startsWith('https://')) {
return `URI="${proxyBase}${encodeURIComponent(uri)}"`;
} else {
return `URI="${proxyBase}${encodeURIComponent(baseUrl + uri)}"`;
}
});
}
return line;
}
// 普通的 URL 行(ts 片段等)
if (line.startsWith('http://') || line.startsWith('https://')) {
return proxyBase + encodeURIComponent(line);
} else {
return proxyBase + encodeURIComponent(baseUrl + line);
}
}).join('\n');
res.setHeader('Content-Type', 'application/vnd.apple.mpegurl');
res.send(rewritten);
});
} else {
// 非 m3u8 文件直接转发
['content-type', 'content-length', 'content-range', 'accept-ranges']
.forEach(h => {
if (proxyRes.headers[h]) res.setHeader(h, proxyRes.headers[h]);
});
proxyRes.pipe(res);
}
});
proxyReq.on('error', (err) => {
console.error('[代理] 请求失败:', err.message);
if (!res.headersSent) {
res.status(500).json({ error: '代理请求失败' });
}
});
proxyReq.end();
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// 更新 yt-dlp
app.post('/api/parser/update', async (req, res) => {
try {
const result = await videoParser.updateYtdlp();
res.json(result);
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// ============ 解析规则管理 API ============
// 获取所有规则
app.get('/api/parser/rules', (req, res) => {
try {
const rules = videoParser.getRulesInfo();
res.json({ success: true, rules });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// 重新加载规则
app.post('/api/parser/rules/reload', (req, res) => {
try {
const rules = videoParser.reloadRules();
res.json({
success: true,
message: `已重新加载 ${rules.length} 条规则`,
count: rules.length
});
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// 添加用户规则
app.post('/api/parser/rules', (req, res) => {
try {
const { rule, filename } = req.body;
if (!rule) {
return res.status(400).json({ success: false, error: '规则内容不能为空' });
}
const result = videoParser.addUserRule(rule, filename);
res.json({
success: true,
message: '规则添加成功',
file: result.file
});
} catch (err) {
res.status(400).json({ success: false, error: err.message });
}
});
// 删除用户规则
app.delete('/api/parser/rules/:filename', (req, res) => {
try {
const { filename } = req.params;
videoParser.removeUserRule(filename);
res.json({ success: true, message: '规则已删除' });
} catch (err) {
res.status(400).json({ success: false, error: err.message });
}
});
// 测试规则
app.post('/api/parser/rules/test', async (req, res) => {
try {
const { rule, testUrl } = req.body;
if (!rule || !testUrl) {
return res.status(400).json({ success: false, error: '规则和测试 URL 不能为空' });
}
const result = await videoParser.testRule(rule, testUrl);
if (result) {
res.json({
success: true,
message: '规则测试成功',
result
});
} else {
res.json({
success: false,
error: '规则未能提取到视频地址'
});
}
} catch (err) {
res.status(400).json({ success: false, error: err.message });
}
});
// ============ OBS 直播推流 API ============
// 获取推流配置 (生成推流密钥)
app.post('/api/stream/start', (req, res) => {
const { roomId, socketId } = req.body;
if (!roomId || !socketId) {
return res.status(400).json({ success: false, error: '缺少必要参数' });
}
const room = rooms.get(roomId);
if (!room) {
return res.status(404).json({ success: false, error: '房间不存在' });
}
// 检查权限
const isHost = room.isHost(socketId);
if (!isHost && !room.settings.allowAllStream) {
return res.status(403).json({ success: false, error: '没有推流权限' });
}
// 检查是否已有人在推流
if (room.liveStreamState.isStreaming) {
return res.status(409).json({
success: false,
error: `${room.liveStreamState.streamerName} 正在直播中`
});
}
// 生成推流密钥
const streamKey = `${roomId}_${uuidv4().substring(0, 8)}`;
const user = room.users.get(socketId);
const userName = user ? user.name : '未知用户';
// 注册推流
const streamInfo = rtmpServer.registerStream(streamKey, {
roomId,
socketId,
userName
});
// 获取服务器主机名(用于显示给用户)
const host = req.headers.host ? req.headers.host.split(':')[0] : 'localhost';
res.json({
success: true,
data: {
rtmpUrl: `rtmp://${host}:${rtmpServer.getConfig().rtmpPort}/live`,
streamKey,
hlsUrl: streamInfo.hlsUrl
}
});
});
// 获取房间直播状态
app.get('/api/stream/status/:roomId', (req, res) => {
const { roomId } = req.params;
const room = rooms.get(roomId);
if (!room) {
return res.status(404).json({ success: false, error: '房间不存在' });
}
res.json({
success: true,
data: room.liveStreamState
});
});
// 停止推流
app.post('/api/stream/stop', (req, res) => {
const { roomId, socketId } = req.body;
if (!roomId || !socketId) {
return res.status(400).json({ success: false, error: '缺少必要参数' });
}
const room = rooms.get(roomId);
if (!room) {
return res.status(404).json({ success: false, error: '房间不存在' });
}
// 只有推流者本人或房主可以停止
const isHost = room.isHost(socketId);
const isStreamer = room.liveStreamState.streamerId === socketId;
if (!isHost && !isStreamer) {
return res.status(403).json({ success: false, error: '没有权限停止直播' });
}
if (!room.liveStreamState.isStreaming) {
return res.status(400).json({ success: false, error: '当前没有进行中的直播' });
}
// 注销推流密钥 (会自动断开 RTMP 连接)
if (room.liveStreamState.streamKey) {
rtmpServer.unregisterStream(room.liveStreamState.streamKey);
}
// 重置直播状态
const stoppedBy = room.users.get(socketId)?.name || '未知用户';
room.liveStreamState = {
isStreaming: false,
streamerId: null,
streamerName: null,
streamKey: null,
hlsUrl: null,
startedAt: null
};
// 通知房间内所有用户
io.in(roomId).emit('stream-stopped', { stoppedBy });
res.json({ success: true, message: '直播已停止' });
});
// ============ 定时清理过期文件 ============