-
Notifications
You must be signed in to change notification settings - Fork 35
/
videodownload.py
7639 lines (7552 loc) · 338 KB
/
videodownload.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
# (C) 2019-2020 lifegpc
# This file is part of bili.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import requests
import JSONParser
import json
import file
import time
import os
from dictcopy import copydict
from re import search
from requests.structures import CaseInsensitiveDict
from biliTime import tostr2, tostr4
import bstr
from biliSub import downsub, ffinputstr, downlrc
from file import mkdir
from dict import delli, dellk
from command import gopt
from lang import getlan, getdict
import sys
import JSONParser2
from inspect import currentframe
from traceback import format_exc
from biliLRC import filterLRC
import biliAudio
from nfofile import NFOFile, NFOActor
from Logger import Logger
from autoopenlist import autoopenfilelist
from HTMLParser import AcfunBangumiParser, NicoVideoInfoParser
from nicoPara import (
genNicoVideoPara,
nicoChooseBestCoverUrl,
nicoChooseBestCoverUrlForLive
)
from M3UParser import parseSimpleMasterM3U
from M3UDownloader import downloadNicoM3U
from nicoHeartBeat import nicoNormalVideoHeartBeatThread
from nicolive import downloadLiveVideo
# https://api.bilibili.com/x/player/playurl?cid=<cid>&qn=<图质大小>&otype=json&avid=<avid>&fnver=0&fnval=16 番剧也可,但不支持4K
# https://api.bilibili.com/pgc/player/web/playurl?avid=<avid>&cid=<cid>&bvid=&qn=<图质大小>&type=&otype=json&ep_id=<epid>&fourk=1&fnver=0&fnval=16&session= 貌似仅番剧
# result -> dash -> video/audio -> [0-?](list) -> baseUrl/base_url
# session = md5(String((getCookie('buvid3') || Math.floor(Math.random() * 100000).toString(16)) + Date.now()));
# 第二个需要带referer,可以解析4K
lan = None
se = JSONParser.loadset()
if se == -1 or se == -2:
se = {}
ip = {}
if len(sys.argv) > 1:
ip = gopt(sys.argv[1:])
lan = getdict('videodownload', getlan(se, ip))
acfunQualityLabelList = ['2160P120', '2160P60', '2160P', '1080P60', '1080P+', '1080P', '720P60', '720P', '540P', '480P', '360P']
def getqualitytrans(t: str) -> str:
"返回画质的翻译"
if t in lan:
return lan[t]
print(lan['NO_QUA_TRANS'].replace('<value>', t))
return t
def getQualityTransWithoutWarning(t: str) -> str:
"返回画质的翻译(无警告)"
return lan[t] if t in lan else t
def getaudesc(data: dict, id: int):
"获取AU号更好的描述"
if 'qualities' not in data or data['qualities'] is None or type(data['qualities']) != list:
return id
templ = [d['desc'] for d in data['qualities'] if d['type'] == id and d['desc'] != ""]
if len(templ) == 1:
t = templ[0]
if f"AU{t}" in lan:
return lan[f"AU{t}"]
print(lan['NO_QUA_TRANS'].replace('<value>', t))
return t
return id
def getqualitytransl(l: list) -> list: # noqa: E741
r = []
for i in l:
r.append(getqualitytrans(i))
return r
def getfps(s: str) -> str:
"解析B站API返回的fps"
if s.isnumeric():
return s + "fps"
else:
r = search(r"([0-9]+)/([0-9]+)", s)
if r is not None:
r = r.groups()
return "%.3f(%s)fps" % (int(r[0]) / int(r[1]), s)
else:
return ""
def getnul():
"获取不输出stdout的命令行"
return f" > {os.devnull} 2>&1"
def geth(h: CaseInsensitiveDict):
s = ''
for i in h.keys():
s = s + ' --header "' + i + ': ' + h[i] + '"'
return s
def calFileSize(len_ms: int, avgBitRate: int) -> int:
"根据视频时长(ms)和平均码率计算视频大小"
return round(len_ms * avgBitRate / 8)
def dwaria2(r, fn, url, size, d2, ip, se, i=1, n=1, d=False):
logg = None
if 'logg' in ip:
logg = ip['logg']
if d:
print(lan['OUTPUT1'].replace('<i>', str(i)).replace('<count>', str(n))) # 正在开始下载第<i>个文件,共<count>个文件
else:
print(lan['OUTPUT2']) # 正在开始下载
(fn1, fn2) = file.spfln(fn)
cm = 'aria2c --auto-file-renaming=false' + geth(r.headers) + ' -o "' + fn2 + '" -d "' + fn1 + '"'
ack = True
if 'cc' in se:
ack = se['cc']
if 'cc' in se:
ack = se['cc']
cm += f" --check-certificate={'true' if ack else 'false'}"
arc = 3
read = JSONParser.getset(se, 'ax')
if read is not None:
arc = read
if 'ax' in ip:
arc = ip['ax']
ars = 5
read = JSONParser.getset(se, 'as')
if read is not None:
ars = read
if 'as' in ip:
ars = ip['as']
arfa = 'prealloc'
if 'fa' in se:
arfa = se['fa']
if 'fa' in ip:
arfa = ip['fa']
ark = 5
read = JSONParser.getset(se, 'ak')
if read is not None:
ark = read
if 'ak' in ip:
ark = ip['ak']
ms = "0"
read = JSONParser.getset(se, 'ms')
if read is not None:
ms = read
if 'ms' in ip:
ms = ip['ms']
xs = ""
if ms != "0":
xs = lan['OUTPUT4'].replace('<value>', ms) # ,限速为<value>
asd = True
if JSONParser.getset(se, 'cad') is True:
asd = False
if 'cad' in ip:
asd = not ip['cad']
if asd:
asd = "true"
else:
asd = "false"
print(lan['OUTPUT3'].replace('<value1>', str(ars)).replace('<value2>', str(arc)).replace('<value3>', str(ark)).replace('<value4>', arfa).replace('<maxspeed>', xs)) # 单文件最大<value1>个连接,单个服务器最大<value2>个连接,文件分片大小<value3>M,预分配方式为<value4><maxspeed>
cm = cm + ' -x ' + str(arc)
cm = cm + ' -s ' + str(ars)
cm = cm + ' --file-allocation=' + arfa
cm = cm + ' -k %sM' % (ark)
cm = cm + ' --max-overall-download-limit=' + ms
cm = cm + ' --async-dns=' + asd
if 'anopro' in ip:
cm += ' --http-proxy='
elif 'ahttpproxy' in ip:
cm = cm + ' --http-proxy=' + ip['ahttpproxy']
if 'anopro' in ip:
cm += ' --https-proxy='
elif 'ahttpsproxy' in ip:
cm = cm + ' --https-proxy=' + ip['ahttpsproxy']
if os.path.exists(fn):
oa = os.path.exists('%s.aria2' % (fn))
if oa:
s = lan['OUTPUT5'] # (发现aria2文件,建议覆盖)
else:
s = ""
bs = True
fg = False
if logg is not None:
logg.write(f"d2 = {d2}\noa = {oa}", currentframe(), "DWARIA2 ARIA2")
if d2 and not oa:
print(lan['OUTPUT6']) # 未找到aria2文件,跳过下载
return 0
if d2 and oa:
cm = cm + ' -c'
if not d2 and ('y' in ip or 's' in ip):
if 's' in ip:
fg = True
bs = False
if 'y' in se:
fg = se['y']
bs = False
if 'y' in ip:
fg = ip['y']
bs = False
while bs and not d2:
inp = input(f'{lan["INPUT1"].replace("<filename>",fn)}{s}(y/n)') # "<filename>"文件已存在,是否覆盖?
if len(inp) > 0:
if inp[0].lower() == 'y':
fg = True
bs = False
elif inp[0].lower() == 'n':
bs = False
if not d2 and fg:
try:
os.remove(fn)
except:
if logg is not None:
logg.write(format_exc(), currentframe(), "DWARIA2 REMOVE FILE FAILED")
print(lan['OUTPUT7']) # 删除原有文件失败,跳过下载
return 0
elif not d2:
return 0
if isinstance(url, str):
cm = cm + ' "' + url + '"'
elif isinstance(url, list):
for i in url:
cm = cm + ' "' + i + '"'
if logg is not None:
logg.write(f"cm = {cm}", currentframe(), "DWARIA2 COMMAND LINE")
re = os.system(cm)
if logg is not None:
logg.write(f"re = {re}", currentframe(), "DWARIA2 RESULT")
if re == 0:
return 0
elif re == 28:
return -3
else:
return -2
def geturll(d):
l = [] # noqa: E741
def isp(u, l): # noqa: E741
for i in l:
if u == i:
return False
return True
if 'url' in d:
l.append(d['url'])
if 'base_url' in d:
l.append(d['base_url'])
if 'video_playurl' in d:
l.append(d['video_playurl'])
if 'backup_url' in d and d['backup_url'] is not None:
for i in d['backup_url']:
if isp(i, l):
l.append(i)
if 'backup_playurl' in d and d['backup_playurl'] is not None:
for i in d['backup_playurl']:
if isp(i, l):
l.append(i)
return l
def tim():
"返回当前时间(毫秒)"
return int(time.time() * 1000)
def sea(s: str, avq: list):
"获取id在avq中的索引"
t = search('^[0-9]+', s)
if t:
t = int(t.group())
k = 0
for i in avq:
if i == t:
break
k = k + 1
return k
def sev(s: str):
t = search('^[0-9]+(.+)', s)
if t:
return t.groups()[0]
return ""
def avvideodownload(i, url, data, r, c, c3, se, ip, ud):
"""下载av号视频
-1 cookies.json读取错误
-2 API Error
-3 下载错误
-4 aria2c参数错误
-5 文件夹创建失败
-6 缺少必要参数"""
fnl = ip['fnl'] if 'fnl' in ip else se["fnl"] if "fnl" in se else 80
log = False
logg = None
if 'logg' in ip:
log = True
logg = ip['logg']
oll = None
if 'oll' in ip:
oll = ip['oll']
ns = True
if 's' in ip:
ns = False
bp = False # 删除无用文件时是否保留封面图片
if JSONParser.getset(se, 'bp') is True:
bp = True
if 'bp' in ip:
bp = ip['bp']
nte = False
if JSONParser.getset(se, 'te') is False:
nte = True
if 'te' in ip:
nte = not ip['te']
o = "Download/"
read = JSONParser.getset(se, 'o')
if read is not None:
o = read
if 'o' in ip:
o = ip['o']
dmp = False # 是否为多P视频创建单独文件夹
if JSONParser.getset(se, 'dmp') is True:
dmp = True
if 'dmp' in ip:
dmp = ip['dmp']
if data['videos'] == 1:
dmp = False
F = False # 仅输出视频信息
if 'F' in ip:
F = True
fin = True
if JSONParser.getset(se, 'in') is False:
fin = False
if 'in' in ip:
fin = ip['in']
if dmp:
if not fin:
o = f"{o}{file.filtern(data['title'], fnl)}/"
else:
o = "%s%s/" % (o, file.filtern(f"{data['title']}(AV{data['aid']},{data['bvid']})", fnl))
if log:
logg.write(f"ns = {ns}\nbp = {bp}\nnte = {nte}\no = '{o}'\ndmp = {dmp}\nF = {F}\nfin = {fin}", currentframe(), "Normal Video Download Var1")
try:
if not os.path.exists(o):
mkdir(o)
except:
if log:
logg.write(format_exc(), currentframe(), "Normal Video Download Mkdir Failed")
print(lan['ERROR1'].replace('<dirname>', o)) # 创建文件夹"<dirname>"失败
return -5
nbd = True
if JSONParser.getset(se, 'bd') is True:
nbd = False
if 'bd' in ip:
nbd = not ip['bd']
vf = 'mkv'
if 'vf' in se:
vf = se['vf']
if 'vf' in ip:
vf = ip['vf']
if log:
logg.write(f"nbd = {nbd}\nvf = {vf}", currentframe(), "Normal Video Download Var2")
if not os.path.exists('Temp/'):
mkdir('Temp/')
r2 = requests.Session()
r2.headers = copydict(r.headers)
if nte:
r2.trust_env = False
r2.proxies = r.proxies
read = JSONParser.loadcookie(r2, logg)
if read != 0:
print(lan['ERROR2']) # 读取cookies.json出现错误
return -1
if i > 1:
url = "%s?p=%s" % (url, i)
r2.headers.update({'referer': url})
if data['videos'] >= 1:
uri = "https://api.bilibili.com/x/player/playurl?cid=%s&qn=%s&otype=json&bvid=%s&fnver=0&fnval=976&session=" % (data['page'][i - 1]['cid'], 125, data['bvid'])
if log:
logg.write(f"GET {uri}", currentframe(), "Get Normal Video Playurl")
re = r2.get(uri)
re.encoding = "utf8"
if log:
logg.write(f"status = {re.status_code}\n{re.text}", currentframe(), "Get Normal Video Playurl Result")
re = re.json()
if re["code"] != 0:
print({"code": re["code"], "message": re["message"]})
return -2
napi = False
else:
return -2
uri = f"https://api.bilibili.com/x/player.so?id=cid:{data['page'][i-1]['cid']}&aid={data['aid']}&bvid={data['bvid']}&buvid={r.cookies.get('buvid3')}"
if log:
logg.write(f"GET {uri}", currentframe(), "Get Normal Video Player.so")
rr = r2.get(uri)
rr.encoding = 'utf8'
if log:
logg.write(f"status = {rr.status_code}\n{rr.text}", currentframe(), "Get Normal Video Player.so Result")
rs2 = search(r'<subtitle>(.+)</subtitle>', rr.text)
if F:
print(f"{lan['OUTPUT8'].replace('<number>',str(i))}{data['page'][i-1]['part']}") # 第<number>P:
if rs2 is not None:
rs2 = json.loads(rs2.groups()[0])
if log:
logg.write(f"rs2 = {rs2}", currentframe(), "Get Normal Video Player.so Sub Regex")
JSONParser2.getsub(rs2, data)
if "data" in re and "durl" in re['data']:
vq = re["data"]["quality"]
vqd = getqualitytransl(re["data"]["accept_description"])
avq = re["data"]["accept_quality"]
durl = {vq: re["data"]['durl']}
durz = {}
vqs = ""
if log:
logg.write(f"vq = {vq}\nvqd = {vqd}\navq = {avq}\nvqs = {vqs}", currentframe(), "Normal Video Download Var3")
if 'V' in ip and not F:
targetVq = ip['V']['id']
if targetVq not in avq:
for quality in avq:
if quality < targetVq:
targetVq = quality
break
if targetVq not in avq:
targetVq = avq[0]
if vq != targetVq:
if napi:
r2.cookies.set('CURRENT_QUALITY', str(targetVq), domain='.bilibili.com', path='/')
if log:
logg.write(f"Current request quality: {targetVq}\nGET {url}", currentframe(), "Get Normal Video Webpage3")
re = r2.get(url)
re.encoding = 'utf8'
if log:
logg.write(f"status = {re.status_code}\n{re.text}", currentframe(), "Get Normal Video Webpage3 Result")
rs = search('__playinfo__=([^<]+)', re.text)
if rs is not None:
re = json.loads(rs.groups()[0])
if log:
logg.write(f"re = {re}", currentframe(), "Get Normal Video Webpage3 Regex")
else:
return -2
else:
uri = f"https://api.bilibili.com/x/player/playurl?cid={data['page'][i-1]['cid']}&qn={targetVq}&otype=json&bvid={data['bvid']}&fnver=0&fnval=976"
if log:
logg.write(f"GET {uri}", currentframe(), "Get Normal Video Playurl3")
re = r2.get(uri)
re.encoding = 'utf8'
if log:
logg.write(f"status = {re.status_code}\n{re.text}", currentframe(), "Get Normal Video Playurl3 Result")
re = re.json()
if re["code"] != 0:
print(f"{re['code']} {re['message']}")
return -2
durl[re["data"]['quality']] = re['data']['durl']
targetVq = re["data"]['quality']
vqs = vqd[avq.index(targetVq)]
vq = targetVq
durz = 0
for k in durl[vq]:
durz += k['size']
if ns:
print(f"{lan['OUTPUT10']}{file.info.size(durz)}({durz}B,{file.cml(durz, re['data']['timelength'])})") # 大小:
durl = durl[vq]
elif not c or F:
j = 0
for l in avq: # noqa: E741
if l not in durl:
if napi:
r2.cookies.set('CURRENT_QUALITY', str(l), domain='.bilibili.com', path='/')
if log:
logg.write(f"Current request quality: {l}\nGET {url}", currentframe(), "Get Normal Video Webpage2")
re = r2.get(url)
re.encoding = 'utf8'
if log:
logg.write(f"status = {re.status_code}\n{re.text}", currentframe(), "Get Normal Video Webpage2 Result")
rs = search('__playinfo__=([^<]+)', re.text)
if rs is not None:
re = json.loads(rs.groups()[0])
if log:
logg.write(f"re = {re}", currentframe(), "Get Normal Video Webpage2 Regex")
else:
return -2
else:
uri = "https://api.bilibili.com/x/player/playurl?cid=%s&qn=%s&otype=json&bvid=%s&fnver=0&fnval=976" % (data['page'][i - 1]['cid'], l, data['bvid'])
if log:
logg.write(f"GET {uri}", currentframe(), "Get Normal Video Playurl2")
re = r2.get(uri)
re.encoding = 'utf8'
if log:
logg.write(f"status = {re.status_code}\n{re.text}", currentframe(), "Get Normal Video Playurl2 Result")
re = re.json()
if re["code"] != 0:
print({"code": re["code"], "message": re["message"]})
return -2
durl[re["data"]['quality']] = re['data']['durl']
if ud['vip'] < 1 and (l > 80 or l == 74):
avq, ii = delli(avq, l)
if ii > -1:
vqd = dellk(vqd, ii)
continue
if ns or (not ns and F):
print(f"{j+1}.{lan['OUTPUT9']}{vqd[j]}") # 图质:
j = j + 1
size = 0
for k in durl[l]:
size = size + k['size']
durz[l] = size
if ns or (not ns and F):
print(f"{lan['OUTPUT10']}{file.info.size(size)}({size}B,{file.cml(size,re['data']['timelength'])})") # 大小:
if log:
logg.write(f"durl.keys() = {durl.keys()}\ndurz = {durz}\nvqs = {vqs}", currentframe(), "Normal Video Download Var4")
r2.cookies.set('CURRENT_QUALITY', '125', domain='.bilibili.com', path='/')
if F:
return 0
bs = True
fi = True
while bs:
if fi and 'v' in ip:
fi = False
inp = ip['v']
elif ns:
inp = input(lan['INPUT2']) # 请选择画质:
else:
print(lan['ERROR3']) # 请使用"-v <id>"选择画质
return -6
if len(inp) > 0 and inp.isnumeric() and int(inp) > 0 and int(inp) < len(avq) + 1:
durl = durl[avq[int(inp) - 1]]
durz = durz[avq[int(inp) - 1]]
vq = avq[int(inp) - 1]
bs = False
if ns:
print(lan['OUTPUT11'].replace('<videoquality>', vqd[int(inp) - 1])) # 已选择<videoquality>画质
vqs = vqd[int(inp) - 1]
else:
j = 0
for l in avq: # noqa: E741
if l == vq: # noqa: E741
if ns:
print(f"{lan['OUTPUT9']}{vqd[j]}") # 画质:
vqs = vqd[j]
break
j = j + 1
durz = 0
for k in durl[vq]:
durz = durz + k['size']
if ns:
print(f"{lan['OUTPUT10']}{file.info.size(durz)}({durz}B,{file.cml(durz,re['data']['timelength'])})") # 大小:
durl = durl[vq]
if log:
logg.write(f"vq = {vq}\ndurl = {durl}\ndurz = {durz}\nvqs = {vqs}", currentframe(), "Normal Video Download Var5")
sv = True
if JSONParser.getset(se, 'sv') is False:
sv = False
if 'sv' in ip:
sv = ip['sv']
if data['videos'] == 1:
if not fin:
filen = f"{o}{file.filtern(data['title'], fnl)}"
elif sv:
filen = '%s%s' % (o, file.filtern('%s(AV%s,%s,P%s,%s,%s)' % (data['title'], data['aid'], data['bvid'], i, data['page'][i - 1]['cid'], vqs), fnl))
else:
filen = '%s%s' % (o, file.filtern('%s(AV%s,%s,P%s,%s)' % (data['title'], data['aid'], data['bvid'], i, data['page'][i - 1]['cid']), fnl))
else:
if not fin and not dmp:
filen = o + file.filtern(f"{data['title']}-{i}.{data['page'][i-1]['part']}", fnl)
elif not fin and dmp:
filen = o + file.filtern(f"{i}.{data['page'][i - 1]['part']}", fnl)
elif sv and not dmp:
filen = '%s%s' % (o, file.filtern(f"{data['title']}-{i}.{data['page'][i-1]['part']}(AV{data['aid']},{data['bvid']},P{i},{data['page'][i-1]['cid']},{vqs})", fnl))
elif not dmp:
filen = '%s%s' % (o, file.filtern(f"{data['title']}-{i}.{data['page'][i-1]['part']}(AV{data['aid']},{data['bvid']},P{i},{data['page'][i-1]['cid']})", fnl))
elif sv:
filen = '%s%s' % (o, file.filtern(f"{i}.{data['page'][i - 1]['part']}(P{i},{data['page'][i - 1]['cid']},{vqs})", fnl))
else:
filen = '%s%s' % (o, file.filtern(f"{i}.{data['page'][i - 1]['part']}(P{i},{data['page'][i - 1]['cid']})", fnl))
ff = True
if JSONParser.getset(se, 'nf') is True:
ff = False
if 'yf' in ip:
if ip['yf']:
ff = True
else:
ff = False
ma = True
if JSONParser.getset(se, "ma") is False:
ma = False
if 'ma' in ip:
ma = ip['ma']
if log:
logg.write(f"sv = {sv}\nfilen = {filen}\nff = {ff}\nma = {ma}", currentframe(), "Normal Video Download Var6")
if ff and (len(durl) > 1 or ma) and os.path.exists(f'{filen}.{vf}') and os.system(f'ffmpeg -h{getnul()}') == 0:
fg = False
bs = True
if not ns:
fg = True
bs = False
if 'y' in se:
fg = se['y']
bs = False
if 'y' in ip:
fg = ip['y']
bs = False
while bs:
inp = input(f"{lan['INPUT1'].replace('<filename>', '%s.%s' % (filen, vf))}(y/n)")
if len(inp) > 0:
if inp[0].lower() == 'y':
fg = True
bs = False
elif inp[0].lower() == 'n':
bs = False
if fg:
try:
os.remove(f'{filen}.{vf}')
except:
if log:
logg.write(format_exc(), currentframe(), "Normal Video Download Remove File Failed")
print(lan['OUTPUT7'])
return 0
else:
return 0
if ns:
print(lan['OUTPUT12'].replace('<number>', str(len(durl)))) # 共有<number>个文件
j = 1
hzm = file.geturlfe(durl[0]['url'])
com = 0
for k in durl:
if len(durl) == 1:
fn = '%s.%s' % (filen, hzm)
bs2 = True
while bs2:
bs2 = False
ar = True
if JSONParser.getset(se, 'a') is False:
ar = False
if 'ar' in ip:
if ip['ar']:
ar = True
else:
ar = False
if log:
logg.write(f"fn = {fn}\nar = {ar}", currentframe(), "Normal Video Download Var7")
if os.system('aria2c -h%s' % (getnul())) == 0 and ar:
ab = True
if JSONParser.getset(se, 'ab') is False:
ab = False
if 'ab' in ip:
if ip['ab']:
ab = True
else:
ab = False
if log:
logg.write(f"ab = {ab}", currentframe(), "Normal Video Download Var8")
if ab:
read = dwaria2(r2, fn, geturll(k), k['size'], c3, ip, se)
else:
read = dwaria2(r2, fn, k['url'], k['size'], c3, ip, se)
if read == -3:
print(f"{lan['ERROR4']}{lan['ERROR5']}") # aria2c 参数错误
return -4
else:
if log:
logg.write(f"GET {k['url']}", currentframe(), "Normal Video Download Video Request")
re = r2.get(k['url'], stream=True)
read = downloadstream(nte, ip, k['url'], r2, re, fn, k['size'], c3)
if log:
logg.write(f"read = {read}", currentframe(), "Normal Video Download Var9")
if read == -1:
return -1
elif read == -2:
bs = True
rc = False
if not ns:
bs = False
read = JSONParser.getset(se, 'rd')
if read is True:
bs = False
rc = True
elif read is False:
bs = False
if 'r' in ip:
if ip['r']:
rc = True
bs = False
else:
rc = False
bs = False
while bs:
inp = input(f"{lan['INPUT3']}(y/n)") # 文件下载失败,是否重新下载?
if len(inp) > 0:
if inp[0].lower() == 'y':
bs = False
rc = True
elif inp[0].lower() == 'n':
bs = False
if rc:
if os.path.exists(fn):
os.remove(fn)
bs2 = True
else:
return -3
else:
fn = '%s_%s.%s' % (filen, j, hzm)
bs2 = True
while bs2:
bs2 = False
ar = True
if JSONParser.getset(se, 'a') is False:
ar = False
if 'ar' in ip:
if ip['ar']:
ar = True
else:
ar = False
if log:
logg.write(f"fn = {fn}\nar = {ar}\nj = {j}", currentframe(), "Normal Video Download Var10")
if os.system('aria2c -h%s' % (getnul())) == 0 and ar:
ab = True
if JSONParser.getset(se, 'ab') is False:
ab = False
if 'ab' in ip:
if ip['ab']:
ab = True
else:
ab = False
if log:
logg.write(f"ab = {ab}", currentframe(), "Normal Video Download Var11")
if ab:
read = dwaria2(r2, fn, geturll(k), k['size'], c3, ip, se, j, len(durl), True)
else:
read = dwaria2(r2, fn, k['url'], k['size'], c3, ip, se, j, len(durl), True)
if read == -3:
print(f"{lan['ERROR4']}{lan['ERROR5']}") # aria2c 参数错误
return -4
else:
if log:
logg.write(f"GET {k['url']}", currentframe(), "Normal Video Download Video Request2")
re = r2.get(k['url'], stream=True)
read = downloadstream(nte, ip, k['url'], r2, re, fn, k['size'], c3, j, len(durl), True, durz, com)
if log:
logg.write(f"read = {read}", currentframe(), "Normal Video Download Var12")
if read == -1:
return -1
elif read == -2:
bs = True
rc = False
if not ns:
bs = False
read = JSONParser.getset(se, 'rd')
if read is True:
bs = False
rc = True
elif read is False:
bs = False
if 'r' in ip:
if ip['r']:
rc = True
bs = False
else:
rc = False
bs = False
while bs:
inp = input(f"{lan['INPUT3']}(y/n)") # 文件下载失败,是否重新下载?
if len(inp) > 0:
if inp[0].lower() == 'y':
bs = False
rc = True
elif inp[0].lower() == 'n':
bs = False
if rc:
if os.path.exists(fn):
os.remove(fn)
bs2 = True
else:
return -3
com = com + k['size']
if oll:
oll.add(fn)
j = j + 1
if 'sub' in data:
for s in data['sub']:
downsub(r2, filen + "." + vf, s, ip, se, data, ns, i)
imgs = -1
if 'pic' in data:
imgf = file.spfn(filen + "." + vf)[0] + "." + file.geturlfe(data['pic']) # 图片文件名
imgs = avpicdownload(data, r, ip, se, imgf) # 封面下载状况
if log:
logg.write(f"imgf = {imgf}\nimgs = {imgs}", currentframe(), "Normal Video Download Var13")
if (len(durl) > 1 or ma) and os.system('ffmpeg -h%s' % (getnul())) == 0 and ff:
print(lan['OUTPUT13']) # 将用ffmpeg自动合成
tt = int(time.time())
sa = ""
sb = ""
nss = ""
imga = ""
imga2 = ""
if not ns:
nss = getnul()
if 'sub' in data:
sa, sb = ffinputstr(data['sub'], 2, 1, logg=logg)
if imgs == 0 and vf == "mkv":
imga = f" -attach \"{imgf}\" -metadata:s:t mimetype=image/jpeg"
elif imgs == 0 and vf == "mp4":
imga = f' -i "{imgf}"'
imga2 = ' -disposition:v:1 attached_pic'
if 'sub' in data:
sa, sb = ffinputstr(data['sub'], 3, 1, logg=logg)
else:
sb = ' -map 0 -map 2'
if len(durl) > 1 and vf == "mkv":
te = open('Temp/%s_%s.txt' % (file.filtern('%s' % (data['aid']), 80), tt), 'wt', encoding='utf8')
j = 1
for k in durl:
te.write("file '../%s_%s.%s'\n" % (filen, j, hzm))
j = j + 1
te.close()
tit = data['title']
tit2 = data['page'][i - 1]['part']
if tit2 != "":
tit = f'{tit} - {tit2}'
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'w', encoding='utf8', newline='\n') as te:
te.write(';FFMETADATA1\n')
te.write(f"aid={data['aid']}\n")
te.write(f"bvid={data['bvid']}\n")
te.write(f"ctime={tostr2(data['ctime'])}\n")
te.write(f"description={bstr.g(data['desc'])}\n")
te.write(f"p={i}P/{data['videos']}P\n")
te.write(f"title={bstr.g(tit)}\n")
te.write(f"pubdate={tostr2(data['pubdate'])}\n")
te.write(f"uid={data['uid']}\n")
te.write(f"artist={bstr.g(data['name'])}\n")
te.write(f"author={bstr.g(data['name'])}\n")
te.write(f"cid={data['page'][i-1]['cid']}\n")
te.write(f"atitle={bstr.g(data['title'])}\n")
te.write(f"part={bstr.g(data['page'][i-1]['part'])}\n")
te.write(f"vq={bstr.g(vqs)}\n")
te.write(f"purl={bstr.g(url)}\n")
te.write(f"tags={bstr.g(bstr.gettags(data['tags']))}\n")
if log:
with open(f"Temp/{data['aid']}_{tt}.txt", 'r', encoding='utf8') as te:
logg.write(f"INPUT FILE 'Temp/{data['aid']}_{tt}.txt'\n{te.read()}", currentframe(), "Normal Video Video Download Temp File")
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'r', encoding='utf8') as te:
logg.write(f"METADATAFILE 'Temp/{data['aid']}_{tt}_metadata.txt'\n{te.read()}", currentframe(), "Normal Video Video Download Metadata")
ml = f"ffmpeg -f concat -safe 0 -i \"Temp/{data['aid']}_{tt}.txt\" -i \"Temp/{data['aid']}_{tt}_metadata.txt\"{sa} -map_metadata 1{sb}{imga} -c copy \"{filen}.mkv\"{nss}"
elif vf == "mkv":
tit = data['title']
tit2 = data['page'][i - 1]['part']
if tit2 != "":
tit = f'{tit} - {tit2}'
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'w', encoding='utf8', newline='\n') as te:
te.write(';FFMETADATA1\n')
te.write(f"aid={data['aid']}\n")
te.write(f"bvid={data['bvid']}\n")
te.write(f"ctime={tostr2(data['ctime'])}\n")
te.write(f"description={bstr.g(data['desc'])}\n")
te.write(f"p={i}P/{data['videos']}P\n")
te.write(f"title={bstr.g(tit)}\n")
te.write(f"pubdate={tostr2(data['pubdate'])}\n")
te.write(f"uid={data['uid']}\n")
te.write(f"artist={bstr.g(data['name'])}\n")
te.write(f"author={bstr.g(data['name'])}\n")
te.write(f"cid={data['page'][i-1]['cid']}\n")
te.write(f"atitle={bstr.g(data['title'])}\n")
te.write(f"part={bstr.g(data['page'][i-1]['part'])}\n")
te.write(f"vq={bstr.g(vqs)}\n")
te.write(f"purl={bstr.g(url)}\n")
te.write(f"tags={bstr.g(bstr.gettags(data['tags']))}\n")
if log:
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'r', encoding='utf8') as te:
logg.write(f"METADATAFILE 'Temp/{data['aid']}_{tt}_metadata.txt'\n{te.read()}", currentframe(), "Normal Video Video Download Metadata2")
ml = f"ffmpeg -i \"{filen}.{hzm}\" -i \"Temp/{data['aid']}_{tt}_metadata.txt\"{sa} -map_metadata 1{sb}{imga} -c copy \"{filen}.mkv\"{nss}"
elif len(durl) > 1:
te = open('Temp/%s_%s.txt' % (file.filtern('%s' % (data['aid']), 80), tt), 'wt', encoding='utf8')
j = 1
for k in durl:
te.write("file '../%s_%s.%s'\n" % (filen, j, hzm))
j = j + 1
te.close()
tit = data['title']
tit2 = data['page'][i - 1]['part']
if tit2 != "":
tit = f'{tit} - {tit2}'
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'w', encoding='utf8', newline='\n') as te:
te.write(';FFMETADATA1\n')
te.write(f"title={bstr.g(tit)}\n")
te.write(f"comment={bstr.g(data['desc'])}\n")
te.write(f"album={bstr.g(data['title'])}\n")
te.write(f"artist={bstr.g(data['name'])}\n")
te.write(f"album_artist={bstr.g(data['name'])}\n")
te.write(f"track={i}/{data['videos']}\n")
te.write("disc=1/1\n")
te.write(f"episode_id=AV{data['aid']}\n")
te.write(f"date={tostr4(data['pubdate'])}\n")
te.write(f"description={bstr.g(vqs)},{data['uid']}\\\n")
te.write(f"{bstr.g(bstr.gettags(data['tags']))}\\\n")
te.write(f"{bstr.g(url)}\n")
te.write(f"genre={bstr.g(bstr.gettags(data['tags']))}\n")
if log:
with open(f"Temp/{data['aid']}_{tt}.txt", 'r', encoding='utf8') as te:
logg.write(f"INPUT FILE 'Temp/{data['aid']}_{tt}.txt'\n{te.read()}", currentframe(), "Normal Video Video Download Temp File2")
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'r', encoding='utf8') as te:
logg.write(f"METADATAFILE 'Temp/{data['aid']}_{tt}_metadata.txt'\n{te.read()}", currentframe(), "Normal Video Video Download Metadata3")
ml = f"ffmpeg -f concat -safe 0 -i \"Temp/{data['aid']}_{tt}.txt\" -i \"Temp/{data['aid']}_{tt}_metadata.txt\"{imga}{sa} -map_metadata 1{sb} -c copy -c:s mov_text{imga2} \"{filen}.mp4\"{nss}"
else:
tit = data['title']
tit2 = data['page'][i - 1]['part']
if tit2 != "":
tit = f'{tit} - {tit2}'
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'w', encoding='utf8', newline='\n') as te:
te.write(';FFMETADATA1\n')
te.write(f"title={bstr.g(tit)}\n")
te.write(f"comment={bstr.g(data['desc'])}\n")
te.write(f"album={bstr.g(data['title'])}\n")
te.write(f"artist={bstr.g(data['name'])}\n")
te.write(f"album_artist={bstr.g(data['name'])}\n")
te.write(f"track={i}/{data['videos']}\n")
te.write("disc=1/1\n")
te.write(f"episode_id=AV{data['aid']}\n")
te.write(f"date={tostr4(data['pubdate'])}\n")
te.write(f"description={bstr.g(vqs)},{data['uid']}\\\n")
te.write(f"{bstr.g(bstr.gettags(data['tags']))}\\\n")
te.write(f"{bstr.g(url)}\n")
te.write(f"genre={bstr.g(bstr.gettags(data['tags']))}\n")
if log:
with open(f"Temp/{data['aid']}_{tt}_metadata.txt", 'r', encoding='utf8') as te:
logg.write(f"METADATAFILE 'Temp/{data['aid']}_{tt}_metadata.txt'\n{te.read()}", currentframe(), "Normal Video Video Download Metadata4")
ml = f"ffmpeg -i \"{filen}.{hzm}\" -i \"Temp/{data['aid']}_{tt}_metadata.txt\"{imga}{sa} -map_metadata 1{sb} -c copy -c:s mov_text{imga2} \"{filen}.mp4\"{nss}"
if log:
logg.write(f"ml = {ml}", currentframe(), "Normal Video Download FFmpeg Command Line")
re = os.system(ml)
if log:
logg.write(f"re = {re}", currentframe(), "Normal Video Download FFmpeg Return")
if re == 0:
print(lan['OUTPUT14']) # 合并完成!
de = False
if re == 0:
if oll:
oll.add(f"{filen}.{vf}")
bs = True
if not ns:
bs = False
if JSONParser.getset(se, 'ad') is True:
de = True
bs = False
elif JSONParser.getset(se, 'ad') is False:
bs = False
if 'ad' in ip:
if ip['ad']:
de = True
bs = False
else:
de = False
bs = False
while bs:
inp = input(f"{lan['INPUT4']}(y/n)") # 是否删除中间文件?
if len(inp) > 0:
if inp[0].lower() == 'y':
bs = False
de = True
elif inp[0].lower() == 'n':
bs = False
if re == 0 and de:
if len(durl) > 1:
j = 1
for k in durl:
os.remove("%s_%s.%s" % (filen, j, hzm))
j = j + 1
else:
os.remove('%s.%s' % (filen, hzm))
if 'sub' in data and nbd:
for j in data['sub']:
os.remove(j['fn'])