]>
Commit | Line | Data |
---|---|---|
1 | import base64 | |
2 | import hashlib | |
3 | import itertools | |
4 | import functools | |
5 | import re | |
6 | import math | |
7 | ||
8 | from .common import InfoExtractor, SearchInfoExtractor | |
9 | from ..compat import ( | |
10 | compat_parse_qs, | |
11 | compat_urlparse, | |
12 | compat_urllib_parse_urlparse | |
13 | ) | |
14 | from ..utils import ( | |
15 | ExtractorError, | |
16 | filter_dict, | |
17 | int_or_none, | |
18 | float_or_none, | |
19 | mimetype2ext, | |
20 | parse_iso8601, | |
21 | qualities, | |
22 | traverse_obj, | |
23 | parse_count, | |
24 | smuggle_url, | |
25 | srt_subtitles_timecode, | |
26 | str_or_none, | |
27 | strip_jsonp, | |
28 | unified_timestamp, | |
29 | unsmuggle_url, | |
30 | urlencode_postdata, | |
31 | url_or_none, | |
32 | OnDemandPagedList | |
33 | ) | |
34 | ||
35 | ||
36 | class BiliBiliIE(InfoExtractor): | |
37 | _VALID_URL = r'''(?x) | |
38 | https?:// | |
39 | (?:(?:www|bangumi)\.)? | |
40 | bilibili\.(?:tv|com)/ | |
41 | (?: | |
42 | (?: | |
43 | video/[aA][vV]| | |
44 | anime/(?P<anime_id>\d+)/play\# | |
45 | )(?P<id>\d+)| | |
46 | (s/)?video/[bB][vV](?P<id_bv>[^/?#&]+) | |
47 | ) | |
48 | (?:/?\?p=(?P<page>\d+))? | |
49 | ''' | |
50 | ||
51 | _TESTS = [{ | |
52 | 'url': 'http://www.bilibili.com/video/av1074402/', | |
53 | 'md5': '7ac275ec84a99a6552c5d229659a0fe1', | |
54 | 'info_dict': { | |
55 | 'id': '1074402_part1', | |
56 | 'ext': 'mp4', | |
57 | 'title': '【金坷垃】金泡沫', | |
58 | 'uploader_id': '156160', | |
59 | 'uploader': '菊子桑', | |
60 | 'upload_date': '20140420', | |
61 | 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923', | |
62 | 'timestamp': 1398012678, | |
63 | 'tags': ['顶上去报复社会', '该来的总会来的', '金克拉是检验歌曲的唯一标准', '坷垃教主', '金坷垃', '邓紫棋', '治愈系坷垃'], | |
64 | 'bv_id': 'BV11x411K7CN', | |
65 | 'cid': '1554319', | |
66 | 'thumbnail': 'http://i2.hdslb.com/bfs/archive/c79a8cf0347cd7a897c53a2f756e96aead128e8c.jpg', | |
67 | 'duration': 308.36, | |
68 | }, | |
69 | }, { | |
70 | # Tested in BiliBiliBangumiIE | |
71 | 'url': 'http://bangumi.bilibili.com/anime/1869/play#40062', | |
72 | 'only_matching': True, | |
73 | }, { | |
74 | # bilibili.tv | |
75 | 'url': 'http://www.bilibili.tv/video/av1074402/', | |
76 | 'only_matching': True, | |
77 | }, { | |
78 | 'url': 'http://bangumi.bilibili.com/anime/5802/play#100643', | |
79 | 'md5': '3f721ad1e75030cc06faf73587cfec57', | |
80 | 'info_dict': { | |
81 | 'id': '100643_part1', | |
82 | 'ext': 'mp4', | |
83 | 'title': 'CHAOS;CHILD', | |
84 | 'description': '如果你是神明,并且能够让妄想成为现实。那你会进行怎么样的妄想?是淫靡的世界?独裁社会?毁灭性的制裁?还是……2015年,涩谷。从6年前发生的大灾害“涩谷地震”之后复兴了的这个街区里新设立的私立高中...', | |
85 | }, | |
86 | 'skip': 'Geo-restricted to China', | |
87 | }, { | |
88 | 'url': 'http://www.bilibili.com/video/av8903802/', | |
89 | 'info_dict': { | |
90 | 'id': '8903802_part1', | |
91 | 'ext': 'mp4', | |
92 | 'title': '阿滴英文|英文歌分享#6 "Closer', | |
93 | 'upload_date': '20170301', | |
94 | 'description': '滴妹今天唱Closer給你聽! 有史以来,被推最多次也是最久的歌曲,其实歌词跟我原本想像差蛮多的,不过还是好听! 微博@阿滴英文', | |
95 | 'timestamp': 1488382634, | |
96 | 'uploader_id': '65880958', | |
97 | 'uploader': '阿滴英文', | |
98 | 'thumbnail': 'http://i2.hdslb.com/bfs/archive/49267ce20bc246be6304bf369a3ded0256854c23.jpg', | |
99 | 'cid': '14694589', | |
100 | 'duration': 554.117, | |
101 | 'bv_id': 'BV13x41117TL', | |
102 | 'tags': ['人文', '英语', '文化', '公开课', '阿滴英文'], | |
103 | }, | |
104 | 'params': { | |
105 | 'skip_download': True, | |
106 | }, | |
107 | }, { | |
108 | # new BV video id format | |
109 | 'url': 'https://www.bilibili.com/video/BV1JE411F741', | |
110 | 'only_matching': True, | |
111 | }, { | |
112 | # Anthology | |
113 | 'url': 'https://www.bilibili.com/video/BV1bK411W797', | |
114 | 'info_dict': { | |
115 | 'id': 'BV1bK411W797', | |
116 | 'title': '物语中的人物是如何吐槽自己的OP的' | |
117 | }, | |
118 | 'playlist_count': 17, | |
119 | }, { | |
120 | # Correct matching of single and double quotes in title | |
121 | 'url': 'https://www.bilibili.com/video/BV1NY411E7Rx/', | |
122 | 'info_dict': { | |
123 | 'id': '255513412_part1', | |
124 | 'ext': 'mp4', | |
125 | 'title': 'Vid"eo" Te\'st', | |
126 | 'cid': '570602418', | |
127 | 'thumbnail': 'http://i2.hdslb.com/bfs/archive/0c0de5a90b6d5b991b8dcc6cde0afbf71d564791.jpg', | |
128 | 'upload_date': '20220408', | |
129 | 'timestamp': 1649436552, | |
130 | 'description': 'Vid"eo" Te\'st', | |
131 | 'uploader_id': '1630758804', | |
132 | 'bv_id': 'BV1NY411E7Rx', | |
133 | 'duration': 60.394, | |
134 | 'uploader': 'bili_31244483705', | |
135 | 'tags': ['VLOG'], | |
136 | }, | |
137 | 'params': { | |
138 | 'skip_download': True, | |
139 | }, | |
140 | }] | |
141 | ||
142 | _APP_KEY = 'iVGUTjsxvpLeuDCf' | |
143 | _BILIBILI_KEY = 'aHRmhWMLkdeMuILqORnYZocwMBpMEOdt' | |
144 | ||
145 | def _report_error(self, result): | |
146 | if 'message' in result: | |
147 | raise ExtractorError('%s said: %s' % (self.IE_NAME, result['message']), expected=True) | |
148 | elif 'code' in result: | |
149 | raise ExtractorError('%s returns error %d' % (self.IE_NAME, result['code']), expected=True) | |
150 | else: | |
151 | raise ExtractorError('Can\'t extract Bangumi episode ID') | |
152 | ||
153 | def _real_extract(self, url): | |
154 | url, smuggled_data = unsmuggle_url(url, {}) | |
155 | ||
156 | mobj = self._match_valid_url(url) | |
157 | video_id = mobj.group('id_bv') or mobj.group('id') | |
158 | ||
159 | av_id, bv_id = self._get_video_id_set(video_id, mobj.group('id_bv') is not None) | |
160 | video_id = av_id | |
161 | ||
162 | info = {} | |
163 | anime_id = mobj.group('anime_id') | |
164 | page_id = mobj.group('page') | |
165 | webpage = self._download_webpage(url, video_id) | |
166 | ||
167 | # Bilibili anthologies are similar to playlists but all videos share the same video ID as the anthology itself. | |
168 | # If the video has no page argument, check to see if it's an anthology | |
169 | if page_id is None: | |
170 | if not self.get_param('noplaylist'): | |
171 | r = self._extract_anthology_entries(bv_id, video_id, webpage) | |
172 | if r is not None: | |
173 | self.to_screen('Downloading anthology %s - add --no-playlist to just download video' % video_id) | |
174 | return r | |
175 | else: | |
176 | self.to_screen('Downloading just video %s because of --no-playlist' % video_id) | |
177 | ||
178 | if 'anime/' not in url: | |
179 | cid = self._search_regex( | |
180 | r'\bcid(?:["\']:|=)(\d+),["\']page(?:["\']:|=)' + str(page_id), webpage, 'cid', | |
181 | default=None | |
182 | ) or self._search_regex( | |
183 | r'\bcid(?:["\']:|=)(\d+)', webpage, 'cid', | |
184 | default=None | |
185 | ) or compat_parse_qs(self._search_regex( | |
186 | [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)', | |
187 | r'EmbedPlayer\([^)]+,\s*\\"([^"]+)\\"\)', | |
188 | r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'], | |
189 | webpage, 'player parameters'))['cid'][0] | |
190 | else: | |
191 | if 'no_bangumi_tip' not in smuggled_data: | |
192 | self.to_screen('Downloading episode %s. To download all videos in anime %s, re-run yt-dlp with %s' % ( | |
193 | video_id, anime_id, compat_urlparse.urljoin(url, '//bangumi.bilibili.com/anime/%s' % anime_id))) | |
194 | headers = { | |
195 | 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', | |
196 | 'Referer': url | |
197 | } | |
198 | headers.update(self.geo_verification_headers()) | |
199 | ||
200 | js = self._download_json( | |
201 | 'http://bangumi.bilibili.com/web_api/get_source', video_id, | |
202 | data=urlencode_postdata({'episode_id': video_id}), | |
203 | headers=headers) | |
204 | if 'result' not in js: | |
205 | self._report_error(js) | |
206 | cid = js['result']['cid'] | |
207 | ||
208 | headers = { | |
209 | 'Accept': 'application/json', | |
210 | 'Referer': url | |
211 | } | |
212 | headers.update(self.geo_verification_headers()) | |
213 | ||
214 | video_info = self._parse_json( | |
215 | self._search_regex(r'window.__playinfo__\s*=\s*({.+?})</script>', webpage, 'video info', default=None) or '{}', | |
216 | video_id, fatal=False) | |
217 | video_info = video_info.get('data') or {} | |
218 | ||
219 | durl = traverse_obj(video_info, ('dash', 'video')) | |
220 | audios = traverse_obj(video_info, ('dash', 'audio')) or [] | |
221 | entries = [] | |
222 | ||
223 | RENDITIONS = ('qn=80&quality=80&type=', 'quality=2&type=mp4') | |
224 | for num, rendition in enumerate(RENDITIONS, start=1): | |
225 | payload = 'appkey=%s&cid=%s&otype=json&%s' % (self._APP_KEY, cid, rendition) | |
226 | sign = hashlib.md5((payload + self._BILIBILI_KEY).encode('utf-8')).hexdigest() | |
227 | if not video_info: | |
228 | video_info = self._download_json( | |
229 | 'http://interface.bilibili.com/v2/playurl?%s&sign=%s' % (payload, sign), | |
230 | video_id, note='Downloading video info page', | |
231 | headers=headers, fatal=num == len(RENDITIONS)) | |
232 | if not video_info: | |
233 | continue | |
234 | ||
235 | if not durl and 'durl' not in video_info: | |
236 | if num < len(RENDITIONS): | |
237 | continue | |
238 | self._report_error(video_info) | |
239 | ||
240 | formats = [] | |
241 | for idx, durl in enumerate(durl or video_info['durl']): | |
242 | formats.append({ | |
243 | 'url': durl.get('baseUrl') or durl.get('base_url') or durl.get('url'), | |
244 | 'ext': mimetype2ext(durl.get('mimeType') or durl.get('mime_type')), | |
245 | 'fps': int_or_none(durl.get('frameRate') or durl.get('frame_rate')), | |
246 | 'width': int_or_none(durl.get('width')), | |
247 | 'height': int_or_none(durl.get('height')), | |
248 | 'vcodec': durl.get('codecs'), | |
249 | 'acodec': 'none' if audios else None, | |
250 | 'tbr': float_or_none(durl.get('bandwidth'), scale=1000), | |
251 | 'filesize': int_or_none(durl.get('size')), | |
252 | }) | |
253 | for backup_url in traverse_obj(durl, 'backup_url', expected_type=list) or []: | |
254 | formats.append({ | |
255 | 'url': backup_url, | |
256 | 'quality': -2 if 'hd.mp4' in backup_url else -3, | |
257 | }) | |
258 | ||
259 | for audio in audios: | |
260 | formats.append({ | |
261 | 'url': audio.get('baseUrl') or audio.get('base_url') or audio.get('url'), | |
262 | 'ext': mimetype2ext(audio.get('mimeType') or audio.get('mime_type')), | |
263 | 'fps': int_or_none(audio.get('frameRate') or audio.get('frame_rate')), | |
264 | 'width': int_or_none(audio.get('width')), | |
265 | 'height': int_or_none(audio.get('height')), | |
266 | 'acodec': audio.get('codecs'), | |
267 | 'vcodec': 'none', | |
268 | 'tbr': float_or_none(audio.get('bandwidth'), scale=1000), | |
269 | 'filesize': int_or_none(audio.get('size')) | |
270 | }) | |
271 | for backup_url in traverse_obj(audio, 'backup_url', expected_type=list) or []: | |
272 | formats.append({ | |
273 | 'url': backup_url, | |
274 | # backup URLs have lower priorities | |
275 | 'quality': -3, | |
276 | }) | |
277 | ||
278 | info.update({ | |
279 | 'id': video_id, | |
280 | 'duration': float_or_none(durl.get('length'), 1000), | |
281 | 'formats': formats, | |
282 | 'http_headers': { | |
283 | 'Referer': url, | |
284 | }, | |
285 | }) | |
286 | break | |
287 | ||
288 | self._sort_formats(formats) | |
289 | ||
290 | title = self._html_search_regex(( | |
291 | r'<h1[^>]+title=(["])(?P<content>[^"]+)', | |
292 | r'<h1[^>]+title=([\'])(?P<content>[^\']+)', | |
293 | r'(?s)<h1[^>]*>(?P<content>.+?)</h1>', | |
294 | self._meta_regex('title') | |
295 | ), webpage, 'title', group='content', fatal=False) | |
296 | ||
297 | # Get part title for anthologies | |
298 | if page_id is not None: | |
299 | # TODO: The json is already downloaded by _extract_anthology_entries. Don't redownload for each video. | |
300 | part_info = traverse_obj(self._download_json( | |
301 | f'https://api.bilibili.com/x/player/pagelist?bvid={bv_id}&jsonp=jsonp', | |
302 | video_id, note='Extracting videos in anthology'), 'data', expected_type=list) | |
303 | title = title if len(part_info) == 1 else traverse_obj(part_info, (int(page_id) - 1, 'part')) or title | |
304 | ||
305 | description = self._html_search_meta('description', webpage) | |
306 | timestamp = unified_timestamp(self._html_search_regex( | |
307 | r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time', | |
308 | default=None) or self._html_search_meta( | |
309 | 'uploadDate', webpage, 'timestamp', default=None)) | |
310 | thumbnail = self._html_search_meta(['og:image', 'thumbnailUrl'], webpage) | |
311 | ||
312 | # TODO 'view_count' requires deobfuscating Javascript | |
313 | info.update({ | |
314 | 'id': f'{video_id}_part{page_id or 1}', | |
315 | 'cid': cid, | |
316 | 'title': title, | |
317 | 'description': description, | |
318 | 'timestamp': timestamp, | |
319 | 'thumbnail': thumbnail, | |
320 | 'duration': float_or_none(video_info.get('timelength'), scale=1000), | |
321 | }) | |
322 | ||
323 | uploader_mobj = re.search( | |
324 | r'<a[^>]+href="(?:https?:)?//space\.bilibili\.com/(?P<id>\d+)"[^>]*>\s*(?P<name>[^<]+?)\s*<', | |
325 | webpage) | |
326 | if uploader_mobj: | |
327 | info.update({ | |
328 | 'uploader': uploader_mobj.group('name').strip(), | |
329 | 'uploader_id': uploader_mobj.group('id'), | |
330 | }) | |
331 | ||
332 | if not info.get('uploader'): | |
333 | info['uploader'] = self._html_search_meta( | |
334 | 'author', webpage, 'uploader', default=None) | |
335 | ||
336 | top_level_info = { | |
337 | 'tags': traverse_obj(self._download_json( | |
338 | f'https://api.bilibili.com/x/tag/archive/tags?aid={video_id}', | |
339 | video_id, fatal=False, note='Downloading tags'), ('data', ..., 'tag_name')), | |
340 | } | |
341 | ||
342 | info['subtitles'] = { | |
343 | 'danmaku': [{ | |
344 | 'ext': 'xml', | |
345 | 'url': f'https://comment.bilibili.com/{cid}.xml', | |
346 | }] | |
347 | } | |
348 | ||
349 | r''' | |
350 | # Requires https://github.com/m13253/danmaku2ass which is licenced under GPL3 | |
351 | # See https://github.com/animelover1984/youtube-dl | |
352 | ||
353 | raw_danmaku = self._download_webpage( | |
354 | f'https://comment.bilibili.com/{cid}.xml', video_id, fatal=False, note='Downloading danmaku comments') | |
355 | danmaku = NiconicoIE.CreateDanmaku(raw_danmaku, commentType='Bilibili', x=1024, y=576) | |
356 | entries[0]['subtitles'] = { | |
357 | 'danmaku': [{ | |
358 | 'ext': 'ass', | |
359 | 'data': danmaku | |
360 | }] | |
361 | } | |
362 | ''' | |
363 | ||
364 | top_level_info['__post_extractor'] = self.extract_comments(video_id) | |
365 | ||
366 | for entry in entries: | |
367 | entry.update(info) | |
368 | ||
369 | if len(entries) == 1: | |
370 | entries[0].update(top_level_info) | |
371 | return entries[0] | |
372 | ||
373 | for idx, entry in enumerate(entries): | |
374 | entry['id'] = '%s_part%d' % (video_id, (idx + 1)) | |
375 | ||
376 | return { | |
377 | 'id': str(video_id), | |
378 | 'bv_id': bv_id, | |
379 | 'title': title, | |
380 | 'description': description, | |
381 | **info, **top_level_info | |
382 | } | |
383 | ||
384 | def _extract_anthology_entries(self, bv_id, video_id, webpage): | |
385 | title = self._html_search_regex( | |
386 | (r'<h1[^>]+\btitle=(["\'])(?P<title>(?:(?!\1).)+)\1', | |
387 | r'(?s)<h1[^>]*>(?P<title>.+?)</h1>', | |
388 | r'<title>(?P<title>.+?)</title>'), webpage, 'title', | |
389 | group='title') | |
390 | json_data = self._download_json( | |
391 | f'https://api.bilibili.com/x/player/pagelist?bvid={bv_id}&jsonp=jsonp', | |
392 | video_id, note='Extracting videos in anthology') | |
393 | ||
394 | if json_data['data']: | |
395 | return self.playlist_from_matches( | |
396 | json_data['data'], bv_id, title, ie=BiliBiliIE.ie_key(), | |
397 | getter=lambda entry: 'https://www.bilibili.com/video/%s?p=%d' % (bv_id, entry['page'])) | |
398 | ||
399 | def _get_video_id_set(self, id, is_bv): | |
400 | query = {'bvid': id} if is_bv else {'aid': id} | |
401 | response = self._download_json( | |
402 | "http://api.bilibili.cn/x/web-interface/view", | |
403 | id, query=query, | |
404 | note='Grabbing original ID via API') | |
405 | ||
406 | if response['code'] == -400: | |
407 | raise ExtractorError('Video ID does not exist', expected=True, video_id=id) | |
408 | elif response['code'] != 0: | |
409 | raise ExtractorError(f'Unknown error occurred during API check (code {response["code"]})', | |
410 | expected=True, video_id=id) | |
411 | return response['data']['aid'], response['data']['bvid'] | |
412 | ||
413 | def _get_comments(self, video_id, commentPageNumber=0): | |
414 | for idx in itertools.count(1): | |
415 | replies = traverse_obj( | |
416 | self._download_json( | |
417 | f'https://api.bilibili.com/x/v2/reply?pn={idx}&oid={video_id}&type=1&jsonp=jsonp&sort=2&_=1567227301685', | |
418 | video_id, note=f'Extracting comments from page {idx}', fatal=False), | |
419 | ('data', 'replies')) | |
420 | if not replies: | |
421 | return | |
422 | for children in map(self._get_all_children, replies): | |
423 | yield from children | |
424 | ||
425 | def _get_all_children(self, reply): | |
426 | yield { | |
427 | 'author': traverse_obj(reply, ('member', 'uname')), | |
428 | 'author_id': traverse_obj(reply, ('member', 'mid')), | |
429 | 'id': reply.get('rpid'), | |
430 | 'text': traverse_obj(reply, ('content', 'message')), | |
431 | 'timestamp': reply.get('ctime'), | |
432 | 'parent': reply.get('parent') or 'root', | |
433 | } | |
434 | for children in map(self._get_all_children, reply.get('replies') or []): | |
435 | yield from children | |
436 | ||
437 | ||
438 | class BiliBiliBangumiIE(InfoExtractor): | |
439 | _VALID_URL = r'https?://bangumi\.bilibili\.com/anime/(?P<id>\d+)' | |
440 | ||
441 | IE_NAME = 'bangumi.bilibili.com' | |
442 | IE_DESC = 'BiliBili番剧' | |
443 | ||
444 | _TESTS = [{ | |
445 | 'url': 'http://bangumi.bilibili.com/anime/1869', | |
446 | 'info_dict': { | |
447 | 'id': '1869', | |
448 | 'title': '混沌武士', | |
449 | 'description': 'md5:6a9622b911565794c11f25f81d6a97d2', | |
450 | }, | |
451 | 'playlist_count': 26, | |
452 | }, { | |
453 | 'url': 'http://bangumi.bilibili.com/anime/1869', | |
454 | 'info_dict': { | |
455 | 'id': '1869', | |
456 | 'title': '混沌武士', | |
457 | 'description': 'md5:6a9622b911565794c11f25f81d6a97d2', | |
458 | }, | |
459 | 'playlist': [{ | |
460 | 'md5': '91da8621454dd58316851c27c68b0c13', | |
461 | 'info_dict': { | |
462 | 'id': '40062', | |
463 | 'ext': 'mp4', | |
464 | 'title': '混沌武士', | |
465 | 'description': '故事发生在日本的江户时代。风是一个小酒馆的打工女。一日,酒馆里来了一群恶霸,虽然他们的举动令风十分不满,但是毕竟风只是一届女流,无法对他们采取什么行动,只能在心里嘟哝。这时,酒家里又进来了个“不良份子...', | |
466 | 'timestamp': 1414538739, | |
467 | 'upload_date': '20141028', | |
468 | 'episode': '疾风怒涛 Tempestuous Temperaments', | |
469 | 'episode_number': 1, | |
470 | }, | |
471 | }], | |
472 | 'params': { | |
473 | 'playlist_items': '1', | |
474 | }, | |
475 | }] | |
476 | ||
477 | @classmethod | |
478 | def suitable(cls, url): | |
479 | return False if BiliBiliIE.suitable(url) else super(BiliBiliBangumiIE, cls).suitable(url) | |
480 | ||
481 | def _real_extract(self, url): | |
482 | bangumi_id = self._match_id(url) | |
483 | ||
484 | # Sometimes this API returns a JSONP response | |
485 | season_info = self._download_json( | |
486 | 'http://bangumi.bilibili.com/jsonp/seasoninfo/%s.ver' % bangumi_id, | |
487 | bangumi_id, transform_source=strip_jsonp)['result'] | |
488 | ||
489 | entries = [{ | |
490 | '_type': 'url_transparent', | |
491 | 'url': smuggle_url(episode['webplay_url'], {'no_bangumi_tip': 1}), | |
492 | 'ie_key': BiliBiliIE.ie_key(), | |
493 | 'timestamp': parse_iso8601(episode.get('update_time'), delimiter=' '), | |
494 | 'episode': episode.get('index_title'), | |
495 | 'episode_number': int_or_none(episode.get('index')), | |
496 | } for episode in season_info['episodes']] | |
497 | ||
498 | entries = sorted(entries, key=lambda entry: entry.get('episode_number')) | |
499 | ||
500 | return self.playlist_result( | |
501 | entries, bangumi_id, | |
502 | season_info.get('bangumi_title'), season_info.get('evaluate')) | |
503 | ||
504 | ||
505 | class BilibiliChannelIE(InfoExtractor): | |
506 | _VALID_URL = r'https?://space.bilibili\.com/(?P<id>\d+)' | |
507 | _API_URL = "https://api.bilibili.com/x/space/arc/search?mid=%s&pn=%d&jsonp=jsonp" | |
508 | _TESTS = [{ | |
509 | 'url': 'https://space.bilibili.com/3985676/video', | |
510 | 'info_dict': {}, | |
511 | 'playlist_mincount': 112, | |
512 | }] | |
513 | ||
514 | def _entries(self, list_id): | |
515 | count, max_count = 0, None | |
516 | ||
517 | for page_num in itertools.count(1): | |
518 | data = self._download_json( | |
519 | self._API_URL % (list_id, page_num), list_id, note=f'Downloading page {page_num}')['data'] | |
520 | ||
521 | max_count = max_count or traverse_obj(data, ('page', 'count')) | |
522 | ||
523 | entries = traverse_obj(data, ('list', 'vlist')) | |
524 | if not entries: | |
525 | return | |
526 | for entry in entries: | |
527 | yield self.url_result( | |
528 | 'https://www.bilibili.com/video/%s' % entry['bvid'], | |
529 | BiliBiliIE.ie_key(), entry['bvid']) | |
530 | ||
531 | count += len(entries) | |
532 | if max_count and count >= max_count: | |
533 | return | |
534 | ||
535 | def _real_extract(self, url): | |
536 | list_id = self._match_id(url) | |
537 | return self.playlist_result(self._entries(list_id), list_id) | |
538 | ||
539 | ||
540 | class BilibiliCategoryIE(InfoExtractor): | |
541 | IE_NAME = 'Bilibili category extractor' | |
542 | _MAX_RESULTS = 1000000 | |
543 | _VALID_URL = r'https?://www\.bilibili\.com/v/[a-zA-Z]+\/[a-zA-Z]+' | |
544 | _TESTS = [{ | |
545 | 'url': 'https://www.bilibili.com/v/kichiku/mad', | |
546 | 'info_dict': { | |
547 | 'id': 'kichiku: mad', | |
548 | 'title': 'kichiku: mad' | |
549 | }, | |
550 | 'playlist_mincount': 45, | |
551 | 'params': { | |
552 | 'playlistend': 45 | |
553 | } | |
554 | }] | |
555 | ||
556 | def _fetch_page(self, api_url, num_pages, query, page_num): | |
557 | parsed_json = self._download_json( | |
558 | api_url, query, query={'Search_key': query, 'pn': page_num}, | |
559 | note='Extracting results from page %s of %s' % (page_num, num_pages)) | |
560 | ||
561 | video_list = traverse_obj(parsed_json, ('data', 'archives'), expected_type=list) | |
562 | if not video_list: | |
563 | raise ExtractorError('Failed to retrieve video list for page %d' % page_num) | |
564 | ||
565 | for video in video_list: | |
566 | yield self.url_result( | |
567 | 'https://www.bilibili.com/video/%s' % video['bvid'], 'BiliBili', video['bvid']) | |
568 | ||
569 | def _entries(self, category, subcategory, query): | |
570 | # map of categories : subcategories : RIDs | |
571 | rid_map = { | |
572 | 'kichiku': { | |
573 | 'mad': 26, | |
574 | 'manual_vocaloid': 126, | |
575 | 'guide': 22, | |
576 | 'theatre': 216, | |
577 | 'course': 127 | |
578 | }, | |
579 | } | |
580 | ||
581 | if category not in rid_map: | |
582 | raise ExtractorError( | |
583 | f'The category {category} isn\'t supported. Supported categories: {list(rid_map.keys())}') | |
584 | if subcategory not in rid_map[category]: | |
585 | raise ExtractorError( | |
586 | f'The subcategory {subcategory} isn\'t supported for this category. Supported subcategories: {list(rid_map[category].keys())}') | |
587 | rid_value = rid_map[category][subcategory] | |
588 | ||
589 | api_url = 'https://api.bilibili.com/x/web-interface/newlist?rid=%d&type=1&ps=20&jsonp=jsonp' % rid_value | |
590 | page_json = self._download_json(api_url, query, query={'Search_key': query, 'pn': '1'}) | |
591 | page_data = traverse_obj(page_json, ('data', 'page'), expected_type=dict) | |
592 | count, size = int_or_none(page_data.get('count')), int_or_none(page_data.get('size')) | |
593 | if count is None or not size: | |
594 | raise ExtractorError('Failed to calculate either page count or size') | |
595 | ||
596 | num_pages = math.ceil(count / size) | |
597 | ||
598 | return OnDemandPagedList(functools.partial( | |
599 | self._fetch_page, api_url, num_pages, query), size) | |
600 | ||
601 | def _real_extract(self, url): | |
602 | u = compat_urllib_parse_urlparse(url) | |
603 | category, subcategory = u.path.split('/')[2:4] | |
604 | query = '%s: %s' % (category, subcategory) | |
605 | ||
606 | return self.playlist_result(self._entries(category, subcategory, query), query, query) | |
607 | ||
608 | ||
609 | class BiliBiliSearchIE(SearchInfoExtractor): | |
610 | IE_DESC = 'Bilibili video search' | |
611 | _MAX_RESULTS = 100000 | |
612 | _SEARCH_KEY = 'bilisearch' | |
613 | ||
614 | def _search_results(self, query): | |
615 | for page_num in itertools.count(1): | |
616 | videos = self._download_json( | |
617 | 'https://api.bilibili.com/x/web-interface/search/type', query, | |
618 | note=f'Extracting results from page {page_num}', query={ | |
619 | 'Search_key': query, | |
620 | 'keyword': query, | |
621 | 'page': page_num, | |
622 | 'context': '', | |
623 | 'order': 'pubdate', | |
624 | 'duration': 0, | |
625 | 'tids_2': '', | |
626 | '__refresh__': 'true', | |
627 | 'search_type': 'video', | |
628 | 'tids': 0, | |
629 | 'highlight': 1, | |
630 | })['data'].get('result') or [] | |
631 | for video in videos: | |
632 | yield self.url_result(video['arcurl'], 'BiliBili', str(video['aid'])) | |
633 | ||
634 | ||
635 | class BilibiliAudioBaseIE(InfoExtractor): | |
636 | def _call_api(self, path, sid, query=None): | |
637 | if not query: | |
638 | query = {'sid': sid} | |
639 | return self._download_json( | |
640 | 'https://www.bilibili.com/audio/music-service-c/web/' + path, | |
641 | sid, query=query)['data'] | |
642 | ||
643 | ||
644 | class BilibiliAudioIE(BilibiliAudioBaseIE): | |
645 | _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/au(?P<id>\d+)' | |
646 | _TEST = { | |
647 | 'url': 'https://www.bilibili.com/audio/au1003142', | |
648 | 'md5': 'fec4987014ec94ef9e666d4d158ad03b', | |
649 | 'info_dict': { | |
650 | 'id': '1003142', | |
651 | 'ext': 'm4a', | |
652 | 'title': '【tsukimi】YELLOW / 神山羊', | |
653 | 'artist': 'tsukimi', | |
654 | 'comment_count': int, | |
655 | 'description': 'YELLOW的mp3版!', | |
656 | 'duration': 183, | |
657 | 'subtitles': { | |
658 | 'origin': [{ | |
659 | 'ext': 'lrc', | |
660 | }], | |
661 | }, | |
662 | 'thumbnail': r're:^https?://.+\.jpg', | |
663 | 'timestamp': 1564836614, | |
664 | 'upload_date': '20190803', | |
665 | 'uploader': 'tsukimi-つきみぐー', | |
666 | 'view_count': int, | |
667 | }, | |
668 | } | |
669 | ||
670 | def _real_extract(self, url): | |
671 | au_id = self._match_id(url) | |
672 | ||
673 | play_data = self._call_api('url', au_id) | |
674 | formats = [{ | |
675 | 'url': play_data['cdns'][0], | |
676 | 'filesize': int_or_none(play_data.get('size')), | |
677 | 'vcodec': 'none' | |
678 | }] | |
679 | ||
680 | song = self._call_api('song/info', au_id) | |
681 | title = song['title'] | |
682 | statistic = song.get('statistic') or {} | |
683 | ||
684 | subtitles = None | |
685 | lyric = song.get('lyric') | |
686 | if lyric: | |
687 | subtitles = { | |
688 | 'origin': [{ | |
689 | 'url': lyric, | |
690 | }] | |
691 | } | |
692 | ||
693 | return { | |
694 | 'id': au_id, | |
695 | 'title': title, | |
696 | 'formats': formats, | |
697 | 'artist': song.get('author'), | |
698 | 'comment_count': int_or_none(statistic.get('comment')), | |
699 | 'description': song.get('intro'), | |
700 | 'duration': int_or_none(song.get('duration')), | |
701 | 'subtitles': subtitles, | |
702 | 'thumbnail': song.get('cover'), | |
703 | 'timestamp': int_or_none(song.get('passtime')), | |
704 | 'uploader': song.get('uname'), | |
705 | 'view_count': int_or_none(statistic.get('play')), | |
706 | } | |
707 | ||
708 | ||
709 | class BilibiliAudioAlbumIE(BilibiliAudioBaseIE): | |
710 | _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/am(?P<id>\d+)' | |
711 | _TEST = { | |
712 | 'url': 'https://www.bilibili.com/audio/am10624', | |
713 | 'info_dict': { | |
714 | 'id': '10624', | |
715 | 'title': '每日新曲推荐(每日11:00更新)', | |
716 | 'description': '每天11:00更新,为你推送最新音乐', | |
717 | }, | |
718 | 'playlist_count': 19, | |
719 | } | |
720 | ||
721 | def _real_extract(self, url): | |
722 | am_id = self._match_id(url) | |
723 | ||
724 | songs = self._call_api( | |
725 | 'song/of-menu', am_id, {'sid': am_id, 'pn': 1, 'ps': 100})['data'] | |
726 | ||
727 | entries = [] | |
728 | for song in songs: | |
729 | sid = str_or_none(song.get('id')) | |
730 | if not sid: | |
731 | continue | |
732 | entries.append(self.url_result( | |
733 | 'https://www.bilibili.com/audio/au' + sid, | |
734 | BilibiliAudioIE.ie_key(), sid)) | |
735 | ||
736 | if entries: | |
737 | album_data = self._call_api('menu/info', am_id) or {} | |
738 | album_title = album_data.get('title') | |
739 | if album_title: | |
740 | for entry in entries: | |
741 | entry['album'] = album_title | |
742 | return self.playlist_result( | |
743 | entries, am_id, album_title, album_data.get('intro')) | |
744 | ||
745 | return self.playlist_result(entries, am_id) | |
746 | ||
747 | ||
748 | class BiliBiliPlayerIE(InfoExtractor): | |
749 | _VALID_URL = r'https?://player\.bilibili\.com/player\.html\?.*?\baid=(?P<id>\d+)' | |
750 | _TEST = { | |
751 | 'url': 'http://player.bilibili.com/player.html?aid=92494333&cid=157926707&page=1', | |
752 | 'only_matching': True, | |
753 | } | |
754 | ||
755 | def _real_extract(self, url): | |
756 | video_id = self._match_id(url) | |
757 | return self.url_result( | |
758 | 'http://www.bilibili.tv/video/av%s/' % video_id, | |
759 | ie=BiliBiliIE.ie_key(), video_id=video_id) | |
760 | ||
761 | ||
762 | class BiliIntlBaseIE(InfoExtractor): | |
763 | _API_URL = 'https://api.bilibili.tv/intl/gateway' | |
764 | _NETRC_MACHINE = 'biliintl' | |
765 | ||
766 | def _call_api(self, endpoint, *args, **kwargs): | |
767 | json = self._download_json(self._API_URL + endpoint, *args, **kwargs) | |
768 | if json.get('code'): | |
769 | if json['code'] in (10004004, 10004005, 10023006): | |
770 | self.raise_login_required() | |
771 | elif json['code'] == 10004001: | |
772 | self.raise_geo_restricted() | |
773 | else: | |
774 | if json.get('message') and str(json['code']) != json['message']: | |
775 | errmsg = f'{kwargs.get("errnote", "Unable to download JSON metadata")}: {self.IE_NAME} said: {json["message"]}' | |
776 | else: | |
777 | errmsg = kwargs.get('errnote', 'Unable to download JSON metadata') | |
778 | if kwargs.get('fatal'): | |
779 | raise ExtractorError(errmsg) | |
780 | else: | |
781 | self.report_warning(errmsg) | |
782 | return json.get('data') | |
783 | ||
784 | def json2srt(self, json): | |
785 | data = '\n\n'.join( | |
786 | f'{i + 1}\n{srt_subtitles_timecode(line["from"])} --> {srt_subtitles_timecode(line["to"])}\n{line["content"]}' | |
787 | for i, line in enumerate(json['body']) if line.get('content')) | |
788 | return data | |
789 | ||
790 | def _get_subtitles(self, *, ep_id=None, aid=None): | |
791 | sub_json = self._call_api( | |
792 | '/web/v2/subtitle', ep_id or aid, note='Downloading subtitles list', | |
793 | errnote='Unable to download subtitles list', query=filter_dict({ | |
794 | 'platform': 'web', | |
795 | 'episode_id': ep_id, | |
796 | 'aid': aid, | |
797 | })) | |
798 | subtitles = {} | |
799 | for sub in sub_json.get('subtitles') or []: | |
800 | sub_url = sub.get('url') | |
801 | if not sub_url: | |
802 | continue | |
803 | sub_data = self._download_json( | |
804 | sub_url, ep_id or aid, errnote='Unable to download subtitles', fatal=False, | |
805 | note='Downloading subtitles%s' % f' for {sub["lang"]}' if sub.get('lang') else '') | |
806 | if not sub_data: | |
807 | continue | |
808 | subtitles.setdefault(sub.get('lang_key', 'en'), []).append({ | |
809 | 'ext': 'srt', | |
810 | 'data': self.json2srt(sub_data) | |
811 | }) | |
812 | return subtitles | |
813 | ||
814 | def _get_formats(self, *, ep_id=None, aid=None): | |
815 | video_json = self._call_api( | |
816 | '/web/playurl', ep_id or aid, note='Downloading video formats', | |
817 | errnote='Unable to download video formats', query=filter_dict({ | |
818 | 'platform': 'web', | |
819 | 'ep_id': ep_id, | |
820 | 'aid': aid, | |
821 | })) | |
822 | video_json = video_json['playurl'] | |
823 | formats = [] | |
824 | for vid in video_json.get('video') or []: | |
825 | video_res = vid.get('video_resource') or {} | |
826 | video_info = vid.get('stream_info') or {} | |
827 | if not video_res.get('url'): | |
828 | continue | |
829 | formats.append({ | |
830 | 'url': video_res['url'], | |
831 | 'ext': 'mp4', | |
832 | 'format_note': video_info.get('desc_words'), | |
833 | 'width': video_res.get('width'), | |
834 | 'height': video_res.get('height'), | |
835 | 'vbr': video_res.get('bandwidth'), | |
836 | 'acodec': 'none', | |
837 | 'vcodec': video_res.get('codecs'), | |
838 | 'filesize': video_res.get('size'), | |
839 | }) | |
840 | for aud in video_json.get('audio_resource') or []: | |
841 | if not aud.get('url'): | |
842 | continue | |
843 | formats.append({ | |
844 | 'url': aud['url'], | |
845 | 'ext': 'mp4', | |
846 | 'abr': aud.get('bandwidth'), | |
847 | 'acodec': aud.get('codecs'), | |
848 | 'vcodec': 'none', | |
849 | 'filesize': aud.get('size'), | |
850 | }) | |
851 | ||
852 | self._sort_formats(formats) | |
853 | return formats | |
854 | ||
855 | def _extract_video_info(self, video_data, *, ep_id=None, aid=None): | |
856 | return { | |
857 | 'id': ep_id or aid, | |
858 | 'title': video_data.get('title_display') or video_data.get('title'), | |
859 | 'thumbnail': video_data.get('cover'), | |
860 | 'episode_number': int_or_none(self._search_regex( | |
861 | r'^E(\d+)(?:$| - )', video_data.get('title_display') or '', 'episode number', default=None)), | |
862 | 'formats': self._get_formats(ep_id=ep_id, aid=aid), | |
863 | 'subtitles': self._get_subtitles(ep_id=ep_id, aid=aid), | |
864 | 'extractor_key': BiliIntlIE.ie_key(), | |
865 | } | |
866 | ||
867 | def _perform_login(self, username, password): | |
868 | try: | |
869 | from Cryptodome.PublicKey import RSA | |
870 | from Cryptodome.Cipher import PKCS1_v1_5 | |
871 | except ImportError: | |
872 | try: | |
873 | from Crypto.PublicKey import RSA | |
874 | from Crypto.Cipher import PKCS1_v1_5 | |
875 | except ImportError: | |
876 | raise ExtractorError('pycryptodomex not found. Please install', expected=True) | |
877 | ||
878 | key_data = self._download_json( | |
879 | 'https://passport.bilibili.tv/x/intl/passport-login/web/key?lang=en-US', None, | |
880 | note='Downloading login key', errnote='Unable to download login key')['data'] | |
881 | ||
882 | public_key = RSA.importKey(key_data['key']) | |
883 | password_hash = PKCS1_v1_5.new(public_key).encrypt((key_data['hash'] + password).encode('utf-8')) | |
884 | login_post = self._download_json( | |
885 | 'https://passport.bilibili.tv/x/intl/passport-login/web/login/password?lang=en-US', None, data=urlencode_postdata({ | |
886 | 'username': username, | |
887 | 'password': base64.b64encode(password_hash).decode('ascii'), | |
888 | 'keep_me': 'true', | |
889 | 's_locale': 'en_US', | |
890 | 'isTrusted': 'true' | |
891 | }), note='Logging in', errnote='Unable to log in') | |
892 | if login_post.get('code'): | |
893 | if login_post.get('message'): | |
894 | raise ExtractorError(f'Unable to log in: {self.IE_NAME} said: {login_post["message"]}', expected=True) | |
895 | else: | |
896 | raise ExtractorError('Unable to log in') | |
897 | ||
898 | ||
899 | class BiliIntlIE(BiliIntlBaseIE): | |
900 | _VALID_URL = r'https?://(?:www\.)?bili(?:bili\.tv|intl\.com)/(?:[a-z]{2}/)?(play/(?P<season_id>\d+)/(?P<ep_id>\d+)|video/(?P<aid>\d+))' | |
901 | _TESTS = [{ | |
902 | # Bstation page | |
903 | 'url': 'https://www.bilibili.tv/en/play/34613/341736', | |
904 | 'info_dict': { | |
905 | 'id': '341736', | |
906 | 'ext': 'mp4', | |
907 | 'title': 'E2 - The First Night', | |
908 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
909 | 'episode_number': 2, | |
910 | } | |
911 | }, { | |
912 | # Non-Bstation page | |
913 | 'url': 'https://www.bilibili.tv/en/play/1033760/11005006', | |
914 | 'info_dict': { | |
915 | 'id': '11005006', | |
916 | 'ext': 'mp4', | |
917 | 'title': 'E3 - Who?', | |
918 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
919 | 'episode_number': 3, | |
920 | } | |
921 | }, { | |
922 | # Subtitle with empty content | |
923 | 'url': 'https://www.bilibili.tv/en/play/1005144/10131790', | |
924 | 'info_dict': { | |
925 | 'id': '10131790', | |
926 | 'ext': 'mp4', | |
927 | 'title': 'E140 - Two Heartbeats: Kabuto\'s Trap', | |
928 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
929 | 'episode_number': 140, | |
930 | }, | |
931 | 'skip': 'According to the copyright owner\'s request, you may only watch the video after you log in.' | |
932 | }, { | |
933 | 'url': 'https://www.biliintl.com/en/play/34613/341736', | |
934 | 'only_matching': True, | |
935 | }, { | |
936 | # User-generated content (as opposed to a series licensed from a studio) | |
937 | 'url': 'https://bilibili.tv/en/video/2019955076', | |
938 | 'only_matching': True, | |
939 | }, { | |
940 | # No language in URL | |
941 | 'url': 'https://www.bilibili.tv/video/2019955076', | |
942 | 'only_matching': True, | |
943 | }] | |
944 | ||
945 | def _real_extract(self, url): | |
946 | season_id, ep_id, aid = self._match_valid_url(url).group('season_id', 'ep_id', 'aid') | |
947 | video_id = ep_id or aid | |
948 | webpage = self._download_webpage(url, video_id) | |
949 | # Bstation layout | |
950 | initial_data = self._parse_json(self._search_regex( | |
951 | r'window\.__INITIAL_(?:DATA|STATE)__\s*=\s*({.+?});', webpage, | |
952 | 'preload state', default='{}'), video_id, fatal=False) or {} | |
953 | video_data = ( | |
954 | traverse_obj(initial_data, ('OgvVideo', 'epDetail'), expected_type=dict) | |
955 | or traverse_obj(initial_data, ('UgcVideo', 'videoData'), expected_type=dict) or {}) | |
956 | ||
957 | if season_id and not video_data: | |
958 | # Non-Bstation layout, read through episode list | |
959 | season_json = self._call_api(f'/web/v2/ogv/play/episodes?season_id={season_id}&platform=web', video_id) | |
960 | video_data = traverse_obj(season_json, | |
961 | ('sections', ..., 'episodes', lambda _, v: str(v['episode_id']) == ep_id), | |
962 | expected_type=dict, get_all=False) | |
963 | return self._extract_video_info(video_data, ep_id=ep_id, aid=aid) | |
964 | ||
965 | ||
966 | class BiliIntlSeriesIE(BiliIntlBaseIE): | |
967 | _VALID_URL = r'https?://(?:www\.)?bili(?:bili\.tv|intl\.com)/(?:[a-z]{2}/)?play/(?P<id>\d+)$' | |
968 | _TESTS = [{ | |
969 | 'url': 'https://www.bilibili.tv/en/play/34613', | |
970 | 'playlist_mincount': 15, | |
971 | 'info_dict': { | |
972 | 'id': '34613', | |
973 | 'title': 'Fly Me to the Moon', | |
974 | 'description': 'md5:a861ee1c4dc0acfad85f557cc42ac627', | |
975 | 'categories': ['Romance', 'Comedy', 'Slice of life'], | |
976 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
977 | 'view_count': int, | |
978 | }, | |
979 | 'params': { | |
980 | 'skip_download': True, | |
981 | }, | |
982 | }, { | |
983 | 'url': 'https://www.biliintl.com/en/play/34613', | |
984 | 'only_matching': True, | |
985 | }] | |
986 | ||
987 | def _entries(self, series_id): | |
988 | series_json = self._call_api(f'/web/v2/ogv/play/episodes?season_id={series_id}&platform=web', series_id) | |
989 | for episode in traverse_obj(series_json, ('sections', ..., 'episodes', ...), expected_type=dict, default=[]): | |
990 | episode_id = str(episode.get('episode_id')) | |
991 | yield self._extract_video_info(episode, ep_id=episode_id) | |
992 | ||
993 | def _real_extract(self, url): | |
994 | series_id = self._match_id(url) | |
995 | series_info = self._call_api(f'/web/v2/ogv/play/season_info?season_id={series_id}&platform=web', series_id).get('season') or {} | |
996 | return self.playlist_result( | |
997 | self._entries(series_id), series_id, series_info.get('title'), series_info.get('description'), | |
998 | categories=traverse_obj(series_info, ('styles', ..., 'title'), expected_type=str_or_none), | |
999 | thumbnail=url_or_none(series_info.get('horizontal_cover')), view_count=parse_count(series_info.get('view'))) | |
1000 | ||
1001 | ||
1002 | class BiliLiveIE(InfoExtractor): | |
1003 | _VALID_URL = r'https?://live.bilibili.com/(?P<id>\d+)' | |
1004 | ||
1005 | _TESTS = [{ | |
1006 | 'url': 'https://live.bilibili.com/196', | |
1007 | 'info_dict': { | |
1008 | 'id': '33989', | |
1009 | 'description': "周六杂谈回,其他时候随机游戏。 | \n录播:@下播型泛式录播组。 | \n直播通知群(全员禁言):666906670,902092584,59971⑧481 (功能一样,别多加)", | |
1010 | 'ext': 'flv', | |
1011 | 'title': "太空狼人杀联动,不被爆杀就算赢", | |
1012 | 'thumbnail': "https://i0.hdslb.com/bfs/live/new_room_cover/e607bc1529057ef4b332e1026e62cf46984c314d.jpg", | |
1013 | 'timestamp': 1650802769, | |
1014 | }, | |
1015 | 'skip': 'not live' | |
1016 | }, { | |
1017 | 'url': 'https://live.bilibili.com/196?broadcast_type=0&is_room_feed=1?spm_id_from=333.999.space_home.strengthen_live_card.click', | |
1018 | 'only_matching': True | |
1019 | }] | |
1020 | ||
1021 | _FORMATS = { | |
1022 | 80: {'format_id': 'low', 'format_note': '流畅'}, | |
1023 | 150: {'format_id': 'high_res', 'format_note': '高清'}, | |
1024 | 250: {'format_id': 'ultra_high_res', 'format_note': '超清'}, | |
1025 | 400: {'format_id': 'blue_ray', 'format_note': '蓝光'}, | |
1026 | 10000: {'format_id': 'source', 'format_note': '原画'}, | |
1027 | 20000: {'format_id': '4K', 'format_note': '4K'}, | |
1028 | 30000: {'format_id': 'dolby', 'format_note': '杜比'}, | |
1029 | } | |
1030 | ||
1031 | _quality = staticmethod(qualities(list(_FORMATS))) | |
1032 | ||
1033 | def _call_api(self, path, room_id, query): | |
1034 | api_result = self._download_json(f'https://api.live.bilibili.com/{path}', room_id, query=query) | |
1035 | if api_result.get('code') != 0: | |
1036 | raise ExtractorError(api_result.get('message') or 'Unable to download JSON metadata') | |
1037 | return api_result.get('data') or {} | |
1038 | ||
1039 | def _parse_formats(self, qn, fmt): | |
1040 | for codec in fmt.get('codec') or []: | |
1041 | if codec.get('current_qn') != qn: | |
1042 | continue | |
1043 | for url_info in codec['url_info']: | |
1044 | yield { | |
1045 | 'url': f'{url_info["host"]}{codec["base_url"]}{url_info["extra"]}', | |
1046 | 'ext': fmt.get('format_name'), | |
1047 | 'vcodec': codec.get('codec_name'), | |
1048 | 'quality': self._quality(qn), | |
1049 | **self._FORMATS[qn], | |
1050 | } | |
1051 | ||
1052 | def _real_extract(self, url): | |
1053 | room_id = self._match_id(url) | |
1054 | room_data = self._call_api('room/v1/Room/get_info', room_id, {'id': room_id}) | |
1055 | if room_data.get('live_status') == 0: | |
1056 | raise ExtractorError('Streamer is not live', expected=True) | |
1057 | ||
1058 | formats = [] | |
1059 | for qn in self._FORMATS.keys(): | |
1060 | stream_data = self._call_api('xlive/web-room/v2/index/getRoomPlayInfo', room_id, { | |
1061 | 'room_id': room_id, | |
1062 | 'qn': qn, | |
1063 | 'codec': '0,1', | |
1064 | 'format': '0,2', | |
1065 | 'mask': '0', | |
1066 | 'no_playurl': '0', | |
1067 | 'platform': 'web', | |
1068 | 'protocol': '0,1', | |
1069 | }) | |
1070 | for fmt in traverse_obj(stream_data, ('playurl_info', 'playurl', 'stream', ..., 'format', ...)) or []: | |
1071 | formats.extend(self._parse_formats(qn, fmt)) | |
1072 | self._sort_formats(formats) | |
1073 | ||
1074 | return { | |
1075 | 'id': room_id, | |
1076 | 'title': room_data.get('title'), | |
1077 | 'description': room_data.get('description'), | |
1078 | 'thumbnail': room_data.get('user_cover'), | |
1079 | 'timestamp': stream_data.get('live_time'), | |
1080 | 'formats': formats, | |
1081 | 'http_headers': { | |
1082 | 'Referer': url, | |
1083 | }, | |
1084 | } |