forked from ihmily/DouyinLiveRecorder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1752 lines (1542 loc) · 89.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: SAOJSM
GitHub: https://github.com/SAOJSM
Date: 2023-07-17 23:52:05
Update: 2024-11-25 02:17:00
Copyright (c) 2023-2024 by SAOJSM, All Rights Reserved.
Function: Record live stream video.
"""
import os
import sys
import builtins
import subprocess
import signal
import threading
import time
import datetime
import re
import shutil
import random
import uuid
from pathlib import Path
import urllib.parse
import urllib.request
from urllib.error import URLError, HTTPError
from typing import Any
import configparser
from douyinliverecorder import spider
from douyinliverecorder import stream
from douyinliverecorder.utils import logger
from douyinliverecorder import utils
from msg_push import (
dingtalk, xizhi, tg_bot, send_email, bark, ntfy
)
version = "v4.0.1"
platforms = ("\n國內站點:抖音|快手|虎牙|斗魚|YY|B站|小紅書|bigo|blued|網易CC|千度熱播|貓耳FM|Look|TwitCasting|百度|微博|"
"酷狗|花椒|流星|Acfun|暢聊|映客|音播|知乎|嗨秀|VV星球|17Live|浪Live|漂漂|六間房|樂嗨|花貓"
"\n海外站點:TikTok|SOOP|PandaTV|WinkTV|FlexTV|PopkonTV|TwitchTV|LiveMe|ShowRoom|CHZZK")
recording = set()
error_count = 0
pre_max_request = 10
max_request_lock = threading.Lock()
error_window = []
error_window_size = 10
error_threshold = 5
monitoring = 0
running_list = []
url_tuples_list = []
url_comments = []
text_no_repeat_url = []
create_var = locals()
first_start = True
exit_recording = False
need_update_line_list = []
first_run = True
not_record_list = []
start_display_time = datetime.datetime.now()
global_proxy = False
recording_time_list = {}
script_path = os.path.split(os.path.realpath(sys.argv[0]))[0]
config_file = f'{script_path}/config/config.ini'
url_config_file = f'{script_path}/config/URL_config.ini'
backup_dir = f'{script_path}/backup_config'
text_encoding = 'utf-8-sig'
rstr = r"[\/\\\:\*\?\"\<\>\|&#.。,, ~!·]"
ffmpeg_path = f"{script_path}/ffmpeg.exe"
default_path = f'{script_path}/downloads'
os.makedirs(default_path, exist_ok=True)
file_update_lock = threading.Lock()
os_type = os.name
clear_command = "cls" if os_type == 'nt' else "clear"
def signal_handler(_signal, _frame):
sys.exit(0)
signal.signal(signal.SIGTERM, signal_handler)
def display_info() -> None:
global start_display_time
time.sleep(5)
while True:
try:
time.sleep(5)
if Path(sys.executable).name != 'pythonw.exe':
os.system(clear_command)
print(f"\r共監測{monitoring}個直播中", end=" | ")
print(f"同一時間訪問網路的線程數: {max_request}", end=" | ")
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_record_quality}", end=" | ")
print(f"錄製視頻格式為: {video_save_type}", end=" | ")
print(f"目前瞬時錯誤數為: {error_count}", end=" | ")
now = time.strftime("%H:%M:%S", time.localtime())
print(f"當前時間: {now}")
if len(recording) == 0:
time.sleep(5)
if monitoring == 0:
print("\r沒有正在監測和錄製的直播")
else:
print(f"\r沒有正在錄製的直播 循環監測間隔時間:{delay_default}秒")
else:
now_time = datetime.datetime.now()
print("x" * 60)
no_repeat_recording = list(set(recording))
print(f"正在錄製{len(no_repeat_recording)}個直播: ")
for recording_live in no_repeat_recording:
rt, qa = recording_time_list[recording_live]
have_record_time = now_time - rt
print(f"{recording_live}[{qa}] 正在錄製中 {str(have_record_time).split('.')[0]}")
# print('\n本軟件已運行:'+str(now_time - start_display_time).split('.')[0])
print("x" * 60)
start_display_time = now_time
except Exception as e:
logger.error(f"錯誤訊息: {e} 發生錯誤的行數: {e.__traceback__.tb_lineno}")
def update_file(file_path: str, old_str: str, new_str: str, start_str: str = None) -> str | None:
if old_str == new_str and start_str is None:
return old_str
with file_update_lock:
file_data = []
with open(file_path, "r", encoding=text_encoding) as f:
try:
for text_line in f:
if old_str in text_line:
text_line = text_line.replace(old_str, new_str)
if start_str:
text_line = f'{start_str}{text_line}'
if text_line not in file_data:
file_data.append(text_line)
except RuntimeError as e:
logger.error(f"錯誤訊息: {e} 發生錯誤的行數: {e.__traceback__.tb_lineno}")
if ini_URL_content:
with open(file_path, "w", encoding=text_encoding) as f2:
f2.write(ini_URL_content)
return old_str
if file_data:
with open(file_path, "w", encoding=text_encoding) as f:
f.write(''.join(file_data))
return new_str
def delete_line(file_path: str, del_line: str, delete_all: bool = False) -> None:
with file_update_lock:
with open(file_path, 'r+', encoding=text_encoding) as f:
lines = f.readlines()
f.seek(0)
f.truncate()
skip_line = False
for txt_line in lines:
if del_line in txt_line:
if delete_all or not skip_line:
skip_line = True
continue
else:
skip_line = False
f.write(txt_line)
def get_startup_info(system_type: str):
if system_type == 'nt':
startup_info = subprocess.STARTUPINFO()
startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
else:
startup_info = None
return startup_info
def converts_mp4(address: str, is_original_delete: bool = True) -> None:
_output = subprocess.check_output([
"ffmpeg", "-i", address,
"-c:v", "copy",
"-c:a", "copy",
"-f", "mp4", address.rsplit('.', maxsplit=1)[0] + ".mp4",
], stderr=subprocess.STDOUT, startupinfo=get_startup_info(os_type))
if is_original_delete:
time.sleep(1)
if os.path.exists(address):
os.remove(address)
def converts_m4a(address: str, is_original_delete: bool = True) -> None:
_output = subprocess.check_output([
"ffmpeg", "-i", address,
"-n", "-vn",
"-c:a", "aac", "-bsf:a", "aac_adtstoasc", "-ab", "320k",
address.rsplit('.', maxsplit=1)[0] + ".m4a",
], stderr=subprocess.STDOUT, startupinfo=get_startup_info(os_type))
if is_original_delete:
time.sleep(1)
if os.path.exists(address):
os.remove(address)
def generate_subtitles(record_name: str, ass_filename: str, sub_format: str = 'srt') -> None:
index_time = 0
today = datetime.datetime.now()
re_datatime = today.strftime('%Y%m%d')
def transform_int_to_time(seconds: int) -> str:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return f"{h:02d}:{m:02d}:{s:02d}"
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\n"
with open(f"{ass_filename}.{sub_format.lower()}", 'a', encoding=text_encoding) as f:
f.write(txt)
if record_name not in recording:
return
time.sleep(1)
today = datetime.datetime.now()
re_datatime = today.strftime('%Y-%m-%d %H:%M:%S')
def adjust_max_request() -> None:
global max_request, error_count, pre_max_request, error_window
preset = max_request
while True:
time.sleep(5)
with max_request_lock:
if error_window:
error_rate = sum(error_window) / len(error_window)
else:
error_rate = 0
if error_rate > error_threshold:
max_request = max(1, max_request - 1)
elif error_rate < error_threshold / 2 and max_request < preset:
max_request += 1
else:
pass
if pre_max_request != max_request:
pre_max_request = max_request
print(f"\r同一時間訪問網路的線程數動態改為 {max_request}")
error_window.append(error_count)
if len(error_window) > error_window_size:
error_window.pop(0)
error_count = 0
def push_message(record_name: str, live_url: str, content: str) -> None:
msg_title = push_message_title.strip() or "直播間狀態更新通知"
push_functions = {
'微信': lambda: xizhi(xizhi_api_url, msg_title, content),
'釘釘': lambda: dingtalk(dingtalk_api_url, content, dingtalk_phone_num),
'郵箱': lambda: send_email(
email_host, login_email, email_password, sender_email, sender_name,
to_email, msg_title, content
),
'TG': lambda: tg_bot(tg_chat_id, tg_token, content),
'BARK': lambda: bark(
bark_msg_api, title=msg_title, content=content, level=bark_msg_level, sound=bark_msg_ring
),
'NTFY': lambda: ntfy(
ntfy_api, title=msg_title, content=content, tags=ntfy_tags, action_url=live_url, email=ntfy_email
),
}
for platform, func in push_functions.items():
if platform in live_status_push.upper():
try:
result = func()
print(f'提示信息:已經將[{record_name}]直播狀態消息推送至你的{platform},'
f' 成功{len(result["success"])}, 失敗{len(result["error"])}')
except Exception as e:
print(f"直播消息推送到{platform}失敗: {e}")
def run_bash(command: list) -> None:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=get_startup_info(os_type)
)
stdout, stderr = process.communicate()
stdout_decoded = stdout.decode('utf-8')
stderr_decoded = stderr.decode('utf-8')
print(stdout_decoded)
print(stderr_decoded)
def clear_record_info(record_name: str, record_url: str) -> None:
global monitoring
recording.discard(record_name)
if record_url in url_comments and record_url in running_list:
running_list.remove(record_url)
monitoring -= 1
print(f"[{record_name}]已經從錄製列表中移除")
def check_subprocess(record_name: str, record_url: str, ffmpeg_command: list, save_type: str,
bash_file_path: str | None = None) -> bool:
save_file_path = ffmpeg_command[-1]
process = subprocess.Popen(
ffmpeg_command, stderr=subprocess.STDOUT, startupinfo=get_startup_info(os_type)
)
subs_file_path = save_file_path.rsplit('.', maxsplit=1)[0]
subs_thread_name = f'subs_{Path(subs_file_path).name}'
if create_time_file and not split_video_by_time and '��频' not in save_type:
create_var[subs_thread_name] = threading.Thread(
target=generate_subtitles, args=(record_name, subs_file_path)
)
create_var[subs_thread_name].daemon = True
create_var[subs_thread_name].start()
while process.poll() is None:
if record_url in url_comments or exit_recording:
print(f"[{record_name}]錄製時已被註解,本條線程將會退出")
clear_record_info(record_name, record_url)
process.terminate()
process.wait()
return True
time.sleep(1)
return_code = process.returncode
stop_time = time.strftime('%Y-%m-%d %H:%M:%S')
if return_code == 0:
if ts_to_mp4 and save_type == 'TS':
if split_video_by_time:
file_paths = utils.get_file_paths(os.path.dirname(save_file_path))
prefix = os.path.basename(save_file_path).rsplit('_', maxsplit=1)[0]
for path in file_paths:
if prefix in path:
threading.Thread(target=converts_mp4, args=(path, delete_origin_file)).start()
else:
threading.Thread(target=converts_mp4, args=(save_file_path, delete_origin_file)).start()
print(f"\n{record_name} {stop_time} 直播錄製完成\n")
if bash_file_path:
if os_type != 'nt':
print(f'準備執行自定義Bash腳本,請確認腳本是否有執行權限! 路徑:{bash_file_path}, 授予權限:chmod +x your_script.sh')
bash_command = [bash_file_path, record_name.split(' ', maxsplit=1)[-1], save_file_path, save_type,
split_video_by_time, ts_to_mp4]
run_bash(bash_command)
else:
print('只支持在Linux環境下執行Bash腳本')
else:
print(f"\n{record_name} {stop_time} 直播錄製出錯,返回碼: {return_code}\n")
recording.discard(record_name)
return False
def clean_name(input_text):
cleaned_name = re.sub(rstr, "_", input_text.strip())
cleaned_name = cleaned_name.replace("(", "(").replace(")", ")")
cleaned_name = utils.remove_emojis(cleaned_name, '_').strip('_')
return cleaned_name or '空白暱稱'
def start_record(url_data: tuple, count_variable: int = -1) -> None:
global error_count
while True:
try:
record_finished = False
run_once = False
is_long_url = False
start_pushed = False
new_record_url = ''
count_time = time.time()
retry = 0
record_quality, record_url, anchor_name = url_data
proxy_address = proxy_addr
platform = '未知平台'
if proxy_addr:
proxy_address = None
for platform in enable_proxy_platform_list:
if platform and platform.strip() in record_url:
proxy_address = proxy_addr
break
if not proxy_address:
if extra_enable_proxy_platform_list:
for pt in extra_enable_proxy_platform_list:
if pt and pt.strip() in record_url:
proxy_address = proxy_addr_bak or None
# print(f'\r代理地址:{proxy_address}')
# print(f'\r全局代理:{global_proxy}')
while True:
try:
port_info = []
if record_url.find("douyin.com/") > -1:
platform = '抖音直播'
with semaphore:
if 'v.douyin.com' not in record_url:
json_data = spider.get_douyin_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=dy_cookie)
else:
json_data = spider.get_douyin_app_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=dy_cookie)
port_info = stream.get_douyin_stream_url(json_data, record_quality)
elif record_url.find("https://www.tiktok.com/") > -1:
platform = 'TikTok直播'
with semaphore:
if global_proxy or proxy_address:
json_data = spider.get_tiktok_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=tiktok_cookie)
port_info = stream.get_tiktok_stream_url(json_data, record_quality)
else:
logger.error("錯誤訊息: 網路異常,請檢查網路是否能正常訪問TikTok平台")
elif record_url.find("https://live.kuaishou.com/") > -1:
platform = '快手直播'
with semaphore:
json_data = spider.get_kuaishou_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=ks_cookie)
port_info = stream.get_kuaishou_stream_url(json_data, record_quality)
elif record_url.find("https://www.huya.com/") > -1:
platform = '虎牙直播'
with semaphore:
if record_quality not in ['原畫', '藍光', '超清']:
json_data = spider.get_huya_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=hy_cookie)
port_info = stream.get_huya_stream_url(json_data, record_quality)
else:
port_info = spider.get_huya_app_stream_url(
url=record_url,
proxy_addr=proxy_address,
cookies=hy_cookie
)
elif record_url.find("https://www.douyu.com/") > -1:
platform = '斗鱼直播'
with semaphore:
json_data = spider.get_douyu_info_data(
url=record_url, proxy_addr=proxy_address, cookies=douyu_cookie)
port_info = stream.get_douyu_stream_url(
json_data, video_quality=record_quality, cookies=douyu_cookie, proxy_addr=proxy_address
)
elif record_url.find("https://www.yy.com/") > -1:
platform = 'YY直播'
with semaphore:
json_data = spider.get_yy_stream_data(
url=record_url, proxy_addr=proxy_address, cookies=yy_cookie)
port_info = stream.get_yy_stream_url(json_data)
elif record_url.find("https://live.bilibili.com/") > -1:
platform = 'B站直播'
with semaphore:
json_data = spider.get_bilibili_room_info(
url=record_url, proxy_addr=proxy_address, cookies=bili_cookie)
port_info = stream.get_bilibili_stream_url(
json_data, video_quality=record_quality, cookies=bili_cookie, proxy_addr=proxy_address)
elif record_url.find("https://www.redelight.cn/") > -1 or \
record_url.find("https://www.xiaohongshu.com/") > -1 or \
record_url.find("http://xhslink.com/") > -1:
platform = '小紅書直播'
with semaphore:
port_info = spider.get_xhs_stream_url(
record_url, proxy_addr=proxy_address, cookies=xhs_cookie)
retry += 1
elif record_url.find("https://www.bigo.tv/") > -1 or record_url.find("slink.bigovideo.tv/") > -1:
platform = 'Bigo直播'
with semaphore:
port_info = spider.get_bigo_stream_url(
record_url, proxy_addr=proxy_address, cookies=bigo_cookie)
elif record_url.find("https://app.blued.cn/") > -1:
platform = 'Blued直播'
with semaphore:
port_info = spider.get_blued_stream_url(
record_url, proxy_addr=proxy_address, cookies=blued_cookie)
elif record_url.find("sooplive.co.kr/") > -1:
platform = 'SOOP'
with semaphore:
if global_proxy or proxy_address:
json_data = spider.get_sooplive_stream_data(
url=record_url, proxy_addr=proxy_address,
cookies=sooplive_cookie,
username=sooplive_username,
password=sooplive_password
)
if json_data and json_data.get('new_cookies'):
utils.update_config(
config_file, 'Cookie', 'sooplive_cookie', json_data['new_cookies']
)
port_info = stream.get_stream_url(json_data, record_quality, spec=True)
else:
logger.error("錯誤訊息: 網路異常,請檢查本網路是否能正常訪問SOOP平台")
elif record_url.find("cc.163.com/") > -1:
platform = '網易CC直播'
with semaphore:
json_data = spider.get_netease_stream_data(url=record_url, cookies=netease_cookie)
port_info = stream.get_netease_stream_url(json_data, record_quality)
elif record_url.find("qiandurebo.com/") > -1:
platform = '千度熱播'
with semaphore:
port_info = spider.get_qiandurebo_stream_data(
url=record_url, proxy_addr=proxy_address, cookies=qiandurebo_cookie)
elif record_url.find("www.pandalive.co.kr/") > -1:
platform = 'PandaTV'
with semaphore:
if global_proxy or proxy_address:
json_data = spider.get_pandatv_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=pandatv_cookie
)
port_info = stream.get_stream_url(json_data, record_quality, spec=True)
else:
logger.error("錯誤訊息: 網路異常,請檢查本網路是否能正常訪問PandaTV直播平台")
elif record_url.find("fm.missevan.com/") > -1:
platform = '貓耳FM直播'
with semaphore:
port_info = spider.get_maoerfm_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=maoerfm_cookie)
elif record_url.find("www.winktv.co.kr/") > -1:
platform = 'WinkTV'
with semaphore:
if global_proxy or proxy_address:
json_data = spider.get_winktv_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=winktv_cookie)
port_info = stream.get_stream_url(json_data, record_quality, spec=True)
else:
logger.error("錯誤訊息: 網路異常,請檢查本網路是否能正常訪問WinkTV直播平台")
elif record_url.find("www.flextv.co.kr/") > -1:
platform = 'FlexTV'
with semaphore:
if global_proxy or proxy_address:
json_data = spider.get_flextv_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=flextv_cookie,
username=flextv_username,
password=flextv_password
)
if json_data and json_data.get('new_cookies'):
utils.update_config(
config_file, 'Cookie', 'flextv_cookie', json_data['new_cookies']
)
port_info = stream.get_stream_url(json_data, record_quality, spec=True)
else:
logger.error("錯誤訊息: 網路異常,請檢查本網路是否能正常訪問FlexTV直播平台")
elif record_url.find("look.163.com/") > -1:
platform = 'Look直播'
with semaphore:
port_info = spider.get_looklive_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=look_cookie
)
elif record_url.find("www.popkontv.com/") > -1:
platform = 'PopkonTV'
with semaphore:
if global_proxy or proxy_address:
port_info = spider.get_popkontv_stream_url(
url=record_url,
proxy_addr=proxy_address,
access_token=popkontv_access_token,
username=popkontv_username,
password=popkontv_password,
partner_code=popkontv_partner_code
)
if port_info and port_info.get('new_token'):
utils.update_config(
file_path=config_file, section='Authorization', key='popkontv_token',
new_value=port_info['new_token']
)
else:
logger.error("錯誤訊息: 網路異常,請檢查本網路是否能正常訪問PopkonTV直播平台")
elif record_url.find("twitcasting.tv/") > -1:
platform = 'TwitCasting'
with semaphore:
port_info = spider.get_twitcasting_stream_url(
url=record_url,
proxy_addr=proxy_address,
cookies=twitcasting_cookie,
account_type=twitcasting_account_type,
username=twitcasting_username,
password=twitcasting_password
)
if port_info and port_info.get('new_cookies'):
utils.update_config(
file_path=config_file, section='Cookie', key='twitcasting_cookie',
new_value=port_info['new_cookies']
)
elif record_url.find("live.baidu.com/") > -1:
platform = '百度直播'
with semaphore:
json_data = spider.get_baidu_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=baidu_cookie)
port_info = stream.get_stream_url(json_data, record_quality)
elif record_url.find("weibo.com/") > -1:
platform = '微博直播'
with semaphore:
json_data = spider.get_weibo_stream_data(
url=record_url, proxy_addr=proxy_address, cookies=weibo_cookie)
port_info = stream.get_stream_url(json_data, record_quality, extra_key='m3u8_url')
elif record_url.find("kugou.com/") > -1:
platform = '酷狗直播'
with semaphore:
port_info = spider.get_kugou_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=kugou_cookie)
elif record_url.find("www.twitch.tv/") > -1:
platform = 'TwitchTV'
with semaphore:
if global_proxy or proxy_address:
json_data = spider.get_twitchtv_stream_data(
url=record_url,
proxy_addr=proxy_address,
cookies=twitch_cookie
)
port_info = stream.get_stream_url(json_data, record_quality, spec=True)
else:
logger.error("錯誤訊息: 網路異常,請檢查本網路是否能正常訪問TwitchTV直播平台")
elif record_url.find("www.liveme.com/") > -1:
if global_proxy or proxy_address:
platform = 'LiveMe'
with semaphore:
port_info = spider.get_liveme_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=liveme_cookie)
else:
logger.error("錯誤訊息: 網路異常,請檢查本網路是否能正常訪問LiveMe直播平台")
elif record_url.find("www.huajiao.com/") > -1:
platform = '花椒直播'
with semaphore:
port_info = spider.get_huajiao_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=huajiao_cookie)
elif record_url.find("7u66.com/") > -1:
platform = '流星直播'
with semaphore:
port_info = spider.get_liuxing_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=liuxing_cookie)
elif record_url.find("showroom-live.com/") > -1:
platform = 'ShowRoom'
with semaphore:
json_data = spider.get_showroom_stream_data(
url=record_url, proxy_addr=proxy_address, cookies=showroom_cookie)
port_info = stream.get_stream_url(json_data, record_quality, spec=True)
elif record_url.find("live.acfun.cn/") > -1 or record_url.find("m.acfun.cn/") > -1:
platform = 'Acfun'
with semaphore:
json_data = spider.get_acfun_stream_data(
url=record_url, proxy_addr=proxy_address, cookies=acfun_cookie)
port_info = stream.get_stream_url(
json_data, record_quality, url_type='flv', extra_key='url')
elif record_url.find("tlclw.com/") > -1:
platform = '暢聊直播'
with semaphore:
port_info = spider.get_changliao_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=changliao_cookie)
elif record_url.find("ybw1666.com/") > -1:
platform = '音播直播'
with semaphore:
port_info = spider.get_yinbo_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=yinbo_cookie)
elif record_url.find("www.inke.cn/") > -1:
platform = '映客直播'
with semaphore:
port_info = spider.get_yingke_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=yingke_cookie)
elif record_url.find("www.zhihu.com/") > -1:
platform = '知乎直播'
with semaphore:
port_info = spider.get_zhihu_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=zhihu_cookie)
elif record_url.find("chzzk.naver.com/") > -1:
platform = 'CHZZK'
with semaphore:
json_data = spider.get_chzzk_stream_data(
url=record_url, proxy_addr=proxy_address, cookies=chzzk_cookie)
port_info = stream.get_stream_url(json_data, record_quality, spec=True)
elif record_url.find("www.haixiutv.com/") > -1:
platform = '嗨秀直播'
with semaphore:
port_info = spider.get_haixiu_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=haixiu_cookie)
elif record_url.find("h5webcdn-pro.vvxqiu.com/") > -1:
platform = 'VV星球'
with semaphore:
port_info = spider.get_vvxqiu_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=vvxqiu_cookie)
elif record_url.find("17.live/") > -1:
platform = '17Live'
with semaphore:
port_info = spider.get_17live_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=yiqilive_cookie)
elif record_url.find("www.lang.live/") > -1:
platform = '浪Live'
with semaphore:
port_info = spider.get_langlive_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=langlive_cookie)
elif record_url.find("m.pp.weimipopo.com/") > -1:
platform = '漂漂直播'
with semaphore:
port_info = spider.get_pplive_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=pplive_cookie)
elif record_url.find(".6.cn/") > -1:
platform = '六間房直播'
with semaphore:
port_info = spider.get_6room_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=six_room_cookie)
elif record_url.find("lehaitv.com/") > -1:
platform = '樂嗨直播'
with semaphore:
port_info = spider.get_haixiu_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=lehaitv_cookie)
elif record_url.find("h.catshow168.com/") > -1:
platform = '花貓直播'
with semaphore:
port_info = spider.get_pplive_stream_url(
url=record_url, proxy_addr=proxy_address, cookies=huamao_cookie)
elif record_url.find(".m3u8") > -1 or record_url.find(".flv") > -1:
platform = '自定義錄製直播'
port_info = {
"anchor_name": platform + '_' + str(uuid.uuid4())[:8],
"is_live": True,
"record_url": record_url,
}
if '.flv' in record_url:
port_info['flv_url'] = record_url
else:
port_info['m3u8_url'] = record_url
else:
logger.error(f'{record_url} {platform}直播地址')
return
if anchor_name:
if '主播:' in anchor_name:
anchor_split: list = 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 not port_info.get("anchor_name", ''):
print(f'序號{count_variable} 網址內容獲取失敗,進行重試中...獲取失敗的地址是:{url_data}')
with max_request_lock:
error_count += 1
error_window.append(1)
else:
anchor_name = clean_name(anchor_name)
record_name = f'序號{count_variable} {anchor_name}'
if record_url in url_comments:
print(f"[{anchor_name}]已被註解,本條線程將會退出")
clear_record_info(record_name, record_url)
return
if not url_data[-1] and run_once is False:
if is_long_url:
need_update_line_list.append(
f'{record_url}|{new_record_url},主播: {anchor_name.strip()}')
else:
need_update_line_list.append(f'{record_url}|{record_url},主播: {anchor_name.strip()}')
run_once = True
push_at = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
if port_info['is_live'] is False:
print(f"\r{record_name} 等待直播... ")
if start_pushed:
if over_show_push:
push_content = "直播間狀態更新:[直播間名稱] 直播已結束!時間:[時間]"
if over_push_message_text:
push_content = over_push_message_text
push_content = (push_content.replace('[直播間名稱]', record_name).
replace('[時間]', push_at))
threading.Thread(
target=push_message,
args=(record_name, record_url, push_content.replace(r'\n', '\n')),
daemon=True
).start()
start_pushed = False
else:
content = f"\r{record_name} 正在直播中..."
print(content)
if live_status_push and not start_pushed:
if begin_show_push:
push_content = "直播間狀態更新:[直播間名稱] 正在直播中,時間:[時間]"
if begin_push_message_text:
push_content = begin_push_message_text
push_content = (push_content.replace('[直播間名稱]', record_name).
replace('[時間]', push_at))
threading.Thread(
target=push_message,
args=(record_name, record_url, push_content.replace(r'\n', '\n')),
daemon=True
).start()
start_pushed = True
if disable_record:
time.sleep(push_check_seconds)
continue
real_url = port_info.get('record_url')
full_path = f'{default_path}/{platform}'
if real_url:
now = datetime.datetime.today().strftime("%Y-%m-%d_%H-%M-%S")
live_title = port_info.get('title')
title_in_name = ''
if live_title:
live_title = clean_name(live_title)
title_in_name = live_title + '_' if filename_by_title else ''
try:
if len(video_save_path) > 0:
if not video_save_path.endswith(('/', '\\')):
full_path = f'{video_save_path}/{platform}'
else:
full_path = f'{video_save_path}{platform}'
full_path = full_path.replace("\\", '/')
if folder_by_author:
full_path = f'{full_path}/{anchor_name}'
if folder_by_time:
full_path = f'{full_path}/{now[:10]}'
if folder_by_title and port_info.get('title'):
if folder_by_time:
full_path = f'{full_path}/{live_title}_{anchor_name}'
else:
full_path = f'{full_path}/{now[:10]}_{live_title}'
if not os.path.exists(full_path):
os.makedirs(full_path)
except Exception as e:
logger.error(f"錯誤訊息: {e} 發生錯誤的行數: {e.__traceback__.tb_lineno}")
if enable_https_recording and real_url.startswith("http://"):
real_url = real_url.replace("http://", "https://")
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")
rw_timeout = "15000000"
analyzeduration = "20000000"
probesize = "10000000"
bufsize = "8000k"
max_muxing_queue_size = "1024"
for pt_host in overseas_platform_host:
if pt_host in record_url:
rw_timeout = "50000000"
analyzeduration = "40000000"
probesize = "20000000"
bufsize = "15000k"
max_muxing_queue_size = "2048"
break
ffmpeg_command = [
'ffmpeg', "-y",
"-v", "verbose",
"-rw_timeout", rw_timeout,
"-loglevel", "error",
"-hide_banner",
"-user_agent", user_agent,
"-protocol_whitelist", "rtmp,crypto,file,http,https,tcp,tls,udp,rtp,httpproxy",
"-thread_queue_size", "1024",
"-analyzeduration", analyzeduration,
"-probesize", probesize,
"-fflags", "+discardcorrupt",
"-i", real_url,
"-bufsize", bufsize,
"-sn", "-dn",
"-reconnect_delay_max", "60",
"-reconnect_streamed", "-reconnect_at_eof",
"-max_muxing_queue_size", max_muxing_queue_size,
"-correct_ts_overflow", "1",
]
record_headers = {
'PandaTV': 'origin:https://www.pandalive.co.kr',
'WinkTV': 'origin:https://www.winktv.co.kr',
'PopkonTV': 'origin:https://www.popkontv.com',
'FlexTV': 'origin:https://www.flextv.co.kr',
'千度熱播': 'referer:https://qiandurebo.com',
'17Live': 'referer:https://17.live/en/live/6302408',
'浪Live': 'referer:https://www.lang.live',
}
headers = record_headers.get(platform)
if headers:
ffmpeg_command.insert(11, "-headers")
ffmpeg_command.insert(12, headers)
if proxy_address:
ffmpeg_command.insert(1, "-http_proxy")
ffmpeg_command.insert(2, proxy_address)
recording.add(record_name)
start_record_time = datetime.datetime.now()
recording_time_list[record_name] = [start_record_time, record_quality]
rec_info = f"\r{anchor_name} 準備開始錄製視頻: {full_path}"
if show_url:
re_plat = ('WinkTV', 'PandaTV', 'ShowRoom', 'CHZZK')
if platform in re_plat:
logger.info(f"{platform} | {anchor_name} | 直播源地址: {port_info['m3u8_url']}")
else:
logger.info(
f"{platform} | {anchor_name} | 直播源地址: {port_info['record_url']}")
if video_save_type == "FLV":
filename = anchor_name + f'_{title_in_name}' + now + '.flv'
save_file_path = f'{full_path}/{filename}'
print(f'{rec_info}/{filename}')
subs_file_path = save_file_path.rsplit('.', maxsplit=1)[0]
subs_thread_name = f'subs_{Path(subs_file_path).name}'
if create_time_file:
create_var[subs_thread_name] = threading.Thread(
target=generate_subtitles, args=(record_name, subs_file_path)
)
create_var[subs_thread_name].daemon = True
create_var[subs_thread_name].start()
try:
flv_url = port_info.get('flv_url')
if flv_url:
_filepath, _ = urllib.request.urlretrieve(real_url, save_file_path)
record_finished = True
recording.discard(record_name)
print(
f"\n{anchor_name} {time.strftime('%Y-%m-%d %H:%M:%S')} 直播錄製完成\n")
except Exception as e:
print(
f"\n{anchor_name} {time.strftime('%Y-%m-%d %H:%M:%S')} 直播錄製出錯,請檢查網路\n")
logger.error(f"錯誤訊息: {e} 發生錯誤的行數: {e.__traceback__.tb_lineno}")
with max_request_lock:
error_count += 1
error_window.append(1)