-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathbilibili.py
More file actions
224 lines (205 loc) · 8.26 KB
/
Copy pathbilibili.py
File metadata and controls
224 lines (205 loc) · 8.26 KB
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
"""
$description Chinese video sharing website based in Shanghai, themed around animation, comics, and games (ACG).
$url live.bilibili.com
$type live
"""
import re
from streamlink.exceptions import NoStreamsError
from streamlink.logger import getLogger
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream
from streamlink.stream.http import HTTPStream
log = getLogger(__name__)
@pluginmatcher(
re.compile(r"https?://live\.bilibili\.com/(?P<channel>[^/?#]+)"),
)
class Bilibili(Plugin):
_URL_API_V1_PLAYURL = "https://api.live.bilibili.com/room/v1/Room/playUrl"
_URL_API_V2_PLAYINFO = "https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo"
SHOW_STATUS_OFFLINE = 0
SHOW_STATUS_ONLINE = 1
SHOW_STATUS_ROUND = 2
@classmethod
def stream_weight(cls, stream: str) -> tuple[float, str]:
offset = 1 if "_alt" in stream else 0
if stream.startswith("httpstream"):
return 4 - offset, stream
if stream.startswith("hls"):
return 2 - offset, stream
return super().stream_weight(stream)
def _get_api_v1_playurl(self, room_id):
return self.session.http.get(
self._URL_API_V1_PLAYURL,
params={
"cid": room_id,
"platform": "web",
"quality": "4",
},
schema=validate.Schema(
validate.parse_json(),
validate.any(
validate.all(
{
"code": 0,
"data": {
"durl": [
validate.all(
{
"url": validate.url(),
},
validate.get("url"),
),
],
},
},
validate.get(("data", "durl")),
),
validate.all(
{
"code": int,
},
validate.transform(lambda _: []),
),
),
),
)
@property
def _schema_v2_streams(self):
return validate.all(
[
{
"protocol_name": str,
"format": validate.all(
[
{
"format_name": str,
"codec": validate.all(
[
{
"codec_name": str,
"base_url": str,
"url_info": [
{
"host": validate.url(),
"extra": str,
},
],
},
],
validate.filter(lambda item: item["codec_name"] == "avc"),
),
},
],
validate.filter(lambda item: item["format_name"] in ("fmp4", "ts")),
),
},
],
validate.filter(lambda item: item["protocol_name"] == "http_hls"),
)
def _get_api_v2_playinfo(self, room_id):
return self.session.http.get(
self._URL_API_V2_PLAYINFO,
params={
"room_id": room_id,
"no_playurl": 0,
"mask": 1,
"qn": 0,
"platform": "web",
"protocol": "0,1",
"format": "0,1,2",
"codec": "0,1,2",
"dolby": 5,
"panorama": 1,
},
schema=validate.Schema(
validate.parse_json(),
{
"code": 0,
"data": {
"playurl_info": validate.none_or_all(
{
"playurl": {
"stream": self._schema_v2_streams,
},
},
validate.get(("playurl", "stream")),
),
},
},
validate.get(("data", "playurl_info")),
),
)
def _get_page_playinfo(self):
data = self.session.http.get(
self.url,
schema=validate.Schema(
validate.parse_html(),
validate.xml_xpath_string(".//script[contains(text(),'window.__NEPTUNE_IS_MY_WAIFU__={')][1]/text()"),
validate.none_or_all(
validate.transform(str.replace, "window.__NEPTUNE_IS_MY_WAIFU__=", ""),
validate.parse_json(),
{
"roomInitRes": {
"data": {
"live_status": int,
"playurl_info": validate.none_or_all(
{
"playurl": {
"stream": self._schema_v2_streams,
},
},
validate.get(("playurl", "stream")),
),
},
},
"roomInfoRes": {
"data": {
"room_info": {
"live_id": int,
"title": str,
"area_name": str,
},
"anchor_info": {
"base_info": {
"uname": str,
},
},
},
},
},
validate.union_get(
("roomInfoRes", "data", "room_info", "live_id"),
("roomInfoRes", "data", "anchor_info", "base_info", "uname"),
("roomInfoRes", "data", "room_info", "area_name"),
("roomInfoRes", "data", "room_info", "title"),
("roomInitRes", "data", "live_status"),
("roomInitRes", "data", "playurl_info"),
),
),
),
)
if not data:
return
self.id, self.author, self.category, self.title, live_status, streams = data
if live_status != self.SHOW_STATUS_ONLINE:
log.info("Channel is offline")
raise NoStreamsError
return streams
def _get_streams(self):
http_streams = self._get_api_v1_playurl(self.match["channel"])
for http_stream in http_streams:
if self.session.http.head(http_stream, raise_for_status=False).status_code >= 400:
continue
yield "httpstream", HTTPStream(self.session, http_stream)
hls_streams = self._get_page_playinfo()
if not hls_streams:
log.debug("Falling back to _get_api_v2_playinfo()")
hls_streams = self._get_api_v2_playinfo(self.match["channel"])
for hls_stream in hls_streams or []:
for stream_format in hls_stream["format"]:
for codec in stream_format["codec"]:
for url_info in codec["url_info"]:
url = f"{url_info['host']}{codec['base_url']}{url_info['extra']}"
yield "hls", HLSStream(self.session, url)
__plugin__ = Bilibili