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