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