-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
executable file
·1943 lines (1817 loc) · 72.6 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
#!/usr/bin/env python3
"""
Copyright (c) 2025 Laosun Studios.
Distributed under GPL-3.0 License.
The product is developing. Effect currently
displayed is for reference only. Not indicative
of final product.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
The old version also use the GPL-3.0 license, not MIT License.
"""
import base64
import datetime
import getpass
import json
import os
import reprlib
import shutil
import subprocess
import sys
import time
import traceback
from typing import Generator, List
import requests
import rsa
from google.protobuf.json_format import MessageToJson
from tqdm import tqdm
from bilibili.protobuf.dm_pb2 import DmSegMobileReply
# from bilibili.biliass.protobuf.danmaku_pb2 import DmSegMobileReply
from bilibili.utils import (
av2bv,
bv2av,
format_time,
validate_title,
encrypt_wbi,
user_manager,
hum_convert,
get_danmaku,
remove, parse_view, danmaku_provider,
)
__version__ = "1.0.0-dev"
__year__ = 2025
__author__ = "Laosun Studios"
saw = False
quality_mapping = {6: "240P 极速", 16: "360P 流畅", 32: "480P 清晰", 64: "720P 高清", 74: "720P60 高帧率",
80: "1080P 高清", 112: "1080P+ 高码率", 116: "1080P60 高帧率", 120: "4K 超清"}
def view_short_video_info(bvid):
video = user_manager.get(
"https://api.bilibili.com/x/web-interface/view/detail?bvid=" + bvid
)
item = video.json()["data"]["View"]
print("封面: ", item["pic"])
print("标题: ", item["title"])
print(
"作者: ",
item["owner"]["name"],
" bvid: ",
item["bvid"],
" 日期: ",
datetime.datetime.fromtimestamp(
item["pubdate"]).strftime("%Y-%m-%d %H:%M:%S"),
" 视频时长:",
format_time(item["duration"]),
" 观看量: ",
item["stat"]["view"],
)
def show_help():
print(
"""帮助菜单:
recommend/r: 推荐
login/l: 登录
logout/lo: 登出
address/a: 按地址播放
bangumi/b: 按地址播放番剧
favorite/f: 查看收藏夹
search/s: 搜索
quit/q: 退出
enable_online_watching: 开启在线观看
disable_online_watching: 关闭在线观看
clean_cache: 清除缓存
refresh_login_state: 刷新登录状态
export_favorite: 导出收藏夹
export_all_favorite: 导出所有收藏夹
download_favorite: 下载收藏夹视频
history: 查看历史记录
view_self: 查看自己的空间
view_user: 查看用户空间
download_manga: 下载漫画
"""
)
class BilibiliLogin:
temp_header = {
"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) "
"Chrome/103.0.5060.134 Safari/537.36 Edg/103.0.1264.77",
"Referer": "https://www.bilibili.com",
}
temp_login_header = temp_header.copy()
@staticmethod
def generate_cookie():
r = requests.get("https://www.bilibili.com",
headers=BilibiliLogin.temp_header)
cookie = ""
for i, j in r.cookies.items():
cookie += f"{i}={j}; "
BilibiliLogin.temp_login_header["Cookie"] = cookie[:-2]
@staticmethod
def logout():
r = user_manager.post(
"https://passport.bilibili.com/login/exit/v2", data={"biliCSRF": user_manager.csrf})
rsp_json = r.json()
if rsp_json["code"] == 0:
print("退出登录成功.")
with open("cookie.txt", "w") as f:
f.write("")
user_manager.refresh_login()
@staticmethod
def login_by_password(username: str, password: str):
token, challenge, validate = BilibiliLogin.generate_captcha()
hash_, key = BilibiliLogin.get_key()
pk = rsa.PublicKey.load_pkcs1_openssl_pem(key.encode())
password_hash = rsa.encrypt((hash_ + password).encode(), pk)
password_base64 = base64.b64encode(password_hash)
data = {"username": username, "password": password_base64, "keep": 0, "token": token, "challenge": challenge,
"validate": validate, "seccode": validate + "|jordan"}
r = requests.post("https://passport.bilibili.com/x/passport-login/web/login", data=data,
headers=BilibiliLogin.temp_login_header)
if r.json()["code"] != 0 or r.json()["data"]["message"].startswith("本次登录"):
print("登录失败!")
print(r.json()["message"])
print(r.json()["data"]["message"])
return False
cookie = ""
for i, j in r.cookies.items():
cookie += f"{i}={j}; "
return cookie[:-2] + "; " + BilibiliLogin.temp_login_header["Cookie"]
@staticmethod
def send_sms(phone_number: str) -> str | bool:
token, challenge, validate = BilibiliLogin.generate_captcha()
data = {"cid": 86, "tel": phone_number, "challenge": challenge, "seccode": validate + "|jordan",
"validate": validate, "token": token,
"source": "main-fe-header"}
r = requests.post("https://passport.bilibili.com/x/passport-login/web/sms/send", data=data,
headers=BilibiliLogin.temp_login_header)
if r.json()["code"] != 0:
print("发送短信认证码失败! ")
print(r.json()["code"])
print(r.json()["message"])
return False
return r.json()["data"]["captcha_key"]
@staticmethod
def login_by_sms(phone_number: str, captcha_key: str, sms_code: str) -> str | bool:
data = {"cid": 86, "tel": phone_number, "captcha_key": captcha_key, "code": sms_code, "keep": True,
"source": "main_mini"}
r = requests.post("https://passport.bilibili.com/x/passport-login/web/login/sms", data=data,
headers=BilibiliLogin.temp_login_header)
if r.json()["code"] != 0:
print("登录失败! ")
print(r.json()["message"])
return False
cookie = ""
for i, j in r.cookies.items():
cookie += f"{i}={j}; "
return cookie[:-2] + "; " + BilibiliLogin.temp_login_header["Cookie"]
@staticmethod
def generate_captcha():
r = requests.get("https://passport.bilibili.com/x/passport-login/captcha",
headers=BilibiliLogin.temp_login_header)
data = r.json()
challenge = data["data"]["geetest"]["challenge"]
gt = data["data"]["geetest"]["gt"]
print("gt: ", gt, "challenge: ", challenge)
print("请到 https://kuresaru.github.io/geetest-validator/ 进行认证.")
while True:
validate = input("请输入得到的 validate: ")
if len(validate.strip()) != 32:
print("validate 长度错误! ")
continue
break
return data["data"]["token"], challenge, validate
@staticmethod
def get_key() -> tuple[str, str]:
r = requests.get("https://passport.bilibili.com/x/passport-login/web/key",
headers=BilibiliLogin.temp_login_header)
return r.json()["data"]["hash"], r.json()["data"]["key"]
class BilibiliManga:
@staticmethod
def get_manga_detail(manga_id: int) -> dict:
detail_request = user_manager.post(
"https://manga.bilibili.com/twirp/comic.v1.Comic/ComicDetail?device=pc&platform=web",
data={"comic_id": manga_id},
)
return detail_request.json()
@staticmethod
def list_history() -> dict:
history = user_manager.post(
"https://manga.bilibili.com/twirp/bookshelf.v1.Bookshelf/ListHistory?device=pc&platform=web",
data={"page_num": 1, "page_size": 50},
)
return history.json()
@staticmethod
def get_image_list(epid) -> dict:
images = user_manager.post(
"https://manga.bilibili.com/twirp/comic.v1.Comic/GetImageIndex?device=pc&platform=web",
data={"ep_id": epid},
)
return images.json()
@staticmethod
def get_token(image: str) -> dict:
token = user_manager.post(
"https://manga.bilibili.com/twirp/comic.v1.Comic/ImageToken?device=pc&platform=web",
data={"urls": '["{}"]'.format(image)},
)
return token.json()
@classmethod
def download_manga(cls, manga_id: int) -> bool:
manga_info = cls.get_manga_detail(manga_id)
ep_info = manga_info["data"]["ep_list"]
name = manga_info["data"]["title"]
if not os.path.exists("download/manga"):
os.mkdir("download/manga")
if not os.path.exists("download/manga/" + validate_title(name)):
os.mkdir("download/manga/" + validate_title(name))
first, end = input("选择回目范围 (1-{}): ".format(len(ep_info))).split("-")
try:
# first, end str值如果不可转换为 int 会直接跳出函数, 故对其忽略类型检查
first = int(first) # type: ignore
end = int(end) # type: ignore
except ValueError:
print("输入回目范围错误!")
return False
download_manga_epid = []
download_manga_name = []
locked = 0
for i in list(reversed(ep_info)):
if first <= i["ord"] <= end:
if i["is_locked"]:
locked += 1
continue
download_manga_epid.append(i["id"])
download_manga_name.append(i["title"])
print(f"有{locked}篇被上锁, 需要购买" if locked else "")
download_image = {}
cursor = 0
picture_count = 0
print("获取图片信息中.")
# 忽略原因同上
with tqdm(total=end) as progress_bar: # type: ignore
for i in download_manga_epid:
download_image_prefix = []
image_list = cls.get_image_list(i)
for j in image_list["data"]["images"]:
download_image_prefix.append(j["path"])
picture_count += 1
download_image[download_manga_name[cursor]
] = download_image_prefix
progress_bar.update(1)
cursor += 1
download_image_url = {}
print("获取图片token中.")
with tqdm(total=picture_count) as progress_bar:
for i, j in download_image.items():
download_image_url_local = []
for k in j:
token = cls.get_token(k)["data"][0]
download_image_url_local.append(
"{}?token={}".format(token["url"], token["token"])
)
progress_bar.update(1)
download_image_url[i] = download_image_url_local
print("下载图片中.")
byte = 0
with tqdm(total=picture_count) as progress_bar:
for i, j in download_image_url.items():
filename = 0
for k in j:
path = (
"download/manga/"
+ validate_title(name)
+ "/"
+ validate_title(i)
+ "/"
)
file = path + f"{filename}.jpg"
if not os.path.exists(path):
os.mkdir(path)
with open(file, "wb") as f:
byte += f.write(user_manager.get(k).content)
progress_bar.update(1)
filename += 1
print("下载完成. 总计下载了 {} 字节 ({})".format(byte, hum_convert(byte)))
return True
class BilibiliUserSpace:
@staticmethod
def get_following_list(mid: int):
following_list = []
pre_page = 20
r = user_manager.get(
f"https://api.bilibili.com/x/relation/fans?vmid={mid}&pn=1&ps={pre_page}"
)
total = r.json()["data"]["total"]
for i in range(1, total // pre_page + 2):
if i == 5:
break
r = user_manager.get(
f"https://api.bilibili.com/x/relation/fans?vmid={mid}&pn={i}&ps={pre_page}"
)
following_list += r.json()["data"]["list"]
return following_list
@staticmethod
def get_followed_list(mid: int):
followed_list = []
pre_page = 20
r = user_manager.get(
f"https://api.bilibili.com/x/relation/followings?vmid={mid}&pn=1&ps={pre_page}"
)
total = r.json()["data"]["total"]
for i in range(1, total // pre_page + 2):
if i == 5:
break
r = user_manager.get(
f"https://api.bilibili.com/x/relation/followings?vmid={mid}&pn={i}&ps={pre_page}"
)
followed_list += r.json()["data"]["list"]
return followed_list
# follow_type 1 关注 2 取关
@staticmethod
def modify_relation(mid: int, modify_type: int = 1):
data = {"fid": mid, "act": modify_type, "csrf": user_manager.csrf}
r = user_manager.post(
"https://api.bilibili.com/x/relation/modify", data=data)
if r.json()["code"] == 0:
print("更改用户关系成功.")
else:
print("更改用户关系失败!")
print(r.json()["message"])
@staticmethod
def get_user_data(mid: int):
user_info = user_manager.get(
"https://api.bilibili.com/x/space/wbi/acc/info?"
+ encrypt_wbi("mid=" + str(mid))
)
return user_info.json()["data"]
@staticmethod
def get_user_video(mid: int):
pre_page = 5
cursor = 1
request = user_manager.get(
"https://api.bilibili.com/x/space/wbi/arc/search?"
+ encrypt_wbi(f"mid={mid}&ps={pre_page}"),
cache=True,
)
total = request.json()["data"]["page"]["count"] // pre_page + 1
while True:
ls = user_manager.get(
"https://api.bilibili.com/x/space/wbi/arc/search?"
+ encrypt_wbi(f"mid={mid}&ps={pre_page}&pn={cursor}"),
cache=True,
)
if total < cursor:
break
yield ls.json()["data"]["list"]["vlist"]
cursor += 1
class BilibiliBangumi:
def __init__(self, quality: int):
self.quality = quality
@staticmethod
def get_follow_bangumi(mid) -> list:
r = user_manager.get(
f"https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=0&pn=1&ps=15"
+ f"&vmid={mid}",
cache=True,
)
if r.json()["code"] != 0:
raise Exception(r.json()["message"])
datas = []
for i in r.json()["data"]["list"]:
datas.append(
{
"watch_progress": i["progress"],
"img": i["cover"],
"title": i["title"],
"bangumi_type": i["season_type_name"],
"areas": i["areas"][0]["name"],
"update_progress": i["new_ep"]["index_show"],
}
)
return datas
@staticmethod
def get_self_follow_bangumi():
return BilibiliBangumi.get_follow_bangumi(user_manager.mid)
@staticmethod
def follow_bangumi(season_id):
data = {"season_id": season_id, "csrf": user_manager.csrf}
r = user_manager.post(
"https://api.bilibili.com/pgc/web/follow/add", data=data)
if r.json()["code"] == 0:
print("追番成功.")
else:
print("追番失败!")
print(f"失败信息: {r.json()['message']}")
@staticmethod
def cancel_follow_bangumi(season_id):
data = {"season_id": season_id, "csrf": user_manager.csrf}
r = user_manager.post(
"https://api.bilibili.com/pgc/web/follow/del", data=data)
if r.json()["code"] == 0:
print("取消追番成功.")
else:
print("取消追番失败!")
print(f"失败信息: {r.json()['message']}")
def select_bangumi(self, ssid="", epid=""):
if not any([ssid, epid]):
return
if ssid:
url = "https://api.bilibili.com/pgc/view/web/season?season_id=" + ssid
else:
url = "https://api.bilibili.com/pgc/view/web/season?ep_id=" + epid
bangumi_url = user_manager.get(url)
bangumi_page = bangumi_url.json()["result"]["episodes"]
for i, j in enumerate(bangumi_page):
print(f"{i + 1}: {j['share_copy']} ({j['badge']})")
print("请以冒号前面的数字为准选择视频.")
while True:
page = input("选择视频: ")
if page == "quit" or page == "q":
break
if not page:
continue
if not page.isdigit():
continue
if int(page) > len(bangumi_page) or int(page) <= 0:
print("选视频错误!")
continue
cid = bangumi_page[int(page) - 1]["cid"]
bvid = bangumi_page[int(page) - 1]["bvid"]
epid = bangumi_page[int(page) - 1]["id"]
title = bangumi_page[int(page) - 1]["share_copy"]
video = BilibiliVideo(
bvid=bvid, epid=epid, bangumi=True, quality=self.quality
)
video.play(cid, title=title)
# search_type
# article 专栏
# video 视频
# bili_user 用户
# live 直播
# media_ft 影视
# media_bangumi 番剧
# order
# click 播放量
# pubdate 最新
# dm 弹幕
# stow 收藏
# 空 综合
class BilibiliSearch:
@staticmethod
def search(keyword, search_type="video", order=""):
"""
搜索
:param keyword: 搜索关键词
:param search_type: 搜索类型 article 专栏 video 视频 bili_user 用户 live 直播 media_ft 影视 media_bangumi 番剧
:param order: 搜索排序 click 播放量 pubdate 最新 dm 弹幕 stow 收藏 空 综合
:return: 搜索结果
"""
pre_page = 5
cursor = 1
while True:
ls = user_manager.get(
f"https://api.bilibili.com/x/web-interface/wbi/search/type?page={cursor}"
f"&page_size={pre_page}&keyword={keyword}&search_type={search_type}"
+ (f"&order={order}" if order else ""),
cache=True,
)
if len(ls.json()["data"]["result"]) == 0:
break
result = ls.json()["data"]["result"]
for i in result:
i["title"] = remove(i["title"], '<em class="keyword">')
i["title"] = remove(i["title"], "</em>")
yield result
cursor += 1
class BilibiliHistory:
def __init__(self, csrf):
self.csrf = csrf
@staticmethod
def get_history():
url = "https://api.bilibili.com/x/web-interface/history/cursor?max={}&view_at={}&business={}"
max_ = 0
view_at = 0
business = ""
history = user_manager.get(url.format(max_, view_at, business))
while history.json()["data"]["cursor"]["max"] != 0:
data = history.json()["data"]["list"]
for cursor in range(0, len(data), 5):
yield data[cursor:cursor + 5]
max_ = history.json()["data"]["cursor"]["max"]
view_at = history.json()["data"]["cursor"]["view_at"]
business = history.json()["data"]["cursor"]["business"]
history = user_manager.get(url.format(max_, view_at, business))
def set_record_history(self, stop=True):
req = user_manager.post(
"https://api.bilibili.com/x/v2/history/shadow/set",
data={"jsonp": "jsonp", "csrf": self.csrf, "switch": stop},
)
if req.json()["code"] == 0:
print(("停止" if stop else "开启") + "记录历史成功.")
else:
print(("停止" if stop else "开启") + "记录历史失败!")
print("错误代码: ", req.json()["code"])
print("错误信息: ", req.json()["message"])
@staticmethod
def search_history(search=""):
url = "https://api.bilibili.com/x/web-goblin/history/search?pn={}&keyword={}&business=all"
cursor = 1
req = user_manager.get(url.format(cursor, search))
print("搜索数量: ", req.json()["data"]["page"]["total"])
while req.json()["data"]["has_more"]:
yield req.json()["data"]["list"]
cursor += 1
req = user_manager.get(url.format(cursor, search))
@staticmethod
def dump_history():
return [j for i in BilibiliHistory.get_history() for j in i]
class BilibiliFavorite:
@staticmethod
def select_favorite(mid: int, aid: int = 0) -> list[int] | int:
"""
选择收藏夹
:param mid: 用户mid
:param aid: 视频aid
:return: 收藏夹id list or int
"""
request = user_manager.get(
f"https://api.bilibili.com/x/v3/fav/folder/created/list-all?type=2&rid={aid}&up_mid={mid}",
cache=True,
)
print("\n")
print("选择收藏夹")
for index, item in enumerate(request.json()["data"]["list"]):
print(
f"{index + 1}: {item['title']} ({item['media_count']}) {'(已收藏)' if item['fav_state'] else ''}"
)
fail = False
ids = []
command = input("选择收藏夹(以逗号为分隔): ")
if command == "quit" or command == "q":
return 0
for index, item in enumerate(command.split(",")):
if not item.replace(" ", "").isdecimal():
print(f"索引{index + 1} 错误: 输入的必须为数字!")
fail = True
break
if int(item) - 1 < 0:
print(f"索引{index + 1} 错误: 输入的必须为正数!")
fail = True
break
try:
if request.json()["data"]["list"][int(item) - 1]["fav_state"]:
print(f"索引{index + 1} 警告: 此收藏夹已收藏过该视频, 将不会重复收藏.")
continue
ids.append(request.json()["data"]["list"][int(item) - 1]["id"])
except IndexError:
print(f"索引{index + 1} 错误: 索引超出收藏夹范围!")
fail = True
if fail:
print("收藏失败!")
return ids
@staticmethod
def select_one_favorite(mid: int, aid: int = 0):
request = user_manager.get(
f"https://api.bilibili.com/x/v3/fav/folder/created/list-all?type=2&rid={aid}&up_mid={mid}",
cache=True,
)
for index, item in enumerate(request.json()["data"]["list"]):
print(
f"{index + 1}: {item['title']} ({item['media_count']}) {'(已收藏)' if item['fav_state'] else ''}"
)
command = input("选择收藏夹: ")
if command == "quit" or command == "q":
return 0
if not command.isdecimal():
print(f"错误: 输入的必须为数字!")
return 0
try:
return request.json()["data"]["list"][int(command) - 1]["id"]
except IndexError:
print("错误: 索引超出收藏夹范围!")
return 0
except TypeError as e:
print("错误: 收藏夹可能未开放")
traceback.print_exc()
@staticmethod
def get_favorite(fav_id: int) -> Generator:
"""
获取收藏夹
:param fav_id: 收藏夹id
:return: 收藏夹内容
"""
pre_page = 5
cursor = 1
request = user_manager.get(
f"https://api.bilibili.com/x/v3/fav/resource/list?ps=20&media_id={fav_id}",
cache=True,
)
total = request.json()["data"]["info"]["media_count"] // pre_page + 1
while True:
ls = user_manager.get(
f"https://api.bilibili.com/x/v3/fav/resource/list?ps=5&media_id={fav_id}&pn={cursor}",
cache=True,
)
if total < cursor:
break
yield ls.json()["data"]["medias"]
cursor += 1
@staticmethod
def get_favorite_information(fav_id: int) -> dict:
"""
获取收藏夹信息
:param fav_id:
:return:
"""
request = user_manager.get(
f"https://api.bilibili.com/x/v3/fav/resource/list?ps=20&media_id={fav_id}"
)
return request.json()["data"]["info"]
@staticmethod
def export_favorite(fav_id: int):
"""
导出收藏夹
:param fav_id: 收藏夹id
:return:
"""
pre_page = 5
cursor = 1
r = user_manager.get(
"https://api.bilibili.com/x/v3/fav/resource/list?ps=20&media_id="
+ str(fav_id)
)
total = r.json()["data"]["info"]["media_count"] // pre_page + (
1 if r.json()["data"]["info"]["media_count"] % pre_page != 0 else 0
)
print(f"正在导出收藏夹\"{r.json()['data']['info']['title']}\".")
# 导出格式
export = {
"id": r.json()["data"]["info"]["id"],
"title": r.json()["data"]["info"]["title"],
"cover": r.json()["data"]["info"]["cover"].replace("http", "https"),
"media_count": r.json()["data"]["info"]["media_count"],
"view": r.json()["data"]["info"]["cnt_info"]["play"],
"user": {
"name": r.json()["data"]["info"]["upper"]["name"],
"mid": r.json()["data"]["info"]["upper"]["mid"],
"create_time": r.json()["data"]["info"]["mtime"],
},
"medias": [],
}
with tqdm(total=total, desc=r.json()["data"]["info"]["title"]) as progress_bar:
while True:
if total < cursor:
break
medias: List[dict] = user_manager.get(
f"https://api.bilibili.com/x/v3/fav/resource/list?ps=5&media_id={fav_id}&pn={cursor}"
).json()["data"]["medias"]
for i in medias:
# 清理数据
del i["type"]
del i["bv_id"]
del i["ugc"]
del i["season"]
del i["ogv"]
del i["link"]
i["publish_time"] = i["pubtime"]
del i["pubtime"]
del i["ctime"]
i["cover"] = i["cover"].replace("http", "https")
export["medias"] += medias
cursor += 1
progress_bar.update(1)
with open(f"favorite_{str(fav_id)}_{str(round(time.time()))}.json", "w", encoding="utf-8") as f:
json.dump(export, f, indent=4, ensure_ascii=False)
print(f"导出收藏夹\"{r.json()['data']['info']['title']}\"成功.")
@staticmethod
def list_favorite(mid):
ls = []
request = user_manager.get(
f"https://api.bilibili.com/x/v3/fav/folder/created/list-all?type=2&up_mid={mid}",
cache=True,
)
for i in request.json()["data"]["list"]:
ls.append(i["id"])
return ls
class BilibiliInteraction:
@staticmethod
def like(bvid: str, unlike=False):
r = user_manager.post(
"https://api.bilibili.com/x/web-interface/archive/like",
data={"bvid": bvid, "like": 2 if unlike else 1,
"csrf": user_manager.csrf},
)
if r.json()["code"] != 0:
print("点赞或取消点赞失败!")
print(f"错误信息: {r.json()['message']}")
else:
if unlike:
print("取消点赞成功!")
else:
print("点赞成功!")
@staticmethod
def coin(bvid: str, count: int):
r = user_manager.post(
"https://api.bilibili.com/x/web-interface/coin/add",
data={"bvid": bvid, "csrf": user_manager.csrf, "multiply": count},
)
if r.json()["code"] == 0:
print("投币成功!")
else:
print("投币失败!")
print(f"错误信息: {r.json()['message']}")
@staticmethod
def triple(bvid: str):
r = user_manager.post(
"https://api.bilibili.com/x/web-interface/archive/like/triple",
data={"bvid": bvid, "csrf": user_manager.csrf},
)
if r.json()["code"] == 0:
print("三联成功!")
else:
print("三联失败!")
print(f"错误信息: {r.json()['message']}")
@staticmethod
def mark_interact_video(bvid: str, score: int):
r = user_manager.post(
"https://api.bilibili.com/x/stein/mark",
data={"bvid": bvid, "csrf": user_manager.csrf, "mark": score},
)
if r.json()["code"] == 0:
print("评分成功!")
else:
print("评分失败!")
print(f"错误信息: {r.json()['message']}")
@staticmethod
def favorite(aid: int, favorite_list: list):
if not favorite_list:
print("收藏列表为空!")
return
r = user_manager.post(
"https://api.bilibili.com/x/v3/fav/resource/deal",
data={
"rid": aid,
"type": 2,
"add_media_ids": ",".join("%s" % fav_id for fav_id in favorite_list),
"csrf": user_manager.csrf,
},
)
if r.json()["code"] == 0:
print("收藏成功!")
else:
print("收藏失败!")
print(f"错误信息: {r.json()['message']}")
# type
# 1 视频稿件 稿件 aid
# 2 话题 话题 id
# 4 活动 活动 id
# 5 小视频 小视频 id
# 6 小黑屋封禁信息 封禁公示 id
# 7 公告信息 公告 id
# 8 直播活动 直播间 id
# 9 活动稿件 (?)
# 10 直播公告 (?)
# 11 相簿(图片动态) 相簿 id
# 12 专栏 专栏 cvid
# 13 票务 (?)
# 14 音频 音频 auid
# 15 风纪委员会 众裁项目 id
# 16 点评 (?)
# 17 动态(纯文字动态&分享) 动态 id
# 18 播单 (?)
# 19 音乐播单 (?)
# 20 漫画 (?)
# 21 漫画 (?)
# 22 漫画 漫画 mcid
# 33 课程 课程 epid
# sort_type
# 默认为0
# 0:按时间
# 1:按点赞数
# 2:按回复数
class BilibiliComment:
@staticmethod
def get_comment(content_type: int, content_id: int, sort_type: int = 0):
pre_page = 5
cursor = 1
request = user_manager.get(
f"https://api.bilibili.com/x/v2/reply?type={content_type}&oid={content_id}&sort={sort_type}&ps={pre_page}"
f"&pn={cursor}",
cache=True,
)
total = request.json()["data"]["page"]["count"] // pre_page + 1
while True:
ls = user_manager.get(
f"https://api.bilibili.com/x/v2/reply?type={content_type}&oid={content_id}&sort={sort_type}&ps={pre_page}"
f"&pn={cursor}",
cache=True,
)
if total < cursor:
break
yield ls.json()["data"]["replies"]
cursor += 1
@staticmethod
def like_comment():
pass
class BilibiliVideo:
def __init__(
self,
bvid: str = "",
aid: int = 0,
epid: str = "",
season_id: str = "",
quality=80,
view_online_watch=True,
audio_quality=30280,
bangumi=False,
source="backup"
):
if not any([bvid, aid, epid, season_id]):
raise Exception("Video id can't be null.")
self.bvid = bvid if bvid else av2bv(aid)
self.aid = aid if aid else bv2av(bvid)
self.epid = epid
self.season_id = season_id
self.bangumi = bangumi
self.quality = quality
self.audio_quality = audio_quality
self.view_online_watch = view_online_watch
self.author_mid = self.get_author_mid()
self.source = source
self.see_message = False
def select_video(self, return_information=False):
r = user_manager.get(
"https://api.bilibili.com/x/web-interface/view/detail?bvid=" + self.bvid,
cache=True,
)
if r.json()["code"] != 0:
print("获取视频信息错误!")
print(r.json()["code"])
print(r.json()["message"])
return
# if r.json()['data']["View"]['stat']['evaluation']:
# print("你播放的视频是一个互动视频.")
# base_cid = r.json()['data']["View"]['cid']
# self.play_interact_video(bvid, base_cid)
# return
video = r.json()["data"]["View"]["pages"]
title = r.json()["data"]["View"]["title"]
pic = r.json()["data"]["View"]["pic"]
if len(video) == 1:
if not return_information:
self.play(video[0]["cid"], title)
return
else:
return (
video[0]["cid"],
title,
video[0]["part"],
pic,
r.json()["data"]["View"]["stat"]["evaluation"],
)
print("\n")
print("视频选集")
for i in video:
print(f"{i['page']}: {i['part']}")
print("\n")
while True:
page = input("选择视频: ")
if page == "quit" or page == "q":
break
elif not page:
continue
elif not page.isdigit():
print("输入的并不是数字!")
continue
elif int(page) > len(video) or int(page) <= 0:
print("选视频超出范围!")
continue
if not return_information:
self.play(video[int(page) - 1]["cid"], self.bvid)
else:
return (
video[int(page) - 1]["cid"],
title,
video[int(page) - 1]["part"],
pic,
True if r.json()[
"data"]["View"]["stat"]["evaluation"] else False,
)
break
def get_author_mid(self):
return user_manager.get(
"https://api.bilibili.com/x/web-interface/view/detail?bvid=" + self.bvid,
cache=True,
).json()["data"]["Card"]["card"]["mid"]
def select_video_collection(self):
r = user_manager.get(
f"https://api.bilibili.com/x/web-interface/view/detail?bvid={self.bvid}", cache=True)
if r.json()["code"] != 0:
print("获取视频信息错误!")
print(r.json()["code"])
print(r.json()["message"])
return
if not r.json()["data"]["View"].get("ugc_season"):
print("视频并没有合集!")