-
Notifications
You must be signed in to change notification settings - Fork 183
/
video.py
2517 lines (2074 loc) · 82.7 KB
/
video.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
"""
bilibili_api.video
视频相关操作
注意,同时存在 page_index 和 cid 的参数,两者至少提供一个。
"""
import re
import os
import json
import struct
import asyncio
import logging
import datetime
from enum import Enum
from inspect import isfunction
from functools import cmp_to_key
from dataclasses import dataclass
from typing import Any, List, Union, Optional
import httpx
import aiohttp
from . import settings
from .utils.aid_bvid_transformer import bvid2aid, aid2bvid
from .utils.utils import get_api
from .utils.AsyncEvent import AsyncEvent
from .utils.credential import Credential
from .utils.BytesReader import BytesReader
from .utils.danmaku import Danmaku, SpecialDanmaku
from .utils.network import get_aiohttp_session, Api, get_session
from .exceptions import (
ArgsException,
NetworkException,
ResponseException,
DanmakuClosedException,
)
API = get_api("video")
def get_cid_info_sync(cid: int):
"""
获取 cid 信息 (对应的视频,具体分 P 序号,up 等)
Returns:
dict: 调用 https://hd.biliplus.com 的 API 返回的结果
"""
api = API["info"]["cid_info"]
params = {"cid": cid}
return Api(**api).update_params(**params).result_sync
async def get_cid_info(cid: int):
"""
获取 cid 信息 (对应的视频,具体分 P 序号,up 等)
Returns:
dict: 调用 https://hd.biliplus.com 的 API 返回的结果
"""
api = API["info"]["cid_info"]
params = {"cid": cid}
return await Api(**api).update_params(**params).result
class DanmakuOperatorType(Enum):
"""
弹幕操作枚举
+ DELETE - 删除弹幕
+ PROTECT - 保护弹幕
+ UNPROTECT - 取消保护弹幕
"""
DELETE = 1
PROTECT = 2
UNPROTECT = 3
class VideoAppealReasonType:
"""
视频投诉原因枚举
注意: 每一项均为函数,部分项有参数,没有参数的函数无需调用函数,直接传入即可,有参数的函数请调用结果之后传入。
- ILLEGAL(): 违法违禁
- PRON(): 色情
- VULGAR(): 低俗
- GAMBLED_SCAMS(): 赌博诈骗
- VIOLENT(): 血腥暴力
- PERSONAL_ATTACK(): 人身攻击
- PLAGIARISM(bvid: str): 与站内其他视频撞车
- BAD_FOR_YOUNGS(): 青少年不良信息
- CLICKBAIT(): 不良封面/标题
- POLITICAL_RUMORS(): 涉政谣言
- SOCIAL_RUMORS(): 涉社会事件谣言
- COVID_RUMORS(): 疫情谣言
- UNREAL_EVENT(): 虚假不实消息
- OTHER(): 有其他问题
- LEAD_WAR(): 引战
- CANNOT_CHARGE(): 不能参加充电
- UNREAL_COPYRIGHT(source: str): 转载/自制类型错误
"""
ILLEGAL = lambda: 2
PRON = lambda: 3
VULGAR = lambda: 4
GAMBLED_SCAMS = lambda: 5
VIOLENT = lambda: 6
PERSONAL_ATTACK = lambda: 7
BAD_FOR_YOUNGS = lambda: 10000
CLICKBAIT = lambda: 10013
POLITICAL_RUMORS = lambda: 10014
SOCIAL_RUMORS = lambda: 10015
COVID_RUMORS = lambda: 10016
UNREAL_EVENT = lambda: 10017
OTHER = lambda: 1
LEAD_WAR = lambda: 9
CANNOT_CHARGE = lambda: 10
@staticmethod
def PLAGIARISM(bvid: str):
"""
与站内其他视频撞车
Args:
bvid (str): 撞车对象
"""
return {"tid": 8, "撞车对象": bvid}
@staticmethod
def UNREAL_COPYRIGHT(source: str):
"""
转载/自制类型错误
Args:
source (str): 原创视频出处
"""
return {"tid": 52, "出处": source}
class Video:
"""
视频类,各种对视频的操作均在里面。
"""
def __init__(
self,
bvid: Union[None, str] = None,
aid: Union[None, int] = None,
credential: Union[None, Credential] = None,
):
"""
Args:
bvid (str | None, optional) : BV 号. bvid 和 aid 必须提供其中之一。
aid (int | None, optional) : AV 号. bvid 和 aid 必须提供其中之一。
credential (Credential | None, optional): Credential 类. Defaults to None.
"""
# ID 检查
if bvid is not None:
self.set_bvid(bvid)
elif aid is not None:
self.set_aid(aid)
else:
# 未提供任一 ID
raise ArgsException("请至少提供 bvid 和 aid 中的其中一个参数。")
# 未提供 credential 时初始化该类
self.credential: Credential = Credential() if credential is None else credential
# 用于存储视频信息,避免接口依赖视频信息时重复调用
self.__info: Union[dict, None] = None
def set_bvid(self, bvid: str) -> None:
"""
设置 bvid。
Args:
bvid (str): 要设置的 bvid。
"""
# 检查 bvid 是否有效
if not re.search("^BV[a-zA-Z0-9]{10}$", bvid):
raise ArgsException("bvid 提供错误,必须是以 BV 开头的纯字母和数字组成的 12 位字符串(大小写敏感)。")
self.__bvid = bvid
self.__aid = bvid2aid(bvid)
def get_bvid(self) -> str:
"""
获取 BVID。
Returns:
str: BVID。
"""
return self.__bvid
def set_aid(self, aid: int) -> None:
"""
设置 aid。
Args:
aid (int): AV 号。
"""
if aid <= 0:
raise ArgsException("aid 不能小于或等于 0。")
self.__aid = aid
self.__bvid = aid2bvid(aid)
def get_aid(self) -> int:
"""
获取 AID。
Returns:
int: aid。
"""
return self.__aid
async def get_info(self) -> dict:
"""
获取视频信息。
Returns:
dict: 调用 API 返回的结果。
"""
api = API["info"]["info"]
params = {"bvid": self.get_bvid(), "aid": self.get_aid()}
resp = (
await Api(**api, credential=self.credential).update_params(**params).result
)
# 存入 self.__info 中以备后续调用
self.__info = resp
return resp
async def get_detail(self) -> dict:
"""
获取视频详细信息
Returns:
dict: 调用 API 返回的结果。
"""
api = API["info"]["detail"]
params = {
"bvid": self.get_bvid(),
"aid": self.get_aid(),
"need_operation_card": 0,
"need_elec": 0,
}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def __get_info_cached(self) -> dict:
"""
获取视频信息,如果已获取过则使用之前获取的信息,没有则重新获取。
Returns:
dict: 调用 API 返回的结果。
"""
if self.__info is None:
return await self.get_info()
return self.__info
# get_stat 403/404 https://github.com/SocialSisterYi/bilibili-API-collect/issues/797 等恢复
# async def get_stat(self) -> dict:
# """
# 获取视频统计数据(播放量,点赞数等)。
# Returns:
# dict: 调用 API 返回的结果。
# """
# api = API["info"]["stat"]
# params = {"bvid": self.get_bvid(), "aid": self.get_aid()}
# return await Api(**api, credential=self.credential).update_params(**params).result
async def get_up_mid(self) -> int:
"""
获取视频 up 主的 mid。
Returns:
int: up_mid
"""
info = await self.__get_info_cached()
return info["owner"]["mid"]
async def get_tags(
self, page_index: Union[int, None] = 0, cid: Union[int, None] = None
) -> List[dict]:
"""
获取视频标签。
Args:
page_index (int | None): 分 P 序号. Defaults to 0.
cid (int | None): 分 P 编码. Defaults to None.
Returns:
List[dict]: 调用 API 返回的结果。
"""
if cid == None:
if page_index == None:
raise ArgsException("page_index 和 cid 至少提供一个。")
cid = await self.get_cid(page_index=page_index)
api = API["info"]["tags"]
params = {"bvid": self.get_bvid(), "aid": self.get_aid(), "cid": cid}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def get_chargers(self) -> dict:
"""
获取视频充电用户。
Returns:
dict: 调用 API 返回的结果。
"""
info = await self.__get_info_cached()
mid = info["owner"]["mid"]
api = API["info"]["chargers"]
params = {"aid": self.get_aid(), "bvid": self.get_bvid(), "mid": mid}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def get_pages(self) -> List[dict]:
"""
获取分 P 信息。
Returns:
dict: 调用 API 返回的结果。
"""
api = API["info"]["pages"]
params = {"aid": self.get_aid(), "bvid": self.get_bvid()}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def __get_cid_by_index(self, page_index: int) -> int:
"""
根据分 p 号获取 cid。
Args:
page_index (int): 分 P 号,从 0 开始。
Returns:
int: cid 分 P 的唯一 ID。
"""
if page_index < 0:
raise ArgsException("分 p 号必须大于或等于 0。")
info = await self.__get_info_cached()
pages = info["pages"]
if len(pages) <= page_index:
raise ArgsException("不存在该分 p。")
page = pages[page_index]
cid = page["cid"]
return cid
async def get_video_snapshot(
self,
cid: Union[int, None] = None,
json_index: bool = False,
pvideo: bool = True,
) -> dict:
"""
获取视频快照(视频各个时间段的截图拼图)
Args:
cid(int): 分 P CID(可选)
json_index(bool): json 数组截取时间表 True 为需要,False 不需要
pvideo(bool): 是否只获取预览
Returns:
dict: 调用 API 返回的结果,数据中 Url 没有 http 头
"""
params: dict[str, Any] = {"aid": self.get_aid()}
if pvideo:
api = API["info"]["video_snapshot_pvideo"]
else:
params["bvid"] = self.get_bvid()
if json_index:
params["index"] = 1
if cid:
params["cid"] = cid
api = API["info"]["video_snapshot"]
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def get_cid(self, page_index: int) -> int:
"""
获取稿件 cid
Args:
page_index(int): 分 P
Returns:
int: cid
"""
return await self.__get_cid_by_index(page_index)
async def get_download_url(
self,
page_index: Union[int, None] = None,
cid: Union[int, None] = None,
html5: bool = False,
) -> dict:
"""
获取视频下载信息。
返回结果可以传入 `VideoDownloadURLDataDetecter` 进行解析。
page_index 和 cid 至少提供其中一个,其中 cid 优先级最高
Args:
page_index (int | None, optional) : 分 P 号,从 0 开始。Defaults to None
cid (int | None, optional) : 分 P 的 ID。Defaults to None
html5 (bool, optional): 是否以 html5 平台访问,这样子能直接在网页中播放,但是链接少。
Returns:
dict: 调用 API 返回的结果。
"""
if cid is None:
if page_index is None:
raise ArgsException("page_index 和 cid 至少提供一个。")
cid = await self.__get_cid_by_index(page_index)
api = API["info"]["playurl"]
if html5:
params = {
"avid": self.get_aid(),
"cid": cid,
"qn": "127",
"otype": "json",
"fnval": 4048,
"fourk": 1,
"platform": "html5",
"high_quality": "1",
}
else:
params = {
"avid": self.get_aid(),
"cid": cid,
"qn": "127",
"otype": "json",
"fnval": 4048,
"fourk": 1,
}
result = (
await Api(**api, credential=self.credential).update_params(**params).result
)
result.update({"is_html5": True} if html5 else {})
return result
async def get_related(self) -> dict:
"""
获取相关视频信息。
Returns:
dict: 调用 API 返回的结果。
"""
api = API["info"]["related"]
params = {"aid": self.get_aid(), "bvid": self.get_bvid()}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def get_relation(self) -> dict:
"""
获取用户与视频的关系
Returns:
dict: 调用 API 返回的结果。
"""
self.credential.raise_for_no_sessdata()
api = API["info"]["relation"]
params = {"aid": self.get_aid(), "bvid": self.get_bvid()}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def has_liked(self) -> bool:
"""
视频是否点赞过。
Returns:
bool: 视频是否点赞过。
"""
self.credential.raise_for_no_sessdata()
api = API["info"]["has_liked"]
params = {"bvid": self.get_bvid(), "aid": self.get_aid()}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def get_pay_coins(self) -> int:
"""
获取视频已投币数量。
Returns:
int: 视频已投币数量。
"""
self.credential.raise_for_no_sessdata()
api = API["info"]["get_pay_coins"]
params = {"bvid": self.get_bvid(), "aid": self.get_aid()}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)["multiply"]
async def has_favoured(self) -> bool:
"""
是否已收藏。
Returns:
bool: 视频是否已收藏。
"""
self.credential.raise_for_no_sessdata()
api = API["info"]["has_favoured"]
params = {"bvid": self.get_bvid(), "aid": self.get_aid()}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)["favoured"]
async def is_forbid_note(self) -> bool:
"""
是否禁止笔记。
Returns:
bool: 是否禁止笔记。
"""
api = API["info"]["is_forbid"]
params = {"aid": self.get_aid()}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)["forbid_note_entrance"]
async def get_private_notes_list(self) -> list:
"""
获取稿件私有笔记列表。
Returns:
list: note_Ids。
"""
self.credential.raise_for_no_sessdata()
api = API["info"]["private_notes"]
params = {"oid": self.get_aid(), "oid_type": 0}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)["noteIds"]
async def get_public_notes_list(self, pn: int, ps: int) -> dict:
"""
获取稿件公开笔记列表。
Args:
pn (int): 页码
ps (int): 每页项数
Returns:
dict: 调用 API 返回的结果。
"""
api = API["info"]["public_notes"]
params = {"oid": self.get_aid(), "oid_type": 0, "pn": pn, "ps": ps}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def get_ai_conclusion(self, cid: Optional[int] = None, page_index: Optional[int] = None,
up_mid: Optional[int] = None) -> dict:
"""
获取稿件 AI 总结结果。
cid 和 page_index 至少提供其中一个,其中 cid 优先级最高
Args:
cid (Optional, int): 分 P 的 cid。
page_index (Optional, int): 分 P 号,从 0 开始。
up_mid (Optional, int): up 主的 mid。
Returns:
dict: 调用 API 返回的结果。
"""
if cid is None:
if page_index is None:
raise ArgsException("page_index 和 cid 至少提供一个。")
cid = await self.__get_cid_by_index(page_index)
api = API["info"]["ai_conclusion"]
params = {"aid": self.get_aid(), "bvid": self.get_bvid(), "cid": cid,
"up_mid": await self.get_up_mid() if up_mid is None else up_mid}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
async def get_danmaku_view(
self, page_index: Union[int, None] = None, cid: Union[int, None] = None
) -> dict:
"""
获取弹幕设置、特殊弹幕、弹幕数量、弹幕分段等信息。
Args:
page_index (int, optional): 分 P 号,从 0 开始。Defaults to None
cid (int, optional): 分 P 的 ID。Defaults to None
Returns:
dict: 调用 API 返回的结果。
"""
if cid is None:
if page_index is None:
raise ArgsException("page_index 和 cid 至少提供一个。")
cid = await self.__get_cid_by_index(page_index)
session = get_session()
api = API["danmaku"]["view"]
config = {}
config["url"] = api["url"]
config["params"] = {"type": 1, "oid": cid, "pid": self.get_aid()}
config["cookies"] = self.credential.get_cookies()
config["headers"] = {
"Referer": "https://www.bilibili.com",
"User-Agent": "Mozilla/5.0",
}
try:
resp = await session.get(**config)
except Exception as e:
raise NetworkException(-1, str(e))
resp_data = resp.read()
json_data = {}
reader = BytesReader(resp_data)
# 解析二进制数据流
def read_dm_seg(stream: bytes):
reader_ = BytesReader(stream)
data = {}
while not reader_.has_end():
t = reader_.varint() >> 3
if t == 1:
data["page_size"] = reader_.varint()
elif t == 2:
data["total"] = reader_.varint()
else:
continue
return data
def read_flag(stream: bytes):
reader_ = BytesReader(stream)
data = {}
while not reader_.has_end():
t = reader_.varint() >> 3
if t == 1:
data["rec_flag"] = reader_.varint()
elif t == 2:
data["rec_text"] = reader_.string()
elif t == 3:
data["rec_switch"] = reader_.varint()
else:
continue
return data
def read_command_danmakus(stream: bytes):
reader_ = BytesReader(stream)
data = {}
while not reader_.has_end():
t = reader_.varint() >> 3
if t == 1:
data["id"] = reader_.varint()
elif t == 2:
data["oid"] = reader_.varint()
elif t == 3:
data["mid"] = reader_.varint()
elif t == 4:
data["commend"] = reader_.string()
elif t == 5:
data["content"] = reader_.string()
elif t == 6:
data["progress"] = reader_.varint()
elif t == 7:
data["ctime"] = reader_.string()
elif t == 8:
data["mtime"] = reader_.string()
elif t == 9:
data["extra"] = json.loads(reader_.string())
elif t == 10:
data["id_str"] = reader_.string()
else:
continue
return data
def read_settings(stream: bytes):
reader_ = BytesReader(stream)
data = {}
while not reader_.has_end():
t = reader_.varint() >> 3
if t == 1:
data["dm_switch"] = reader_.bool()
elif t == 2:
data["ai_switch"] = reader_.bool()
elif t == 3:
data["ai_level"] = reader_.varint()
elif t == 4:
data["enable_top"] = reader_.bool()
elif t == 5:
data["enable_scroll"] = reader_.bool()
elif t == 6:
data["enable_bottom"] = reader_.bool()
elif t == 7:
data["enable_color"] = reader_.bool()
elif t == 8:
data["enable_special"] = reader_.bool()
elif t == 9:
data["prevent_shade"] = reader_.bool()
elif t == 10:
data["dmask"] = reader_.bool()
elif t == 11:
data["opacity"] = reader_.float(True)
elif t == 12:
data["dm_area"] = reader_.varint()
elif t == 13:
data["speed_plus"] = reader_.float(True)
elif t == 14:
data["font_size"] = reader_.float(True)
elif t == 15:
data["screen_sync"] = reader_.bool()
elif t == 16:
data["speed_sync"] = reader_.bool()
elif t == 17:
data["font_family"] = reader_.string()
elif t == 18:
data["bold"] = reader_.bool()
elif t == 19:
data["font_border"] = reader_.varint()
elif t == 20:
data["draw_type"] = reader_.string()
else:
continue
return data
def read_image_danmakus(string: bytes):
image_list = []
reader_ = BytesReader(string)
while not reader_.has_end():
type_ = reader_.varint() >> 3
if type_ == 1:
details_dict: dict[Any, Any] = {"texts": []}
img_details = reader_.bytes_string()
reader_details = BytesReader(img_details)
while not reader_details.has_end():
type_details = reader_details.varint() >> 3
if type_details == 1:
details_dict["texts"].append(reader_details.string())
elif type_details == 2:
details_dict["image"] = reader_details.string()
elif type_details == 3:
id_string = reader_details.bytes_string()
id_reader = BytesReader(id_string)
while not id_reader.has_end():
type_id = id_reader.varint() >> 3
if type_id == 2:
details_dict["id"] = id_reader.varint()
else:
raise ResponseException("解析响应数据错误")
image_list.append(details_dict)
else:
raise ResponseException("解析响应数据错误")
return image_list
while not reader.has_end():
type_ = reader.varint() >> 3
if type_ == 1:
json_data["state"] = reader.varint()
elif type_ == 2:
json_data["text"] = reader.string()
elif type_ == 3:
json_data["text_side"] = reader.string()
elif type_ == 4:
json_data["dm_seg"] = read_dm_seg(reader.bytes_string())
elif type_ == 5:
json_data["flag"] = read_flag(reader.bytes_string())
elif type_ == 6:
if "special_dms" not in json_data:
json_data["special_dms"] = []
json_data["special_dms"].append(reader.string())
elif type_ == 7:
json_data["check_box"] = reader.bool()
elif type_ == 8:
json_data["count"] = reader.varint()
elif type_ == 9:
if "command_dms" not in json_data:
json_data["command_dms"] = []
json_data["command_dms"].append(
read_command_danmakus(reader.bytes_string())
)
elif type_ == 10:
json_data["dm_setting"] = read_settings(reader.bytes_string())
elif type_ == 12:
json_data["image_dms"] = read_image_danmakus(reader.bytes_string())
else:
continue
return json_data
async def get_danmakus(
self,
page_index: int = 0,
date: Union[datetime.date, None] = None,
cid: Union[int, None] = None,
from_seg: Union[int, None] = None,
to_seg: Union[int, None] = None,
) -> List[Danmaku]:
"""
获取弹幕。
Args:
page_index (int, optional): 分 P 号,从 0 开始。Defaults to None
date (datetime.Date | None, optional): 指定日期后为获取历史弹幕,精确到年月日。Defaults to None.
cid (int | None, optional): 分 P 的 ID。Defaults to None
from_seg (int, optional): 从第几段开始(0 开始编号,None 为从第一段开始,一段 6 分钟). Defaults to None.
to_seg (int, optional): 到第几段结束(0 开始编号,None 为到最后一段,包含编号的段,一段 6 分钟). Defaults to None.
注意:
- 1. 段数可以使用 `get_danmaku_view()["dm_seg"]["total"]` 查询。
- 2. `from_seg` 和 `to_seg` 仅对 `date == None` 的时候有效果。
- 3. 例:取前 `12` 分钟的弹幕:`from_seg=0, to_seg=1`
Returns:
List[Danmaku]: Danmaku 类的列表。
"""
if date is not None:
self.credential.raise_for_no_sessdata()
if cid is None:
if page_index is None:
raise ArgsException("page_index 和 cid 至少提供一个。")
cid = await self.__get_cid_by_index(page_index)
session = get_session()
aid = self.get_aid()
params: dict[str, Any] = {"oid": cid, "type": 1, "pid": aid}
if date is not None:
# 获取历史弹幕
api = API["danmaku"]["get_history_danmaku"]
params["date"] = date.strftime("%Y-%m-%d")
params["type"] = 1
from_seg = to_seg = 0
else:
api = API["danmaku"]["get_danmaku"]
if from_seg == None:
from_seg = 0
if to_seg == None:
view = await self.get_danmaku_view(cid=cid)
to_seg = view["dm_seg"]["total"] - 1
danmakus = []
for seg in range(from_seg, to_seg + 1):
if date is None:
# 仅当获取当前弹幕时需要该参数
params["segment_index"] = seg + 1
config = {}
config["url"] = api["url"]
config["params"] = params
config["headers"] = {
"Referer": "https://www.bilibili.com",
"User-Agent": "Mozilla/5.0",
}
config["cookies"] = self.credential.get_cookies()
try:
req = await session.get(**config)
except Exception as e:
raise NetworkException(-1, str(e))
if "content-type" not in req.headers.keys():
break
else:
content_type = req.headers["content-type"]
if content_type != "application/octet-stream":
raise ResponseException("返回数据类型错误:")
# 解析二进制流数据
data = req.read()
if data == b"\x10\x01":
# 视频弹幕被关闭
raise DanmakuClosedException()
reader = BytesReader(data)
while not reader.has_end():
type_ = reader.varint() >> 3
if type_ != 1:
if type_ == 4:
reader.bytes_string()
# 什么鬼?我用 protoc 解析出乱码!
elif type_ == 5:
# 大会员专属颜色
reader.varint()
reader.varint()
reader.varint()
reader.bytes_string()
elif type_ == 13:
# ???
continue
else:
raise ResponseException("解析响应数据错误")
dm = Danmaku("")
dm_pack_data = reader.bytes_string()
dm_reader = BytesReader(dm_pack_data)
while not dm_reader.has_end():
data_type = dm_reader.varint() >> 3
if data_type == 1:
dm.id_ = dm_reader.varint()
elif data_type == 2:
dm.dm_time = dm_reader.varint() / 1000
elif data_type == 3:
dm.mode = dm_reader.varint()
elif data_type == 4:
dm.font_size = dm_reader.varint()
elif data_type == 5:
color = dm_reader.varint()
if color != 60001:
color = hex(color)[2:]
else:
color = "special"
dm.color = color
elif data_type == 6:
dm.crc32_id = dm_reader.string()
elif data_type == 7:
dm.text = dm_reader.string()
elif data_type == 8:
dm.send_time = dm_reader.varint()
elif data_type == 9:
dm.weight = dm_reader.varint()
elif data_type == 10:
dm.action = str(dm_reader.string())
elif data_type == 11:
dm.pool = dm_reader.varint()
elif data_type == 12:
dm.id_str = dm_reader.string()
elif data_type == 13:
dm.attr = dm_reader.varint()
elif data_type == 14:
dm.uid = dm_reader.varint()
elif data_type == 15:
dm_reader.varint()
elif data_type == 20:
dm_reader.bytes_string()
elif data_type == 21:
dm_reader.bytes_string()
elif data_type == 22:
dm_reader.bytes_string()
elif data_type == 25:
dm_reader.varint()
elif data_type == 26:
dm_reader.varint()
else:
break
danmakus.append(dm)
return danmakus
async def get_special_dms(
self, page_index: int = 0, cid: Union[int, None] = None
) -> List[SpecialDanmaku]:
"""
获取特殊弹幕