-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbilitools.py
4858 lines (4542 loc) · 247 KB
/
bilitools.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
import tkinter as tk
import tkinter.messagebox as msgbox
import tkinter.filedialog as filedialog
import tkinter.scrolledtext as scrolledtext
import tkinter.ttk as ttk
import os
import sys
import re
import time
import random
from io import BytesIO
import traceback
import math
import logging
import threading
import queue
from typing import Any
import webbrowser
import json
import base64
import subprocess
import copy
import functools
import typing
import qrcode
import danmaku2ass
import lxml
from configuration import version, inner_data_path
from configuration import config_path
from configuration import default_config as config
from configuration import development_mode
import textlib
import biliapis
from biliapis import bilicodes
import custom_widgets as cusw
from basic_window import Window
import imglib
import ffdriver
from videoshot_handler import VideoShotHandler
#注意:
#为了页面美观,将 Button/Radiobutton/Checkbutton/Entry 的母模块从tk换成ttk
#↑步入现代风(并不
biliapis.requester.filter_emoji = config['filter_emoji']
# 加载关于信息
about_info = textlib.about_info.format(version=version)
rgb2hex = lambda r,g,b:'#{:0>6s}'.format(str(hex((r<<16)+(g<<8)+b))[2:])
def remove_repeat(l):
l_ = []
for i in l:
if i not in l_:
l_.append(i)
return l_
def apply_proxy_config(): # also used as refresher
if config['proxy']['enabled']:
if config['proxy']['port'] == None:
biliapis.requester.proxy = config['proxy']['host']
else:
biliapis.requester.proxy = '%s:%s'%(config['proxy']['host'],config['proxy']['port'])
if config['proxy']['use_system_proxy']:
biliapis.requester.global_config(use_proxy=None)
else:
biliapis.requester.global_config(use_proxy=True)
else:
biliapis.requester.proxy = None
biliapis.requester.global_config(use_proxy=False)
def dump_config(fp=config_path):
json.dump(config,open(fp,'w+',encoding='utf-8',errors='ignore'))
logging.debug('Config File Dumped to {}'.format(config_path))
def load_config(fp=config_path):
global config
if os.path.exists(fp):# and not development_mode:
tmp = json.load(open(fp,'r',encoding='utf-8',errors='ignore'))
if 'version' in tmp:
if tmp['version'] == version:
config = tmp
logging.debug('Config File Loaded from {}'.format(config_path))
else:
dump_config(fp)
logging.warning("Config file version not match, old covered")
else:
dump_config(fp)
else:
dump_config(fp)
def danmaku_to_ass(xmlfilename,outputfile,w=1920,h=1080,reduce_when_full=True):
try:
danmaku2ass.Danmaku2ASS(xmlfilename,'autodetect',outputfile,w,h,is_reduce_comments=reduce_when_full,
font_face='黑体',font_size=40.0,duration_marquee=7.0,duration_still=10.0,)
except Exception as e:
logging.error('Error while converting danmaku: '+str(e))
else:
logging.info('Danmaku file {} converted to {}'.format(xmlfilename,outputfile))
def start_new_thread(func,args=(),kwargs=None,name=None,daemon=True):
threading.Thread(target=func,args=args,kwargs=kwargs,name=name,daemon=daemon).start()
def replaceChr(text):
repChr = {'/':'/','*':'*',':':':','\\':'\','>':'>',
'<':'<','|':'|','?':'?','"':'"'}
for t in list(repChr.keys()):
text = text.replace(t,repChr[t])
return text
def make_qrcode(data) -> BytesIO:
qr = qrcode.QRCode()
qr.add_data(data)
img = qr.make_image()
a = BytesIO()
img.save(a,'png')
return a
def make_quality_regulation(qtext):
targetlist = list(bilicodes.stream_dash_video_quality.keys())
index = list(bilicodes.stream_dash_video_quality.values()).index(qtext)
return list(reversed(targetlist[:index+1]))
class DownloadManager(object):
def __init__(self):
self.window = None
self.task_queue = queue.Queue()
self.refresh_loop_schedule = None
self.task_receiving_lock = threading.Lock()
self.table_edit_lock = threading.Lock() # 尝试添加了这个, 希望能阻止 not in mainloop 报错
self.table_columns = {
'number':'序号',
'title':'标题',
'subtitle':'副标题',
'target':'目标',
'mode':'模式',
'size':'大小',
'quality':'质量',
'length':'长度',
'saveto':'保存至',
'status':'状态'
}
self.table_columns_widths = [40,200,180,100,70,70,100,60,100,150]
self.table_display_list = [] # 多维列表注意, 对应Treeview的内容, 每项格式见table_columns
self.data_objs = [] # 对应每个下载项的数据包, 每项格式:[序号(整型),类型(字符串,video/audio/common/manga),选项(字典,包含从task_receiver传入的除源以外的**args)]
self.thread_counter = 0 # 线程计数器
self.failed_indexes = [] # 存放失败任务在data_objs中的索引
self.running_indexes = [] # 存放运行中的任务在data_objs中的索引
self.done_indexes = [] # 存放已完成任务在data_objs中的索引
start_new_thread(self.auto_thread_starter) # 启动线程启动器
# if (not development_mode or '-debug' in sys.argv):
# self.recover_progress()
def recover_progress(self, path=config['download']['progress_backup_path']):
if os.path.exists(path):
if os.path.getsize(path) >= 50:
hide_window = not bool(self.window)
self.show()
if msgbox.askyesno('PrgRecovery','恢复下载进度?',parent=self.window):
self.load_progress(path)
if hide_window:
self.hide()
def load_progress(self,file=config['download']['progress_backup_path']):
if os.path.exists(file):
pgr = json.load(open(file,'r',encoding='utf-8',errors='ignore'))
for reindex in range(0,len(pgr['objs'])):
obj = pgr['objs'][reindex]
dlist = pgr['displaylist'][reindex]
obj[2] = copy.deepcopy(obj[2])
obj[2]['index'] = len(self.data_objs)
obj[0] = len(self.data_objs)+1
dlist[0] = str(len(self.data_objs)+1)
dlist[-1] = '待处理'
self.data_objs.append(obj)
with self.table_edit_lock:
self.table_display_list.append(dlist)
if obj[1] == 'video':
self.task_queue.put_nowait(lambda args=obj[2]:self._video_download_thread(**args))
elif obj[1] == 'audio':
self.task_queue.put_nowait(lambda args=obj[2]:self._audio_download_thread(**args))
elif obj[1] == 'common':
self.task_queue.put_nowait(lambda args=obj[2]:self._common_download_thread(**args))
elif obj[1] == 'manga':
self.task_queue.put_nowait(lambda args=obj[2]:self._manga_download_thread(**args))
logging.debug('{} Progress Obj Loaded from {}'.format(len(pgr['objs']),file))
else:
logging.debug('Progress File not Exists.')
def save_progress(self,path=config['download']['progress_backup_path']):
pgr = {
'objs':[],
'displaylist':[]
}
with self.table_edit_lock:
for index in range(0,len(self.data_objs)):
if index in self.failed_indexes:
pgr['objs'] += [self.data_objs[index]]
pgr['displaylist'] += [self.table_display_list[index]]
elif index in self.running_indexes:
pgr['objs'] += [self.data_objs[index]]
pgr['displaylist'] += [self.table_display_list[index]]
elif index in self.done_indexes:
continue
else:
pgr['objs'] += [self.data_objs[index]]
pgr['displaylist'] += [self.table_display_list[index]]
json.dump(pgr,open(path,'w+',encoding='utf-8',errors='ignore'))
logging.debug('{} Progress Objs Saved to {}'.format(len(pgr['objs']),path))
def auto_thread_starter(self):#放在子线程里运行
while True:
if self.thread_counter < config['download']['max_thread_num'] and not self.task_queue.empty():
func = self.task_queue.get_nowait()
logging.debug("Starting download thread: "+str(func))
start_new_thread(func) #线程计数器由开启的download_thread来修改
time.sleep(0.5)
self.save_progress()
else:
time.sleep(0.5)
def match_dash_quality(self,videostreams,audiostreams,regulation=config['download']['video']['quality']):
videostream = None
audiostream = None
#Video
vqs = []
for vstream in videostreams:
vqs.append(vstream['quality'])
if regulation:
regulation = make_quality_regulation(bilicodes.stream_dash_video_quality[regulation])
res = None
for vq in regulation:
if vq in vqs:
res = vq
break
if res == None:
videostream = videostreams[vqs.index(min(vqs))]
else:
videostream = videostreams[vqs.index(res)]
else:
videostream = videostreams[vqs.index(max(vqs))]
#Audio
if not audiostreams:
return videostream, None
aqs = []
for astream in audiostreams:
aqs.append(astream['quality'])
if bilicodes.stream_dash_audio_quality_["Flac"] in aqs and config['download']['video']['allow_flac']:
# flac 不是音质代码中数值最高的那个, 所以要手动匹配
audiostream = audiostreams[aqs.index(bilicodes.stream_dash_audio_quality_["Flac"])]
else:
audiostream = audiostreams[aqs.index(max(aqs))]
return videostream,audiostream
def choose_subtitle_lang(self,bccdata,regulation=config['download']['video']['subtitle_lang_regulation']):
if bccdata:
if len(bccdata) == 1:
return bccdata[0]
else:
abbs = [sub['lang_abb'] for sub in bccdata]
for reg in regulation:
if reg in abbs:
return bccdata[abbs.index(reg)]
return bccdata[0]
else:
return None
def _edit_display_list(self,index,colname,var): #供download_thread调用
with self.table_edit_lock:
self.table_display_list[index][list(self.table_columns.keys()).index(colname)] = var
def _common_download_thread(self,index,url,filename,path,**trash):
#跟下面辣两个函数差不多, 流程最简单, 然而这个函数并不能被用户使用...
self.thread_counter += 1
self.running_indexes.append(index)
try:
logging.info(
"New video download started: %s as %s"%(url, str(
threading.current_thread()
)))
self._edit_display_list(index,'status','准备下载')
session = biliapis.requester.download_yield(url,filename,path)
for donesize,totalsize,percent in session:
self._edit_display_list(index,'status','下载中 - {}%'.format(percent))
self._edit_display_list(index,'size',biliapis.requester.convert_size(totalsize))
except Exception as e:
logging.warning("%s exit abnormally"%str(threading.current_thread()))
self.failed_indexes.append(index)
self._edit_display_list(index,'status','错误: '+str(e))
if development_mode:
raise
else:
logging.info("%s exit normally"%str(threading.current_thread()))
self.done_indexes.append(index)
self._edit_display_list(index,'status','完成')
finally:
del self.running_indexes[self.running_indexes.index(index)]
self.thread_counter -= 1
self.save_progress()
def _manga_download_thread(self,index,epid,path,**trash):
#懒得解释了
self.thread_counter += 1
self.running_indexes.append(index)
try:
logging.info(
"New video download started: Ep%d as %s"%(epid,str(
threading.current_thread()
)))
#收集信息
self._edit_display_list(index,'status','收集信息')
episode_info = biliapis.manga.get_episode_info(epid)
comic_title = replaceChr(episode_info['comic_title'])
ep_title = replaceChr(episode_info['eptitle'])
ep_title_short = replaceChr(episode_info['eptitle_short'])
mcid = episode_info['mcid']
path = os.path.join(path,'_'.join([comic_title,ep_title_short,ep_title]).strip())
if path.endswith('.'):
path = path + '_'
#获取url和token
self._edit_display_list(index,'status','获取Token')
urls = ['{}@{}w.jpg'.format(i['path'],i['width']) for i in biliapis.manga.get_episode_image_index(epid)['images']]
urls = [i['url']+'?token='+i['token'] for i in biliapis.manga.get_episode_image_token(*urls)]
self._edit_display_list(index,'length',f'{len(urls)}张')
maxb = len(str(len(urls)))
#开始下载
if not os.path.exists(path):
os.mkdir(path)
counter = 0
self._edit_display_list(index,'status',f'下载中 0/{len(urls)}')
for url in urls:
counter += 1
filename = '%d_%d_%0*d.jpg'%(mcid,epid,maxb,counter)
if not os.path.exists(os.path.join(path,filename)):
biliapis.requester.download_common(url,os.path.join(path,filename))
self._edit_display_list(index,'status',f'下载中 {counter}/{len(urls)}')
self._edit_display_list(index,'status','检查中')
size = 0
for i in os.listdir(path):
size += os.path.getsize(os.path.join(path,i))
self._edit_display_list(index,'size',biliapis.requester.convert_size(size))
self._edit_display_list(index,'status','完成')
except Exception as e:
logging.warning("%s exit abnormally"%str(threading.current_thread()))
self.failed_indexes.append(index)
self._edit_display_list(index,'status','错误: '+str(e))
if not isinstance(e, biliapis.BiliError):
if development_mode:
raise
else:
logging.info("%s exit normally"%str(threading.current_thread()))
self.done_indexes.append(index)
finally:
del self.running_indexes[self.running_indexes.index(index)]
self.thread_counter -= 1
self.save_progress()
def _audio_download_thread(self,index,auid,path,audio_format='mp3',lyrics=True,data=None,**trash):
#跟下面辣个函数差不多, 流程稍微简单些
self.thread_counter += 1
self.running_indexes.append(index)
try:
logging.info(
"New video download started: Au%d as %s"%(auid,str(
threading.current_thread()
)))
#收集信息
self._edit_display_list(index,'status','收集信息')
audio_format = audio_format.lower()
if data:
audio_info = data
else:
audio_info = biliapis.audio.get_info(auid) #因为外面套了一层try所以不用做错误处理
self._edit_display_list(index,'length',biliapis.second_to_time(audio_info['length']))
self._edit_display_list(index,'title',audio_info['title'])
self._edit_display_list(index,'target','Auid{}'.format(auid))
#取流
self._edit_display_list(index,'status','正在取流')
stream = biliapis.stream.get_audio_stream(auid)
self._edit_display_list(index,'quality',stream['quality'])
#下载
tmp_filename = replaceChr('{}_{}.m4a'.format(auid,stream['quality_id']))
final_filename = replaceChr('{}_{}'.format(audio_info['title'],stream['quality']))#文件名格式编辑在这里, 不带后缀名
lyrics_filename = replaceChr('{}_{}.lrc'.format(audio_info['title'],stream['quality']))
if not os.path.exists(os.path.join(path,lyrics_filename)) and lyrics:
self._edit_display_list(index,'status','获取歌词')
lrcdata = biliapis.audio.get_lyrics(auid)
if lrcdata == 'Fatal: API error':
pass
else:
with open(os.path.join(path,lyrics_filename),'w+',encoding='utf-8',errors='ignore') as f:
f.write(lrcdata)
if os.path.exists(os.path.join(path,final_filename+'.'+audio_format)):
self._edit_display_list(index,'status','跳过 - 文件已存在: '+final_filename)
self._edit_display_list(index,'size',biliapis.requester.convert_size(os.path.getsize(os.path.join(path,final_filename+'.'+audio_format))))
else:
surls = [stream['url']]+stream['url_backup']
for i in range(len(surls)):
try:
session = biliapis.requester.download_yield(surls[i],tmp_filename,path)
for donesize,totalsize,percent in session:
self._edit_display_list(index,'status','下载中 - {}%'.format(percent))
except Exception as e:
if i >= len(surls)-1:
raise
else:
logging.warning(f'Stream URL {i+1} failed: '+str(e))
else:
break
self._edit_display_list(index,'size',biliapis.requester.convert_size(totalsize))
#进一步处理
if audio_format and audio_format not in ['m4a','copy']:
self._edit_display_list(index,'status','转码')
ffdriver.convert_audio(os.path.join(path,tmp_filename),os.path.join(path,final_filename),audio_format,stream['quality'].lower())
self._edit_display_list(index,'size',biliapis.requester.convert_size(os.path.getsize(os.path.join(path,final_filename+'.'+audio_format))))
try:
os.remove(os.path.join(path,tmp_filename))
except:
pass
else:
os.rename(os.path.join(path,tmp_filename),os.path.join(path,final_filename)+'.m4a')
self._edit_display_list(index,'status','完成')
except Exception as e:
logging.warning("%s exit abnormally"%str(threading.current_thread()))
self.failed_indexes.append(index)
self._edit_display_list(index,'status','错误: '+str(e))
if not isinstance(e, biliapis.BiliError):
if development_mode:
raise
else:
logging.info("%s exit normally"%str(threading.current_thread()))
self.done_indexes.append(index)
finally:
del self.running_indexes[self.running_indexes.index(index)]
self.thread_counter -= 1
self.save_progress()
def _video_download_thread(self,index,cid,bvid,title,path,audio_format='mp3',audiostream_only=False,quality=None,subtitle=True,danmaku=False,
convert_danmaku=True,subtitle_regulation=config['download']['video']['subtitle_lang_regulation'],**trash):
# 放在子线程里运行
# 此函数被包装为lambda函数后放入task_queue中排队, 由auto_thread_starter取出并开启线程
# 此处index为task_receiver为其分配的在tabled_display_list中的索引
self.thread_counter += 1
self.running_indexes.append(index)
try:
if audiostream_only:
logging.info(
"New video download started: Cid%d (audio only) as %s"%(cid,str(
threading.current_thread()
)))
else:
logging.info(
"New video download started: Cid%d as %s"%(cid,str(
threading.current_thread()
)))
audio_format = audio_format.lower()
self._edit_display_list(index,'status','正在取流')
stream_data = biliapis.stream.get_video_stream_dash(cid,bvid=bvid,hdr=True,_4k=True,dolby_vision=True,_8k=True)
self._edit_display_list(index,'length',biliapis.second_to_time(stream_data['length']))
filename_template = '{}_{}.mp4' # 如果需要封装为mkv的话后面会自己改
filename_template_with_flac = '{}_{}.mkv'
# 发现有些远古视频不能用dash取流, 于是正在试图写出MP4备案
# 写牛魔, 一点都不想碰以前拉的史山了, nmlgbd
# 哪天重写一下罢
is_dash_available = stream_data['method']=='dash'
if is_dash_available:
vstream, astream = self.match_dash_quality(stream_data['video'],stream_data['audio'],quality)
stream_mp4 = None
tmpname_audio = '{}_{}_audiostream.m4s'.format(bvid,cid)
tmpname_video = '{}_{}_{}_videostream.m4s'.format(bvid,cid,vstream['quality'])
else:
vstream, astream = None, None
stream_mp4 = stream_data
tmpname_audio = '{}_{}_audiostream.m4s'.format(bvid,cid)
tmpname_video = '{}_{}_{}_videostream.mp4'.format(bvid,cid,bilicodes.stream_flv_video_quality[stream_mp4['quality']])
# 处理没有音频流但是又请求了音轨抽取的情况
if not astream and audiostream_only and not stream_mp4:
self._edit_display_list(index,'status','中止 - 目标没有音频流')
else:
# 更新状态
if audiostream_only:
self._edit_display_list(index,'quality',bilicodes.stream_dash_audio_quality[astream['quality']])
self._edit_display_list(index,'mode','音轨抽取')
else:
if astream:
self._edit_display_list(
index,'quality',
bilicodes.stream_dash_video_quality[vstream['quality']]+'/'+\
bilicodes.stream_dash_audio_quality[astream['quality']]
)
else:
self._edit_display_list(
index,'quality',
bilicodes.stream_dash_video_quality[vstream['quality']]+'/Null'
)
self._edit_display_list(index,'mode','视频下载')
# 生成文件名
if astream:
if astream['quality'] == bilicodes.stream_dash_audio_quality_['Flac']:
filename_template = filename_template_with_flac
audio_format = 'flac'
final_filename_audio_only = replaceChr('{}_{}'.format(title,bilicodes.stream_dash_audio_quality[astream['quality']])) # 音频抽取不带后缀名
else:
final_filename_audio_only = replaceChr('{}'.format(title)) # 这一行根本不会被执行
final_filename = replaceChr(filename_template.format(title,bilicodes.stream_dash_video_quality[vstream['quality']])) # 标题由task_receiver生成
# 字幕
is_sbt_downloaded = False
subtitle_filename = replaceChr('{}_{}.srt'.format(title,bilicodes.stream_dash_video_quality[vstream['quality']])) # 字幕文件名与视频文件保持一致
if subtitle and not audiostream_only:
self._edit_display_list(index,'status','获取字幕')
bccdata = self.choose_subtitle_lang(biliapis.subtitle.get_bcc(cid,bvid=bvid,allow_ai=config['download']['video']['allow_ai_subtitle']),subtitle_regulation)
if bccdata:
bccdata = json.loads(biliapis.requester.get_content_str(bccdata['url']))
srtdata = biliapis.subtitle.bcc_to_srt(bccdata)
with open(os.path.join(path,subtitle_filename),'w+',encoding='utf-8',errors='ignore') as f:
f.write(srtdata)
is_sbt_downloaded = True
# 弹幕
danmaku_filename = replaceChr('{}_{}.xml'.format(title,bilicodes.stream_dash_video_quality[vstream['quality']]))
if danmaku and not audiostream_only:
self._edit_display_list(index,'status','获取弹幕')
xmlstr = biliapis.danmaku.get_xmlstr(cid)
self._edit_display_list(index,'status','过滤弹幕')
xmlstr = biliapis.danmaku.filter(xmlstr,**config['download']['video']['danmaku_filter'])
with open(os.path.join(path,danmaku_filename),'w+',encoding='utf-8',errors='ignore') as f:
f.write(xmlstr)
if convert_danmaku and os.path.exists(os.path.join(path,danmaku_filename)):
ass_danmaku_filename = replaceChr('{}_{}.ass'.format(title,bilicodes.stream_dash_video_quality[vstream['quality']]))
danmaku_to_ass(os.path.join(path,danmaku_filename),os.path.join(path,ass_danmaku_filename),w=vstream['width'],h=vstream['height'])
# 注意这里判断的是成品文件是否存在
# 断点续传和中间文件存在判断是交给requester的
if os.path.exists(os.path.join(path,final_filename)) and not audiostream_only:
self._edit_display_list(index,'status','跳过 - 文件已存在: '+final_filename)
elif os.path.exists(os.path.join(path,final_filename_audio_only)+'.'+audio_format) and audiostream_only:
self._edit_display_list(index,'status','跳过 - 文件已存在: '+final_filename_audio_only+'.'+audio_format)
else:
#Audio Stream
if astream:
surls = [astream['url']]+astream['url_backup']
for i in range(len(surls)):
try:
a_session = biliapis.requester.download_yield(surls[i],tmpname_audio,path)
for donesize,totalsize,percent in a_session:
self._edit_display_list(index,'status','下载音频流 - {}%'.format(percent))
except Exception as e:
if i >= len(surls)-1:
raise
else:
logging.warning(f'Stream URL {i+1} failed: '+str(e))
else:
break
size = totalsize
else:
size = 0
#Video Stream
if audiostream_only:
self._edit_display_list(index,'size',biliapis.requester.convert_size(size))
if audio_format == 'copy' or astream['quality'] == bilicodes.stream_dash_audio_quality_['Flac']:
if astream['quality'] == bilicodes.stream_dash_audio_quality_['Flac']:
os.rename(os.path.join(path,tmpname_audio),os.path.join(path,final_filename_audio_only)+'.flac')
else:
os.rename(os.path.join(path,tmpname_audio),os.path.join(path,final_filename_audio_only)+'.m4s')
else:
self._edit_display_list(index,'status','转码')
ffdriver.convert_audio(os.path.join(path,tmpname_audio),
os.path.join(path,final_filename_audio_only),audio_format,
bilicodes.stream_dash_audio_quality[astream['quality']].lower())
try:
os.remove(os.path.join(path,tmpname_audio))
except:
pass
else:
surls = [vstream['url']]+vstream['url_backup']
for i in range(len(surls)):
try:
v_session = biliapis.requester.download_yield(surls[i],tmpname_video,path)
for donesize,totalsize,percent in v_session:
self._edit_display_list(index,'status','下载视频流 - {}%'.format(percent))
except Exception as e:
if i >= len(surls)-1:
raise
else:
logging.warning(f'Stream URL {i+1} failed: '+str(e))
else:
break
size += totalsize
self._edit_display_list(index,'size',biliapis.requester.convert_size(size))
# Mix
if astream:
self._edit_display_list(index,'status','混流')
ffstatus = ffdriver.merge_media(
os.path.join(path,tmpname_audio),
os.path.join(path,tmpname_video),
os.path.join(path,final_filename)
)
try:
os.remove(os.path.join(path,tmpname_audio))
os.remove(os.path.join(path,tmpname_video))
except:
pass
else:
self._edit_display_list(index,'status','封装')
ffstatus = ffdriver.convert_video(
os.path.join(path,tmpname_video),
os.path.join(path,final_filename)
)
try:
os.remove(os.path.join(path,tmpname_video))
except:
pass
self._edit_display_list(index,'status','完成')
except Exception as e:
logging.warning("%s exit abnormally"%str(threading.current_thread()))
self.failed_indexes.append(index)
self._edit_display_list(index,'status','错误: '+str(e))
if not isinstance(e, biliapis.BiliError):
if development_mode:
raise
else:
logging.info("%s exit normally"%str(threading.current_thread()))
self.done_indexes.append(index)
finally:
del self.running_indexes[self.running_indexes.index(index)]
self.thread_counter -= 1
self.save_progress()
def task_receiver(self, mode: str, path: str, data: typing.Union[dict, None] = None, **options) -> None:
'''
- `mode`: 下载模式, 必须为 `"video"` `"audio"` `"common"` `"manga"` 中的任意一个
- `path`: 保存位置
- `data`: (可选)传入预请求的数据(dict), 避免再次请求
---
详细规则:
- 若`mode`为`video`, 则必须通过`**options`指定[avid/bvid]或[mdid/ssid/epid]参数
- `avid` 和 `bvid` 的专用附加参数:
- `pids`: 分P`索引`列表, 可为空
- `cids`: `cid`列表, 给互动视频用的, 会覆盖`pids`参数
- 如果此视频为互动视频:
- 则需 提交为真值的`is_interact`参数 并 传入`cid`参数 并 [同时传入`graph_id`和`edge_id`参数 或 传入`data`参数]
- 此时`data`传入的是由`biliapis.video.get_interact_edge_info()`获取的数据, 并可以再传入一个包含主视频数据的`video_data`来避免大批量下载时的重复请求
- 若视频不是互动视频但传入了`video_data`, 在没传入`data`的情况下将其当作`data`参数处理
- 我实在想不到能够怎样一次性处理多个互动视频剧情节点了, 交给调用循环罢
- `mdid` 和 `ssid` 和 `epid` 的专用附加参数:
- `epindexes`: EP索引列表, 可为空
- `section_index`: 番外剧集索引
- `section_index`指定时, `epindexes`指的是对应番外中的剧集索引
- 反之则`epindexes`指正片内的索引; 超出索引范围操作无效
- 通用可选参数:
- `audiostream_only`: 是否仅抽取音轨
- `audio_format`: 音频转换格式, 仅当`audiostream_only`参数被指定时生效
- `quality`: 视频优先质量
- `subtitle`: 是否下载字幕
- `danmaku`: 是否下载弹幕
- `subtitle_regulation`: 字幕匹配规则
- 弹幕过滤列表因为可能太长所以直接由线程从`config`中实时读取
- 除了`audiostream_only`外都会读取`config`中的默认值
- 若`mode`为`audio`, 则必须指定`auid`参数
- `auid`的附加参数: `audio_format` (从`config`中读取默认值)
- 若`mode`为`common`, 则必须指定`url`和`filename`, 无附加参数.
- 若`mode`为`manga`, 则必须指定`epid`或`mcid`参数
- 若`mcid`被指定, 有 `epindexes` 参数可选
'''
with self.task_receiving_lock: # 防止多线程操作资源混乱
is_mainthread = isinstance(threading.current_thread(),threading._MainThread)
if is_mainthread:
self.show() #规避 main thread not in main loop 错误
mode = mode.lower()
if mode == 'video':
#普通视频
if 'avid' in options or 'bvid' in options:
abvid = {'avid':None,'bvid':None}
if 'avid' in options:
abvid['avid'] = options['avid']
else:
abvid['bvid'] = options['bvid']
# 互动视频判定
is_interact = False
if 'is_interact' in options:
if options['is_interact']:
is_interact = True
if is_interact:
edge_data = None
# 特殊处理互动视频
assert 'cid' in options,'提交的资源不够, 互动视频分P的解析需要cid'
cid = options['cid']
if 'graph_id' in options and 'edge_id' in options:
try:
edge_data = biliapis.video.get_interact_edge_info(
graph_id=options['graph_id'],
edge_id=options['edge_id'],
**abvid
)
except Exception as e:
if is_mainthread:
msgbox.showerror('Error','Unable to get edge data:\n'+str(e),parent=self.window)
else:
logging.error('Unable to get edge data: '+str(e))
return
elif data:
# 没有办法做验证
edge_data = data
else:
raise AssertionError('提交的资源不够, 互动视频分P的解析需要 [graph_id和edge_id] 或 来自biliapis.video.get_interact_edge_info()的数据')
if 'video_data' in options:
if 'avid' in options:
assert options['avid']==options['video_data']['avid'],'预请求数据包内容不匹配'
else:
assert options['bvid']==options['video_data']['bvid'],'预请求数据包内容不匹配'
video_data = options['video_data']
else:
try:
video_data = biliapis.video.get_detail(**abvid)
except Exception as e:
if is_mainthread:
msgbox.showerror('Error','Unable to get video data:\n'+str(e),parent=self.window)
else:
logging.error('Unable to get video data: '+str(e))
return
pre_opts = {}
pre_opts['audio_format'] = config['download']['video']['audio_convert']
pre_opts['quality'] = config['download']['video']['quality']
pre_opts['subtitle'] = config['download']['video']['subtitle']
pre_opts['danmaku'] = config['download']['video']['danmaku']
pre_opts['subtitle_regulation'] = config['download']['video']['subtitle_lang_regulation']
pre_opts['convert_danmaku'] = config['download']['video']['convert_danmaku']
for key in ['audiostream_only','quality','subtitle','danmaku','subtitle_regulation','convert_danmaku']:#过滤download_thread不需要的, 防止出错
if key in options:
pre_opts[key] = options[key]
pre_opts['bvid'] = video_data['bvid']
pre_opts['path'] = path
pre_opts['cid'] = cid
pre_opts['title'] = '{}_E{}_{}'.format(video_data['title'],edge_data['edge_id'],edge_data['title'])#文件名格式编辑在这里
pre_opts['index'] = len(self.data_objs)
self.data_objs.append([len(self.data_objs)+1,'video',pre_opts])
with self.table_edit_lock:
self.table_display_list.append([
str(len(self.data_objs)),video_data['title'],'E{} {}'.format(edge_data['edge_id'],edge_data['title']),'Cid'+str(cid),'','','','-',path,'待处理'
])
self.task_queue.put_nowait(lambda args=pre_opts:self._video_download_thread(**args))
else:
# 正常处理普通视频
video_data = None
if not data and 'video_data' in options:
data = options['video_data']
if data:
#提取预处理数据包
if 'avid' in options:
assert options['avid']==data['avid'],'预请求数据包内容不匹配'
else:
assert options['bvid']==data['bvid'],'预请求数据包内容不匹配'
video_data = data
else:
#提取avid/bvid
try:
video_data = biliapis.video.get_detail(**abvid)
except Exception as e:
if is_mainthread:
msgbox.showerror('Error','Unable to get video data:\n'+str(e),parent=self.window)
else:
logging.error('Unable to get video data: '+str(e))
return
# if 'avid' in options:
# video_data = biliapis.video.get_detail(avid=options['avid'])
# else:
# video_data = biliapis.video.get_detail(bvid=options['bvid'])
#提取分P索引列表
if 'pids' in options: #这里的所谓pid其实是分P的索引值哒
pids = options['pids']
else:
pids = []
if not pids:
pids = list(range(0,len(video_data['parts'])))
#选项预处理
pre_opts = {}
pre_opts['audio_format'] = config['download']['video']['audio_convert']
pre_opts['quality'] = config['download']['video']['quality']
pre_opts['subtitle'] = config['download']['video']['subtitle']
pre_opts['danmaku'] = config['download']['video']['danmaku']
pre_opts['subtitle_regulation'] = config['download']['video']['subtitle_lang_regulation']
pre_opts['convert_danmaku'] = config['download']['video']['convert_danmaku']
for key in ['audiostream_only','quality','subtitle','danmaku','subtitle_regulation','convert_danmaku']:#过滤download_thread不需要的, 防止出错
if key in options:
pre_opts[key] = options[key]
pre_opts['bvid'] = video_data['bvid']
pre_opts['path'] = path
#分发任务
for pid in pids:
if pid < len(video_data['parts']) and pid >= 0:
part = video_data['parts'][pid]
tmpdict = copy.deepcopy(pre_opts)
tmpdict['cid'] = part['cid']
if part['title'] == video_data['title']:
tmpdict['title'] = '{}_P{}'.format(video_data['title'],pid+1)#文件名格式编辑在这里
else:
tmpdict['title'] = '{}_P{}_{}'.format(video_data['title'],pid+1,part['title'])#文件名格式编辑在这里
tmpdict['index'] = len(self.data_objs)
self.data_objs.append([len(self.data_objs)+1,'video',tmpdict])
with self.table_edit_lock:
self.table_display_list.append([str(len(self.data_objs)),video_data['title'],'P{} {}'.format(pid+1,part['title']),'Cid{}'.format(part['cid']),'','','',biliapis.second_to_time(part['length']),path,'待处理'])
self.task_queue.put_nowait(lambda args=tmpdict:self._video_download_thread(**args))
elif 'ssid' in options or 'mdid' in options or 'epid' in options:
try:
if data:
if 'mdid' in options:
assert options['mdid']==data['mdid'],'预请求数据包内容不匹配'
bangumi_data = data
elif 'ssid' in options:
assert options['ssid']==data['ssid'],'预请求数据包内容不匹配'
bangumi_data = data
else:
bangumi_data = biliapis.media.get_detail(epid=options['epid'])
else:
if 'mdid' in options:
bangumi_data = biliapis.media.get_detail(mdid=options['mdid'])
elif 'ssid' in options:
bangumi_data = biliapis.media.get_detail(ssid=options['ssid'])
else:
bangumi_data = biliapis.media.get_detail(epid=options['epid'])
except Exception as e:
if isinstance(e, AssertionError):
raise
if is_mainthread:
msgbox.showerror('',str(e),parent=self.window)
else:
logging.error("Unable to get media data: "+str(e))
return
main_title = bangumi_data['title']
#选择正片/番外
if 'section_index' in options:
if options['section_index'] > len(bangumi_data['sections'])-1 or options['section_index'] < 0:
return
else:
section = bangumi_data['sections'][options['section_index']]
sstitle = section['title']
episodes = section['episodes']
else:
episodes = bangumi_data['episodes']
sstitle = '正片'
#提取EP
if 'epindexes' in options:
epindexes = options['epindexes']
else:
epindexes = []
if not epindexes:
epindexes = list(range(0,len(episodes)))
#提取参数
pre_opts = {}
pre_opts['audio_format'] = config['download']['video']['audio_convert']
pre_opts['quality'] = config['download']['video']['quality']
pre_opts['subtitle'] = config['download']['video']['subtitle']
pre_opts['danmaku'] = config['download']['video']['danmaku']
pre_opts['subtitle_regulation'] = config['download']['video']['subtitle_lang_regulation']
pre_opts['convert_danmaku'] = config['download']['video']['convert_danmaku']
for key in ['audiostream_only','audio_format','quality','subtitle','danmaku','subtitle_regulation','convert_danmaku']:#过滤download_thread不需要的, 防止出错
if key in options:
pre_opts[key] = options[key]
pre_opts['path'] = path
#分发任务
for epindex in epindexes:
if epindex < len(episodes) and epindex >= 0:
episode = episodes[epindex]
tmpdict = copy.deepcopy(pre_opts)
tmpdict['title'] = '{}_{}_{}.{}'.format(main_title,sstitle,epindex+1,episode['title'])#文件名格式编辑在这里
tmpdict['cid'] = episode['cid']
tmpdict['bvid'] = episode['bvid']
tmpdict['index'] = len(self.data_objs)
self.data_objs.append([len(self.data_objs)+1,'video',tmpdict])
with self.table_edit_lock:
self.table_display_list.append([str(len(self.data_objs)),main_title,'{} {}.{}'.format(sstitle,epindex+1,episode['title']),'Cid{}'.format(episode['cid']),'','','','-',path,'待处理'])
self.task_queue.put_nowait(lambda args=tmpdict:self._video_download_thread(**args))
else:
raise AssertionError('提交的资源不足, 解析视频需要avid/bvid/mdid/ssid/epid中的任意一个')
elif mode == 'audio':
tmpdict = {
'index':len(self.data_objs),
'auid':options['auid'],
'path':path,
'audio_format':config['download']['audio']['convert'],
'lyrics':config['download']['audio']['lyrics']
}
if 'audio_format' in options:
tmpdict['audio_format'] = options['audio_format']
if data:
assert data['auid']==options['auid'],'预请求数据包内容不匹配'
tmpdict['data'] = data.copy()
tmpdict = tmpdict.copy()
self.data_objs.append([len(self.data_objs)+1,'audio',tmpdict])
with self.table_edit_lock:
self.table_display_list.append([str(len(self.data_objs)),'','','Auid'+str(tmpdict['auid']),'音频下载','','','',path,'待处理'])
self.task_queue.put_nowait(lambda args=tmpdict:self._audio_download_thread(**args))
elif mode == 'common':
tmpdict = {
'index':len(self.data_objs),
'url':options['url'],
'filename':options['filename'],
'path':path
}
self.data_objs.append([len(self.data_objs)+1,'common',tmpdict])
with self.table_edit_lock:
self.table_display_list.append([str(len(self.data_objs)),options['filename'],'',options['url'],'普通下载','','','-',path,'待处理'])
self.task_queue.put_nowait(lambda args=tmpdict:self._common_download_thread(**args))
elif mode == 'manga':
if 'mcid' in options:
#提取预处理数据
if data:
assert data['mcid']==options['mcid'],'预请求数据包内容不匹配'
else:
try:
data = biliapis.manga.get_detail(options['mcid'])
except Exception as e:
if is_mainthread:
msgbox.showerror('',str(e),parent=self.window)
else:
logging.error("Unable to get manga data: "+str(e))
return
#提取epindexes
if 'epindexes' in options:
indexes = options['epindexes']
if not indexes:
list(range(0,len(data['ep_list'])))
#分发任务
else:
indexes = list(range(0,len(data['ep_list'])))
#分发任务
for index in indexes:
tmpdict = {
'index':len(self.data_objs),
'epid':data['ep_list'][index]['epid'],
'path':path
}
self.data_objs.append([len(self.data_objs)+1,'manga',tmpdict])
with self.table_edit_lock:
self.table_display_list.append([str(len(self.data_objs)),data['comic_title'],data['ep_list'][index]['eptitle'],'EP'+str(data['ep_list'][index]['epid']),'漫画下载','','-','',path,'待处理'])
self.task_queue.put_nowait(lambda args=tmpdict:self._manga_download_thread(**args))
elif 'epid' in options:
#提取预处理数据
if data:
assert data['epid']==options['epid'],'预请求数据包内容不匹配'
else:
try:
data = biliapis.manga.get_episode_info(options['epid'])
except Exception as e:
if is_mainthread:
msgbox.showerror('',str(e),parent=self.window)
else:
logging.error('Unable to get episode data: '+str(e))
return
tmpdict = {
'index':len(self.data_objs),
'epid':options['epid'],
'path':path
}
self.data_objs.append([len(self.data_objs)+1,'manga',tmpdict])
with self.table_edit_lock:
self.table_display_list.append([str(len(self.data_objs)),data['comic_title'],data['eptitle'],'EP'+str(data['epid']),'漫画下载','','-','',path,'待处理'])
self.task_queue.put_nowait(lambda args=tmpdict:self._manga_download_thread(**args))
self.save_progress()
def retry_all_failed(self):
count = len(self.failed_indexes)
if self.failed_indexes:
while self.failed_indexes:
self._restart_task(self.failed_indexes[0])
elif self.window:
msgbox.showinfo('','没有失败的任务呢.',parent=self.window)
logging.info("Retried all failed: count=%d"%count)
def _restart_task(self,index):
if index in self.failed_indexes:
del self.failed_indexes[self.failed_indexes.index(index)]
elif index in self.done_indexes:
del self.done_indexes[self.done_indexes.index(index)]
else:
raise RuntimeError('Task index {} not allowed being restarted.'.format(index))
data = self.data_objs[index]
for name in ['size','quality']:
self._edit_display_list(index,name,'')
self._edit_display_list(index,'status','待处理')
if data[1] == 'video':
self.task_queue.put_nowait(lambda args=data[2]:self._video_download_thread(**args))
elif data[1] == 'audio':
self.task_queue.put_nowait(lambda args=data[2]:self._audio_download_thread(**args))
elif data[1] == 'common':
self.task_queue.put_nowait(lambda args=data[2]:self._common_download_thread(**args))
elif data[1] == 'manga':
self.task_queue.put_nowait(lambda args=data[2]:self._manga_download_thread(**args))
def show(self):
if self.window: # 构建GUI
if self.window.state() == 'iconic':
self.window.deiconify()