forked from ihmily/DouyinLiveRecorder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1324 lines (1129 loc) · 60.4 KB
/
main.py
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
# -*- encoding: utf-8 -*-
"""
Author: Hmily
GitHub: https://github.com/ihmily
Date: 2023-07-17 23:52:05
Update: 2023-12-10 22:03:56
Copyright (c) 2023 by Hmily, All Rights Reserved.
Function: Record live stream video.
"""
import random
import os
import sys
import urllib.parse
import urllib.request
import configparser
import subprocess
import threading
import logging
import datetime
import time
import json
import re
import shutil
from spider import (
get_douyin_stream_data,
get_tiktok_stream_data,
get_kuaishou_stream_data,
get_kuaishou_stream_data2,
get_huya_stream_data,
get_douyu_info_data,
get_douyu_stream_data,
get_yy_stream_data,
get_bilibili_stream_data,
get_xhs_stream_url,
get_bigo_stream_url,
get_blued_stream_url,
get_afreecatv_stream_url
)
from web_rid import (
get_live_room_id,
get_sec_user_id
)
from utils import (
logger, check_md5,
trace_error_decorator
)
from msg_push import dingtalk, xizhi
version = "v2.0.7"
platforms = "抖音|TikTok|快手|虎牙|斗鱼|YY|B站|小红书|bigo直播|blued直播|AfreecaTV"
# --------------------------全局变量-------------------------------------
recording = set()
unrecording = set()
warning_count = 0
max_request = 0
monitoring = 0
runing_list = []
url_tuples_list = []
text_no_repeat_url = []
create_var = locals()
first_start = True
name_list = []
first_run = True
live_list = []
not_record_list = []
start_display_time = datetime.datetime.now()
global_proxy = False
recording_time_list = {}
config_file = './config/config.ini'
url_config_file = './config/URL_config.ini'
backup_dir = './backup_config'
encoding = 'utf-8-sig'
rstr = r"[\/\\\:\*\?\"\<\>\|&u]"
ffmpeg_path = "ffmpeg" # ffmpeg文件路径
default_path = os.getcwd()
# --------------------------用到的函数-------------------------------------
def display_info():
# TODO: 显示当前录制配置信息
global start_display_time
global recording_time_list
time.sleep(5)
while True:
try:
time.sleep(5)
os.system("cls")
print(f"\r共监测{monitoring}个直播中", end=" | ")
print(f"同一时间访问网络的线程数: {max_request}", end=" | ")
if len(video_save_path) > 0:
if not os.path.exists(video_save_path):
print("配置文件里,直播保存路径并不存在,请重新输入一个正确的路径.或留空表示当前目录,按回车退出")
input("程序结束")
sys.exit(0)
print(f"是否开启代理录制: {'是' if use_proxy else '否'}", end=" | ")
if split_video_by_time:
print(f"录制分段开启: {split_time}秒", end=" | ")
print(f"是否生成时间文件: {'是' if create_time_file else '否'}", end=" | ")
print(f"录制视频质量为: {video_quality}", end=" | ")
print(f"录制视频格式为: {video_save_type}", end=" | ")
print(f"目前瞬时错误数为: {warning_count}", end=" | ")
format_now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"当前时间: {format_now_time}")
if len(recording) == 0 and len(unrecording) == 0:
time.sleep(5)
print(f"\r没有正在录制的直播 {format_now_time[-8:]}", end="")
print("")
continue
else:
now_time = datetime.datetime.now()
if len(recording) > 0:
print("x" * 60)
no_repeat_recording = list(set(recording))
print(f"正在录制{len(no_repeat_recording)}个直播: ")
for recording_live in no_repeat_recording:
have_record_time = now_time - recording_time_list[recording_live]
print(f"{recording_live} 正在录制中 " + str(have_record_time).split('.')[0])
# print('\n本软件已运行:'+str(now_time - start_display_time).split('.')[0])
print("x" * 60)
else:
start_display_time = now_time
except Exception as e:
print(f"错误信息:{e}\r\n发生错误的行数: {e.__traceback__.tb_lineno}")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
def update_file(file, old_str, new_str):
# TODO: 更新文件操作
file_data = ""
with open(file, "r", encoding="utf-8-sig") as f:
for text_line in f:
if old_str in text_line:
text_line = text_line.replace(old_str, new_str)
file_data += text_line
with open(file, "w", encoding="utf-8-sig") as f:
f.write(file_data)
def converts_mp4(address):
if tsconvert_to_mp4:
_output = subprocess.check_output([
"ffmpeg", "-i", address,
"-c:v", "copy",
"-c:a", "copy",
"-f", "mp4", address.split('.')[0] + ".mp4",
], stderr=subprocess.STDOUT)
if delete_origin_file:
time.sleep(1)
if os.path.exists(address):
os.remove(address)
def converts_m4a(address):
if tsconvert_to_m4a:
_output = subprocess.check_output([
"ffmpeg", "-i", address,
"-n", "-vn",
"-c:a", "aac", "-bsf:a", "aac_adtstoasc", "-ab", "320k",
address.split('.')[0] + ".m4a",
], stderr=subprocess.STDOUT)
if delete_origin_file:
time.sleep(1)
if os.path.exists(address):
os.remove(address)
def create_ass_file(filegruop):
# TODO: 录制时生成ass格式的字幕文件
anchor_name = filegruop[0]
ass_filename = filegruop[1]
index_time = -1
finish = 0
today = datetime.datetime.now()
re_datatime = today.strftime('%Y-%m-%d %H:%M:%S')
while True:
index_time += 1
txt = str(index_time) + "\n" + transform_int_to_time(index_time) + ',000 --> ' + transform_int_to_time(
index_time + 1) + ',000' + "\n" + str(re_datatime) + "\n"
with open(ass_filename + ".ass", 'a', encoding='utf8') as f:
f.write(txt)
if anchor_name not in recording:
finish += 1
offset = datetime.timedelta(seconds=1)
# 获取修改后的时间并格式化
re_datatime = (today + offset).strftime('%Y-%m-%d %H:%M:%S')
today = today + offset
else:
time.sleep(1)
today = datetime.datetime.now()
re_datatime = today.strftime('%Y-%m-%d %H:%M:%S')
if finish > 15:
break
def change_max_connect():
global max_request
global warning_count
# 动态控制连接次数
preset = max_request
# 记录当前时间
start_time = time.time()
while True:
time.sleep(5)
if 10 <= warning_count <= 20:
if preset > 5:
max_request = 5
else:
max_request //= 2 # 将max_request除以2(向下取整)
if max_request > 0: # 如果得到的结果大于0,则直接取该结果
max_request = preset
else: # 否则将其设置为1
preset = 1
print("同一时间访问网络的线程数动态改为", max_request)
warning_count = 0
time.sleep(5)
elif 20 < warning_count:
max_request = 1
print("同一时间访问网络的线程数动态改为", max_request)
warning_count = 0
time.sleep(10)
elif warning_count < 10 and time.time() - start_time > 60:
max_request = preset
warning_count = 0
start_time = time.time()
print("同一时间访问网络的线程数动态改为", max_request)
@trace_error_decorator
def get_douyin_stream_url(json_data):
# TODO: 获取抖音直播源地址
anchor_name = json_data.get('anchor_name', None)
result = {
"anchor_name": anchor_name,
"is_live": False,
}
status = json_data.get("status", 4) # 直播状态 2 是正在直播、4 是未开播
if status == 2:
stream_url = json_data['stream_url']
flv_url_list = stream_url['flv_pull_url']
m3u8_url_list = stream_url['hls_pull_url_map']
# video_qualities = {
# "原画": "FULL_HD1",
# "蓝光": "FULL_HD1",
# "超清": "HD1",
# "高清": "SD1",
# "标清": "SD2",
# }
quality_list = list(m3u8_url_list.keys())
while len(quality_list) < 4:
quality_list.append(quality_list[-1])
video_qualities = {"原画": 0, "蓝光": 0, "超清": 1, "高清": 2, "标清": 3}
quality_index = video_qualities.get(video_quality)
quality_key = quality_list[quality_index]
m3u8_url = m3u8_url_list.get(quality_key)
flv_url = flv_url_list.get(quality_key)
result['m3u8_url'] = m3u8_url
result['flv_url'] = flv_url
result['is_live'] = True
result['record_url'] = m3u8_url # 使用 m3u8 链接进行录制
return result
@trace_error_decorator
def get_tiktok_stream_url(json_data):
# TODO: 获取tiktok直播源地址
def get_video_quality_url(stream_data, quality_key):
return {
'hls': re.sub("https", "http", stream_data[quality_key]['main']['hls']),
'flv': re.sub("https", "http", stream_data[quality_key]['main']['flv']),
}
live_room = json_data['LiveRoom']['liveRoomUserInfo']
user = live_room['user']
anchor_name = user['nickname']
status = user.get("status", 4)
result = {
"anchor_name": anchor_name,
"is_live": False,
}
if status == 2:
stream_data = live_room.get('liveRoom', {}).get('streamData', {}).get('pull_data', {}).get('stream_data', '{}')
stream_data = json.loads(stream_data).get('data', {})
quality_list: list = list(stream_data.keys()) # ["origin","uhd","sd","ld"]
while len(quality_list) < 4:
quality_list.append(quality_list[-1])
video_qualities = {"原画": 0, "蓝光": 0, "超清": 1, "高清": 2, "标清": 3}
quality_index = video_qualities.get(video_quality)
quality_key = quality_list[quality_index]
video_quality_urls = get_video_quality_url(stream_data, quality_key)
result['flv_url'] = video_quality_urls['flv']
result['m3u8_url'] = video_quality_urls['hls']
result['is_live'] = True
result['record_url'] = result['flv_url'] if result['flv_url'] else result['m3u8_url']
result['record_url'] = re.sub("only_audio=1", "only_audio=0", result['record_url'])
return result
@trace_error_decorator
def get_kuaishou_stream_url(json_data):
# TODO: 获取快手直播源地址
if json_data['type'] == 1:
return json_data
live_status = json_data['is_live']
result = {
"type": 2,
"anchor_name": json_data['anchor_name'],
"is_live": live_status,
}
if live_status:
quality_mapping = {'原画': 0, '蓝光': 0, '超清': 1, '高清': 2, '标清': 3, }
if video_quality in quality_mapping:
quality_index = quality_mapping[video_quality]
if 'm3u8_url_list' in json_data:
m3u8_url_list = json_data['m3u8_url_list'][::-1]
while len(m3u8_url_list) < 4:
m3u8_url_list.append(m3u8_url_list[-1])
m3u8_url = m3u8_url_list[quality_index]['url']
else:
m3u8_url = json_data['backup']['m3u8_url']
if 'flv_url_list' in json_data:
flv_url_list = json_data['flv_url_list'][::-1]
while len(flv_url_list) < 4:
flv_url_list.append(flv_url_list[-1])
flv_url = flv_url_list[quality_index]['url']
else:
flv_url = json_data['backup']['flv_url']
result['flv_url'] = flv_url
result['m3u8_url'] = m3u8_url
result['is_live'] = True
result['record_url'] = flv_url if flv_url else m3u8_url
return result
@trace_error_decorator
def get_huya_stream_url(json_data):
# TODO: 获取虎牙直播源地址
game_live_info = json_data.get('data', [])[0].get('gameLiveInfo', {})
stream_info_list = json_data.get('data', [])[0].get('gameStreamInfoList', [])
anchor_name = game_live_info.get('nick', '')
result = {
"anchor_name": anchor_name,
"is_live": False,
}
if stream_info_list:
select_cdn = stream_info_list[0]
flv_url = select_cdn.get('sFlvUrl')
stream_name = select_cdn.get('sStreamName')
flv_url_suffix = select_cdn.get('sFlvUrlSuffix')
hls_url = select_cdn.get('sHlsUrl')
hls_url_suffix = select_cdn.get('sHlsUrlSuffix')
flv_anti_code = select_cdn.get('sFlvAntiCode')
flv_url = f'{flv_url}/{stream_name}.{flv_url_suffix}?{flv_anti_code}&ratio='
m3u8_url = f'{hls_url}/{stream_name}.{hls_url_suffix}?{flv_anti_code}&ratio='
quality_list = flv_anti_code.split('&exsphd=')
if len(quality_list) > 1:
pattern = r"(?<=264_)\d+"
quality_list = [x for x in re.findall(pattern, quality_list[1])][::-1]
while len(quality_list) < 4:
quality_list.append(quality_list[-1])
video_quality_options = {
"原画": quality_list[0],
"蓝光": quality_list[0],
"超清": quality_list[1],
"高清": quality_list[2],
"标清": quality_list[3]
}
if video_quality not in video_quality_options:
raise ValueError(
f"Invalid video quality. Available options are: {', '.join(video_quality_options.keys())}")
flv_url = flv_url + str(video_quality_options[video_quality])
m3u8_url = m3u8_url + str(video_quality_options[video_quality])
result['flv_url'] = flv_url
result['m3u8_url'] = m3u8_url
result['is_live'] = True
result['record_url'] = flv_url # 虎牙使用flv视频流录制
return result
@trace_error_decorator
def get_douyu_stream_url(json_data, cookies):
# TODO: 获取斗鱼直播源地址
video_quality_options = {
"原画": '0',
"蓝光": '0',
"超清": '3',
"高清": '2',
"标清": '1'
}
room_info = json_data.get('pageContext', json_data)['pageProps']['room']['roomInfo']['roomInfo']
anchor_name = room_info.get('nickname', '')
status = room_info.get('isLive', False)
result = {
"anchor_name": anchor_name,
"is_live": False,
}
# 如果status值为1,则正在直播
# 这边有个bug,就是如果是直播回放,状态也是在直播 待修复
if status == 1:
rid = str(room_info['rid'])
rate = video_quality_options.get(video_quality, '0') # 默认为原画
flv_data = get_douyu_stream_data(rid, rate, cookies)
flv_url = flv_data['data'].get('url', None)
if flv_url:
result['flv_url'] = flv_url
result['is_live'] = True
result['record_url'] = flv_url # 斗鱼目前只能使用flv视频流录制
return result
@trace_error_decorator
def get_yy_stream_url(json_data):
# TODO: 获取YY直播源地址
anchor_name = json_data.get('anchor_name', '')
result = {
"anchor_name": anchor_name,
"is_live": False,
}
if 'avp_info_res' in json_data:
stream_line_addr = json_data['avp_info_res']['stream_line_addr']
# 获取最后一个键的值
cdn_info = list(stream_line_addr.values())[0]
flv_url = cdn_info['cdn_info']['url'] # 清晰度暂时默认高清
result['flv_url'] = flv_url
result['is_live'] = True
result['record_url'] = flv_url
return result
@trace_error_decorator
def get_bilibili_stream_url(json_data):
# TODO: 获取B站直播源地址
anchor_name = json_data.get('roomInfoRes', {}).get('data', {}).get('anchor_info', {}).get('base_info', {}).get(
'uname', '')
playurl_info = json_data['roomInitRes']['data']['playurl_info']
result = {
"anchor_name": anchor_name,
"is_live": False,
}
if playurl_info:
def get_url(m, n):
format_list = ['.flv', '.m3u8']
# 字典中的键就是qn,其中qn=30000为杜比 20000为4K 10000为原画 400蓝光 250超清 150高清,qn=0是默认画质
quality_list = {'10000': '', '400': '_4000', '250': '_2500', '150': '_1500'}
stream_data = playurl_info['playurl']['stream'][m]['format'][0]['codec'][0]
accept_qn_list = stream_data['accept_qn']
while len(accept_qn_list) < 4:
accept_qn_list.append(accept_qn_list[-1])
base_url = stream_data['base_url']
host = stream_data['url_info'][0]['host']
extra = stream_data['url_info'][0]['extra']
url_type = format_list[m]
qn = str(accept_qn_list[n])
quality = quality_list[qn]
base_url = re.sub(r'_(\d+)' + f'(?={url_type}\?)', quality, base_url)
extra = re.sub('&qn=0', f'&qn={qn}', extra)
url = host + base_url + extra
return url
if video_quality == "原画" or video_quality == "蓝光":
flv_url = get_url(0, 0)
m3u8_url = get_url(1, 0)
elif video_quality == "超清":
flv_url = get_url(0, 1)
m3u8_url = get_url(1, 1)
elif video_quality == "高清":
flv_url = get_url(0, 2)
m3u8_url = get_url(1, 2)
elif video_quality == "标清":
flv_url = get_url(0, 3)
m3u8_url = get_url(1, 3)
else:
flv_url = get_url(0, 0)
m3u8_url = get_url(1, 0)
result['flv_url'] = flv_url
result['m3u8_url'] = m3u8_url
result['is_live'] = True
result['record_url'] = m3u8_url # B站使用m3u8链接进行录制
return result
def start_record(url_tuple, count_variable=-1):
global warning_count
global video_save_path
global live_list
global not_record_list
global recording_time_list
while True:
try:
record_finished = False
record_finished_2 = False
run_once = False
is_long_url = False
no_error = True
new_record_url = ''
count_time = time.time()
record_url = url_tuple[0]
anchor_name = url_tuple[1]
print(f"\r运行新线程,传入地址 {record_url}")
while True:
try:
port_info = []
if record_url.find("https://live.douyin.com/") > -1:
# 判断如果是浏览器长链接
with semaphore:
# 使用semaphore来控制同时访问资源的线程数量
json_data = get_douyin_stream_data(record_url, dy_cookie)
port_info = get_douyin_stream_url(json_data)
elif record_url.find("https://v.douyin.com/") > -1:
# 判断如果是app分享链接
is_long_url = True
room_id, sec_user_id = get_sec_user_id(record_url)
web_rid = get_live_room_id(room_id, sec_user_id)
if len(web_rid) == 0:
print('web_rid 获取失败,若多次失败请联系作者修复或者使用浏览器打开后的长链接')
new_record_url = "https://live.douyin.com/" + str(web_rid)
not_record_list.append(new_record_url)
with semaphore:
json_data = get_douyin_stream_data(new_record_url, dy_cookie)
port_info = get_douyin_stream_url(json_data)
elif record_url.find("https://www.tiktok.com/") > -1:
with semaphore:
if use_proxy:
if global_proxy or proxy_addr != '':
json_data = get_tiktok_stream_data(record_url, proxy_addr, tiktok_cookie)
port_info = get_tiktok_stream_url(json_data)
elif record_url.find("https://live.kuaishou.com/") > -1:
with semaphore:
json_data = get_kuaishou_stream_data(record_url, ks_cookie)
port_info = get_kuaishou_stream_url(json_data)
elif record_url.find("https://www.huya.com/") > -1:
with semaphore:
json_data = get_huya_stream_data(record_url, hy_cookie)
port_info = get_huya_stream_url(json_data)
elif record_url.find("https://www.douyu.com/") > -1:
with semaphore:
json_data = get_douyu_info_data(record_url)
port_info = get_douyu_stream_url(json_data, douyu_cookie)
elif record_url.find("https://www.yy.com/") > -1:
with semaphore:
json_data = get_yy_stream_data(record_url, yy_cookie)
port_info = get_yy_stream_url(json_data)
elif record_url.find("https://live.bilibili.com/") > -1:
with semaphore:
json_data = get_bilibili_stream_data(record_url, bili_cookie)
port_info = get_bilibili_stream_url(json_data)
elif record_url.find("https://www.xiaohongshu.com/") > -1:
with semaphore:
port_info = get_xhs_stream_url(record_url, xhs_cookie)
elif record_url.find("https://www.bigo.tv/") > -1:
with semaphore:
port_info = get_bigo_stream_url(record_url, bigo_cookie)
elif record_url.find("https://app.blued.cn/") > -1:
with semaphore:
port_info = get_blued_stream_url(record_url, blued_cookie)
elif record_url.find("afreecatv.com/") > -1:
with semaphore:
port_info = get_afreecatv_stream_url(record_url, afreecatv_cookie)
if anchor_name:
anchor_split = anchor_name.split('主播:')
if len(anchor_split) > 1 and anchor_split[1].strip():
anchor_name = anchor_split[1].strip()
else:
anchor_name = port_info.get("anchor_name", '')
else:
anchor_name = port_info.get("anchor_name", '')
if anchor_name == '':
print(f'序号{count_variable} 网址内容获取失败,进行重试中...获取失败的地址是:{url_tuple}')
warning_count += 1
else:
anchor_name = re.sub(rstr, "_", anchor_name) # 过滤不能作为文件名的字符,替换为下划线
record_name = f'序号{count_variable} {anchor_name}'
if anchor_name in recording:
print(f"新增的地址: {anchor_name} 已经存在,本条线程将会退出")
name_list.append(f'{record_url}|#{record_url}')
return
if url_tuple[1] == "" and run_once is False:
if is_long_url:
name_list.append(f'{record_url}|{new_record_url},主播: {anchor_name.strip()}')
else:
name_list.append(f'{record_url}|{record_url},主播: {anchor_name.strip()}')
run_once = True
if port_info['is_live'] is False:
print(f"{record_name} 等待直播... ")
else:
content = f"{record_name} 正在直播中..."
print(content)
# 推送通知
if live_status_push:
if '微信' in live_status_push:
xizhi(xizhi_api_url, content)
if '钉钉' in live_status_push:
dingtalk(dingtalk_api_url, content, dingtalk_phone_num)
real_url = port_info['record_url']
full_path = f'{default_path}/{anchor_name}'
if real_url != "":
live_list.append(anchor_name)
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime(time.time()))
try:
if len(video_save_path) > 0:
if video_save_path[-1] != "/":
video_save_path = video_save_path + "/"
else:
video_save_path = default_path + '/'
video_save_path = video_save_path.replace("\\", "/")
full_path = f'{video_save_path}{anchor_name}'
if not os.path.exists(full_path):
os.makedirs(full_path)
except Exception as e:
print(f"路径错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
if not os.path.exists(full_path):
print(
"保存路径不存在,不能生成录制.请避免把本程序放在c盘,桌面,下载文件夹,qq默认传输目录.请重新检查设置")
logger.warning(
"错误信息: 保存路径不存在,不能生成录制.请避免把本程序放在c盘,桌面,下载文件夹,qq默认传输目录.请重新检查设置")
user_agent = ("Mozilla/5.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 ("
"KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile "
"Safari/537.36")
ffmpeg_command = [
ffmpeg_path, "-y",
"-v", "verbose",
"-rw_timeout", "15000000", # 15s
"-loglevel", "error",
"-hide_banner",
"-user_agent", user_agent,
"-protocol_whitelist", "rtmp,crypto,file,http,https,tcp,tls,udp,rtp",
"-thread_queue_size", "1024",
"-analyzeduration", "2147483647",
"-probesize", "2147483647",
"-fflags", "+discardcorrupt",
"-i", real_url,
"-bufsize", "5000k",
"-sn", "-dn",
"-reconnect_delay_max", "30",
"-reconnect_streamed", "-reconnect_at_eof",
"-max_muxing_queue_size", "64",
"-correct_ts_overflow", "1",
]
# 添加代理参数
need_proxy_url = ['tiktok', 'afreecatv']
for i in need_proxy_url:
if i in real_url:
if use_proxy and proxy_addr != '':
# os.environ["http_proxy"] = proxy_addr
ffmpeg_command.insert(1, "-http_proxy")
ffmpeg_command.insert(2, proxy_addr)
break
recording.add(record_name)
start_record_time = datetime.datetime.now()
recording_time_list[record_name] = start_record_time
rec_info = f"\r{anchor_name} 录制视频中: {full_path}"
filename_short = full_path + '/' + anchor_name + '_' + now
if video_save_type == "FLV":
filename = anchor_name + '_' + now + '.flv'
print(f'{rec_info}/{filename}')
if create_time_file:
filename_gruop = [anchor_name, filename_short]
create_var[str(filename_short)] = threading.Thread(target=create_ass_file,
args=(filename_gruop,))
create_var[str(filename_short)].daemon = True
create_var[str(filename_short)].start()
try:
flv_url = port_info.get('flv_url', None)
if flv_url:
_filepath, _ = urllib.request.urlretrieve(real_url,
full_path + '/' + filename)
else:
raise Exception('该直播无flv直播流,请切换视频保存类型')
except Exception as e:
print(f"\r{time.strftime('%Y-%m-%d %H:%M:%S')} {anchor_name} 未开播")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
warning_count += 1
no_error = False
elif video_save_type == "MKV":
filename = anchor_name + '_' + now + ".mkv"
print(f'{rec_info}/{filename}')
save_file_path = full_path + '/' + filename
try:
if split_video_by_time:
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
save_file_path = f"{full_path}/{anchor_name}_{now}_%03d.mkv"
command = [
"-c:v", "copy",
"-c:a", "aac",
"-map", "0",
"-f", "segment",
"-segment_time", split_time,
"-segment_format", "matroska",
"-reset_timestamps", "1",
save_file_path,
]
else:
if create_time_file:
filename_gruop = [anchor_name, filename_short]
create_var[str(filename_short)] = threading.Thread(
target=create_ass_file,
args=(filename_gruop,))
create_var[str(filename_short)].daemon = True
create_var[str(filename_short)].start()
command = [
"-map", "0",
"-c:v", "copy",
"-c:a", "copy",
"-f", "matroska",
"{path}".format(path=save_file_path),
]
ffmpeg_command.extend(command)
_output = subprocess.check_output(ffmpeg_command, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
# logging.warning(str(e.output))
print(f"{e.output} 发生错误的行数: {e.__traceback__.tb_lineno}")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
warning_count += 1
no_error = False
elif video_save_type == "MP4":
filename = anchor_name + '_' + now + ".mp4"
print(f'{rec_info}/{filename}')
save_file_path = full_path + '/' + filename
try:
if split_video_by_time:
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
save_file_path = f"{full_path}/{anchor_name}_{now}_%03d.mp4"
command = [
"-c:v", "copy",
"-c:a", "aac",
"-map", "0",
"-f", "segment",
"-segment_time", split_time,
"-segment_format", "mp4",
"-movflags", "+faststart",
"-reset_timestamps", "1",
save_file_path,
]
else:
if create_time_file:
filename_gruop = [anchor_name, filename_short]
create_var[str(filename_short)] = threading.Thread(
target=create_ass_file,
args=(filename_gruop,))
create_var[str(filename_short)].daemon = True
create_var[str(filename_short)].start()
command = [
"-map", "0",
"-c:v", "copy",
"-c:a", "copy",
"-f", "mp4",
"{path}".format(path=save_file_path),
]
ffmpeg_command.extend(command)
_output = subprocess.check_output(ffmpeg_command, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
# logging.warning(str(e.output))
print(f"{e.output} 发生错误的行数: {e.__traceback__.tb_lineno}")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
warning_count += 1
no_error = False
elif video_save_type == "MKV音频":
filename = anchor_name + '_' + now + ".mkv"
print(f'{rec_info}/{filename}')
save_file_path = full_path + '/' + filename
try:
command = [
"-map", "0:a",
"-c:a", "copy",
"-f", "matroska",
"{path}".format(path=save_file_path),
]
ffmpeg_command.extend(command)
_output = subprocess.check_output(ffmpeg_command, stderr=subprocess.STDOUT)
if tsconvert_to_m4a:
threading.Thread(target=converts_m4a, args=(file,)).start()
except subprocess.CalledProcessError as e:
# logging.warning(str(e.output))
print(f"{e.output} 发生错误的行数: {e.__traceback__.tb_lineno}")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
warning_count += 1
no_error = False
elif video_save_type == "TS音频":
filename = anchor_name + '_' + now + ".ts"
print(f'{rec_info}/{filename}')
save_file_path = full_path + '/' + filename
try:
command = [
"-map", "0:a",
"-c:a", "copy",
"-f", "mpegts",
"{path}".format(path=save_file_path),
]
ffmpeg_command.extend(command)
_output = subprocess.check_output(ffmpeg_command, stderr=subprocess.STDOUT)
if tsconvert_to_m4a:
threading.Thread(target=converts_m4a, args=(file,)).start()
except subprocess.CalledProcessError as e:
# logging.warning(str(e.output))
print(f"{e.output} 发生错误的行数: {e.__traceback__.tb_lineno}")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
warning_count += 1
no_error = False
else:
if split_video_by_time:
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
filename = anchor_name + '_' + now + ".ts"
print(f'{rec_info}/{filename}')
try:
if tsconvert_to_mp4:
save_path_name = f"{full_path}/{anchor_name}_{now}_%03d.mp4"
audio_code = 'aac'
segment_format = 'mp4'
else:
save_path_name = f"{full_path}/{anchor_name}_{now}_%03d.ts"
audio_code = 'copy'
segment_format = 'mpegts'
command = [
"-c:v", "copy",
"-c:a", audio_code,
"-map", "0",
"-f", "segment",
"-segment_time", split_time,
"-segment_format", segment_format,
"-reset_timestamps", "1",
save_path_name,
]
ffmpeg_command.extend(command)
_output = subprocess.check_output(ffmpeg_command,
stderr=subprocess.STDOUT)
if tsconvert_to_mp4:
threading.Thread(target=converts_mp4, args=(file,)).start()
if tsconvert_to_m4a:
threading.Thread(target=converts_m4a, args=(file,)).start()
except subprocess.CalledProcessError as e:
logging.warning(str(e.output))
logger.warning(
f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
warning_count += 1
no_error = False
else:
filename = anchor_name + '_' + now + ".ts"
print(f'{rec_info}/{filename}')
save_file_path = full_path + '/' + filename
if create_time_file:
filename_gruop = [anchor_name, filename_short]
create_var[str(filename_short)] = threading.Thread(target=create_ass_file,
args=(filename_gruop,))
create_var[str(filename_short)].daemon = True
create_var[str(filename_short)].start()
try:
command = [
"-c:v", "copy",
"-c:a", "copy",
"-map", "0",
"-f", "mpegts",
"{path}".format(path=save_file_path),
]
ffmpeg_command.extend(command)
_output = subprocess.check_output(ffmpeg_command, stderr=subprocess.STDOUT)
if tsconvert_to_mp4:
threading.Thread(target=converts_mp4, args=(file,)).start()
if tsconvert_to_m4a:
threading.Thread(target=converts_m4a, args=(file,)).start()
except subprocess.CalledProcessError as e:
# logging.warning(str(e.output))
print(f"{e.output} 发生错误的行数: {e.__traceback__.tb_lineno}")
logger.warning(f"错误信息: {e} 发生错误的行数: {e.__traceback__.tb_lineno}")
warning_count += 1
no_error = False
record_finished = True
record_finished_2 = True
count_time = time.time()
if record_finished_2:
if record_name in recording:
recording.remove(record_name)
if anchor_name in unrecording:
unrecording.add(anchor_name)
if no_error:
print(f"\n{anchor_name} {time.strftime('%Y-%m-%d %H:%M:%S')} 直播录制完成\n")
else:
print(
f"\n{anchor_name} {time.strftime('%Y-%m-%d %H:%M:%S')} 直播录制出错,请检查网络\n")
record_finished_2 = False
# 推送通知
content = f"{record_name} 直播已结束"
if live_status_push:
if '微信' in live_status_push:
xizhi(xizhi_api_url, content)
if '钉钉' in live_status_push:
dingtalk(dingtalk_api_url, content, dingtalk_phone_num)