]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/bilibili.py
[MuseScore] Add Extractor (#918)
[yt-dlp.git] / yt_dlp / extractor / bilibili.py
CommitLineData
28746fbd
PH
1# coding: utf-8
2from __future__ import unicode_literals
3
04b32c8f 4import hashlib
6efb0711 5import itertools
06167fbb 6import json
c34f505b 7import functools
520e7533 8import re
c34f505b 9import math
28746fbd 10
06167fbb 11from .common import InfoExtractor, SearchInfoExtractor
bd8f48c7 12from ..compat import (
adc74b3c 13 compat_str,
bd8f48c7
YCH
14 compat_parse_qs,
15 compat_urlparse,
c34f505b 16 compat_urllib_parse_urlparse
bd8f48c7 17)
28746fbd 18from ..utils import (
bd8f48c7 19 ExtractorError,
6461f2b7
YCH
20 int_or_none,
21 float_or_none,
bd8f48c7 22 parse_iso8601,
adc74b3c 23 try_get,
bd8f48c7 24 smuggle_url,
4bc15a68 25 str_or_none,
bd8f48c7 26 strip_jsonp,
04b32c8f 27 unified_timestamp,
bd8f48c7 28 unsmuggle_url,
1f85029d 29 urlencode_postdata,
c34f505b 30 OnDemandPagedList
28746fbd
PH
31)
32
33
34class BiliBiliIE(InfoExtractor):
b4eb08bb
S
35 _VALID_URL = r'''(?x)
36 https?://
37 (?:(?:www|bangumi)\.)?
38 bilibili\.(?:tv|com)/
39 (?:
40 (?:
41 video/[aA][vV]|
42 anime/(?P<anime_id>\d+)/play\#
06167fbb 43 )(?P<id>\d+)|
9536bc07 44 (s/)?video/[bB][vV](?P<id_bv>[^/?#&]+)
b4eb08bb 45 )
06167fbb 46 (?:/?\?p=(?P<page>\d+))?
b4eb08bb 47 '''
28746fbd 48
bd8f48c7 49 _TESTS = [{
06167fbb 50 'url': 'http://www.bilibili.com/video/av1074402/',
3526c304 51 'md5': '5f7d29e1a2872f3df0cf76b1f87d3788',
28746fbd 52 'info_dict': {
04b32c8f 53 'id': '1074402',
3526c304 54 'ext': 'flv',
28746fbd 55 'title': '【金坷垃】金泡沫',
6461f2b7 56 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
3526c304
S
57 'duration': 308.067,
58 'timestamp': 1398012678,
28746fbd 59 'upload_date': '20140420',
ec85ded8 60 'thumbnail': r're:^https?://.+\.jpg',
d90e4030 61 'uploader': '菊子桑',
6461f2b7 62 'uploader_id': '156160',
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
YCH
82 }, {
83 # Title with double quotes
84 'url': 'http://www.bilibili.com/video/av8903802/',
85 'info_dict': {
86 'id': '8903802',
ca270371
YCH
87 'title': '阿滴英文|英文歌分享#6 "Closer',
88 'description': '滴妹今天唱Closer給你聽! 有史以来,被推最多次也是最久的歌曲,其实歌词跟我原本想像差蛮多的,不过还是好听! 微博@阿滴英文',
ca270371 89 },
3526c304
S
90 'playlist': [{
91 'info_dict': {
92 'id': '8903802_part1',
93 'ext': 'flv',
94 'title': '阿滴英文|英文歌分享#6 "Closer',
95 'description': 'md5:3b1b9e25b78da4ef87e9b548b88ee76a',
96 'uploader': '阿滴英文',
97 'uploader_id': '65880958',
98 'timestamp': 1488382634,
99 'upload_date': '20170301',
100 },
101 'params': {
102 'skip_download': True, # Test metadata only
103 },
104 }, {
105 'info_dict': {
106 'id': '8903802_part2',
107 'ext': 'flv',
108 'title': '阿滴英文|英文歌分享#6 "Closer',
109 'description': 'md5:3b1b9e25b78da4ef87e9b548b88ee76a',
110 'uploader': '阿滴英文',
111 'uploader_id': '65880958',
112 'timestamp': 1488382634,
113 'upload_date': '20170301',
114 },
115 'params': {
116 'skip_download': True, # Test metadata only
117 },
118 }]
b4eb08bb
S
119 }, {
120 # new BV video id format
121 'url': 'https://www.bilibili.com/video/BV1JE411F741',
122 'only_matching': True,
adc74b3c 123 }, {
124 # Anthology
125 'url': 'https://www.bilibili.com/video/BV1bK411W797',
126 'info_dict': {
127 'id': 'BV1bK411W797',
7e60c069 128 'title': '物语中的人物是如何吐槽自己的OP的'
adc74b3c 129 },
130 'playlist_count': 17,
bd8f48c7 131 }]
28746fbd 132
c9a0ea6e
S
133 _APP_KEY = 'iVGUTjsxvpLeuDCf'
134 _BILIBILI_KEY = 'aHRmhWMLkdeMuILqORnYZocwMBpMEOdt'
6461f2b7 135
bd8f48c7
YCH
136 def _report_error(self, result):
137 if 'message' in result:
138 raise ExtractorError('%s said: %s' % (self.IE_NAME, result['message']), expected=True)
139 elif 'code' in result:
140 raise ExtractorError('%s returns error %d' % (self.IE_NAME, result['code']), expected=True)
141 else:
142 raise ExtractorError('Can\'t extract Bangumi episode ID')
143
520e7533 144 def _real_extract(self, url):
bd8f48c7
YCH
145 url, smuggled_data = unsmuggle_url(url, {})
146
5ad28e7f 147 mobj = self._match_valid_url(url)
06167fbb 148 video_id = mobj.group('id_bv') or mobj.group('id')
149
150 av_id, bv_id = self._get_video_id_set(video_id, mobj.group('id_bv') is not None)
151 video_id = av_id
152
bd8f48c7 153 anime_id = mobj.group('anime_id')
06167fbb 154 page_id = mobj.group('page')
6461f2b7
YCH
155 webpage = self._download_webpage(url, video_id)
156
adc74b3c 157 # Bilibili anthologies are similar to playlists but all videos share the same video ID as the anthology itself.
158 # If the video has no page argument, check to see if it's an anthology
159 if page_id is None:
a06916d9 160 if not self.get_param('noplaylist'):
adc74b3c 161 r = self._extract_anthology_entries(bv_id, video_id, webpage)
162 if r is not None:
163 self.to_screen('Downloading anthology %s - add --no-playlist to just download video' % video_id)
164 return r
7e60c069 165 else:
166 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
adc74b3c 167
bd8f48c7 168 if 'anime/' not in url:
3526c304 169 cid = self._search_regex(
adc74b3c 170 r'\bcid(?:["\']:|=)(\d+),["\']page(?:["\']:|=)' + compat_str(page_id), webpage, 'cid',
06167fbb 171 default=None
172 ) or self._search_regex(
61cb6683 173 r'\bcid(?:["\']:|=)(\d+)', webpage, 'cid',
3526c304
S
174 default=None
175 ) or compat_parse_qs(self._search_regex(
95a1322b
S
176 [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
177 r'EmbedPlayer\([^)]+,\s*\\"([^"]+)\\"\)',
178 r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
7be15d40
P
179 webpage, 'player parameters'))['cid'][0]
180 else:
bd8f48c7 181 if 'no_bangumi_tip' not in smuggled_data:
7a5c1cfe 182 self.to_screen('Downloading episode %s. To download all videos in anime %s, re-run yt-dlp with %s' % (
bd8f48c7 183 video_id, anime_id, compat_urlparse.urljoin(url, '//bangumi.bilibili.com/anime/%s' % anime_id)))
10db0d2f 184 headers = {
185 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
186 'Referer': url
187 }
188 headers.update(self.geo_verification_headers())
bd8f48c7 189
1f85029d
YCH
190 js = self._download_json(
191 'http://bangumi.bilibili.com/web_api/get_source', video_id,
192 data=urlencode_postdata({'episode_id': video_id}),
bd8f48c7
YCH
193 headers=headers)
194 if 'result' not in js:
195 self._report_error(js)
7be15d40 196 cid = js['result']['cid']
04b32c8f 197
10db0d2f 198 headers = {
199 'Accept': 'application/json',
200 'Referer': url
201 }
202 headers.update(self.geo_verification_headers())
203
d90e4030 204 entries = []
c4a21bc9 205
3526c304
S
206 RENDITIONS = ('qn=80&quality=80&type=', 'quality=2&type=mp4')
207 for num, rendition in enumerate(RENDITIONS, start=1):
208 payload = 'appkey=%s&cid=%s&otype=json&%s' % (self._APP_KEY, cid, rendition)
209 sign = hashlib.md5((payload + self._BILIBILI_KEY).encode('utf-8')).hexdigest()
210
211 video_info = self._download_json(
d1239608 212 'http://interface.bilibili.com/v2/playurl?%s&sign=%s' % (payload, sign),
3526c304
S
213 video_id, note='Downloading video info page',
214 headers=headers, fatal=num == len(RENDITIONS))
215
216 if not video_info:
217 continue
218
219 if 'durl' not in video_info:
220 if num < len(RENDITIONS):
221 continue
222 self._report_error(video_info)
223
224 for idx, durl in enumerate(video_info['durl']):
225 formats = [{
226 'url': durl['url'],
227 'filesize': int_or_none(durl['size']),
228 }]
229 for backup_url in durl.get('backup_url', []):
230 formats.append({
231 'url': backup_url,
232 # backup URLs have lower priorities
f983b875 233 'quality': -2 if 'hd.mp4' in backup_url else -3,
3526c304
S
234 })
235
236 for a_format in formats:
237 a_format.setdefault('http_headers', {}).update({
238 'Referer': url,
239 })
240
241 self._sort_formats(formats)
242
243 entries.append({
244 'id': '%s_part%s' % (video_id, idx),
245 'duration': float_or_none(durl.get('length'), 1000),
246 'formats': formats,
6461f2b7 247 })
3526c304 248 break
6461f2b7 249
3526c304 250 title = self._html_search_regex(
06167fbb 251 (r'<h1[^>]+\btitle=(["\'])(?P<title>(?:(?!\1).)+)\1',
252 r'(?s)<h1[^>]*>(?P<title>.+?)</h1>'), webpage, 'title',
adc74b3c 253 group='title')
254
255 # Get part title for anthologies
256 if page_id is not None:
257 # TODO: The json is already downloaded by _extract_anthology_entries. Don't redownload for each video
258 part_title = try_get(
259 self._download_json(
260 "https://api.bilibili.com/x/player/pagelist?bvid=%s&jsonp=jsonp" % bv_id,
261 video_id, note='Extracting videos in anthology'),
262 lambda x: x['data'][int(page_id) - 1]['part'])
263 title = part_title or title
264
6461f2b7 265 description = self._html_search_meta('description', webpage)
04b32c8f 266 timestamp = unified_timestamp(self._html_search_regex(
3526c304
S
267 r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time',
268 default=None) or self._html_search_meta(
269 'uploadDate', webpage, 'timestamp', default=None))
1f85029d 270 thumbnail = self._html_search_meta(['og:image', 'thumbnailUrl'], webpage)
6461f2b7
YCH
271
272 # TODO 'view_count' requires deobfuscating Javascript
d90e4030 273 info = {
adc74b3c 274 'id': compat_str(video_id) if page_id is None else '%s_p%s' % (video_id, page_id),
06167fbb 275 'cid': cid,
d90e4030 276 'title': title,
6461f2b7
YCH
277 'description': description,
278 'timestamp': timestamp,
7be15d40 279 'thumbnail': thumbnail,
04b32c8f 280 'duration': float_or_none(video_info.get('timelength'), scale=1000),
28746fbd 281 }
d90e4030 282
6461f2b7 283 uploader_mobj = re.search(
7e60c069 284 r'<a[^>]+href="(?:https?:)?//space\.bilibili\.com/(?P<id>\d+)"[^>]*>\s*(?P<name>[^<]+?)\s*<',
6461f2b7
YCH
285 webpage)
286 if uploader_mobj:
287 info.update({
ed807c18 288 'uploader': uploader_mobj.group('name').strip(),
6461f2b7
YCH
289 'uploader_id': uploader_mobj.group('id'),
290 })
06167fbb 291
3526c304
S
292 if not info.get('uploader'):
293 info['uploader'] = self._html_search_meta(
294 'author', webpage, 'uploader', default=None)
6461f2b7 295
06167fbb 296 raw_danmaku = self._get_raw_danmaku(video_id, cid)
297
298 raw_tags = self._get_tags(video_id)
299 tags = list(map(lambda x: x['tag_name'], raw_tags))
300
301 top_level_info = {
302 'raw_danmaku': raw_danmaku,
06167fbb 303 'tags': tags,
304 'raw_tags': raw_tags,
305 }
a06916d9 306 if self.get_param('getcomments', False):
277d6ff5 307 def get_comments():
308 comments = self._get_all_comment_pages(video_id)
309 return {
310 'comments': comments,
311 'comment_count': len(comments)
312 }
313
314 top_level_info['__post_extractor'] = get_comments
06167fbb 315
316 '''
317 # Requires https://github.com/m13253/danmaku2ass which is licenced under GPL3
318 # See https://github.com/animelover1984/youtube-dl
319 danmaku = NiconicoIE.CreateDanmaku(raw_danmaku, commentType='Bilibili', x=1024, y=576)
320 entries[0]['subtitles'] = {
321 'danmaku': [{
322 'ext': 'ass',
323 'data': danmaku
324 }]
325 }
326 '''
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]
334 else:
ad73083f
YCH
335 for idx, entry in enumerate(entries):
336 entry['id'] = '%s_part%d' % (video_id, (idx + 1))
337
06167fbb 338 global_info = {
d90e4030 339 '_type': 'multi_video',
adc74b3c 340 'id': compat_str(video_id),
06167fbb 341 'bv_id': bv_id,
6461f2b7
YCH
342 'title': title,
343 'description': description,
d90e4030 344 'entries': entries,
6461f2b7 345 }
bd8f48c7 346
06167fbb 347 global_info.update(info)
348 global_info.update(top_level_info)
349
350 return global_info
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',
355 r'(?s)<h1[^>]*>(?P<title>.+?)</h1>'), webpage, 'title',
356 group='title')
357 json_data = self._download_json(
358 "https://api.bilibili.com/x/player/pagelist?bvid=%s&jsonp=jsonp" % bv_id,
359 video_id, note='Extracting videos in anthology')
360
361 if len(json_data['data']) > 1:
362 return self.playlist_from_matches(
363 json_data['data'], bv_id, title, ie=BiliBiliIE.ie_key(),
364 getter=lambda entry: 'https://www.bilibili.com/video/%s?p=%d' % (bv_id, entry['page']))
365
06167fbb 366 def _get_video_id_set(self, id, is_bv):
367 query = {'bvid': id} if is_bv else {'aid': id}
368 response = self._download_json(
369 "http://api.bilibili.cn/x/web-interface/view",
370 id, query=query,
371 note='Grabbing original ID via API')
372
373 if response['code'] == -400:
374 raise ExtractorError('Video ID does not exist', expected=True, video_id=id)
375 elif response['code'] != 0:
376 raise ExtractorError('Unknown error occurred during API check (code %s)' % response['code'], expected=True, video_id=id)
377 return (response['data']['aid'], response['data']['bvid'])
378
379 # recursive solution to getting every page of comments for the video
380 # we can stop when we reach a page without any comments
381 def _get_all_comment_pages(self, video_id, commentPageNumber=0):
382 comment_url = "https://api.bilibili.com/x/v2/reply?jsonp=jsonp&pn=%s&type=1&oid=%s&sort=2&_=1567227301685" % (commentPageNumber, video_id)
383 json_str = self._download_webpage(
384 comment_url, video_id,
385 note='Extracting comments from page %s' % (commentPageNumber))
386 replies = json.loads(json_str)['data']['replies']
387 if replies is None:
388 return []
389 return self._get_all_children(replies) + self._get_all_comment_pages(video_id, commentPageNumber + 1)
390
391 # extracts all comments in the tree
392 def _get_all_children(self, replies):
393 if replies is None:
394 return []
395
396 ret = []
397 for reply in replies:
398 author = reply['member']['uname']
399 author_id = reply['member']['mid']
400 id = reply['rpid']
401 text = reply['content']['message']
402 timestamp = reply['ctime']
403 parent = reply['parent'] if reply['parent'] != 0 else 'root'
404
405 comment = {
406 "author": author,
407 "author_id": author_id,
408 "id": id,
409 "text": text,
410 "timestamp": timestamp,
411 "parent": parent,
412 }
413 ret.append(comment)
414
415 # from the JSON, the comment structure seems arbitrarily deep, but I could be wrong.
416 # Regardless, this should work.
417 ret += self._get_all_children(reply['replies'])
418
419 return ret
420
421 def _get_raw_danmaku(self, video_id, cid):
422 # This will be useful if I decide to scrape all pages instead of doing them individually
423 # cid_url = "https://www.bilibili.com/widget/getPageList?aid=%s" % (video_id)
424 # cid_str = self._download_webpage(cid_url, video_id, note=False)
425 # cid = json.loads(cid_str)[0]['cid']
426
427 danmaku_url = "https://comment.bilibili.com/%s.xml" % (cid)
428 danmaku = self._download_webpage(danmaku_url, video_id, note='Downloading danmaku comments')
429 return danmaku
430
431 def _get_tags(self, video_id):
432 tags_url = "https://api.bilibili.com/x/tag/archive/tags?aid=%s" % (video_id)
433 tags_json = self._download_json(tags_url, video_id, note='Downloading tags')
434 return tags_json['data']
435
bd8f48c7
YCH
436
437class BiliBiliBangumiIE(InfoExtractor):
438 _VALID_URL = r'https?://bangumi\.bilibili\.com/anime/(?P<id>\d+)'
439
440 IE_NAME = 'bangumi.bilibili.com'
441 IE_DESC = 'BiliBili番剧'
442
443 _TESTS = [{
444 'url': 'http://bangumi.bilibili.com/anime/1869',
445 'info_dict': {
446 'id': '1869',
447 'title': '混沌武士',
448 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
449 },
450 'playlist_count': 26,
451 }, {
452 'url': 'http://bangumi.bilibili.com/anime/1869',
453 'info_dict': {
454 'id': '1869',
455 'title': '混沌武士',
456 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
457 },
458 'playlist': [{
459 'md5': '91da8621454dd58316851c27c68b0c13',
460 'info_dict': {
461 'id': '40062',
462 'ext': 'mp4',
463 'title': '混沌武士',
464 'description': '故事发生在日本的江户时代。风是一个小酒馆的打工女。一日,酒馆里来了一群恶霸,虽然他们的举动令风十分不满,但是毕竟风只是一届女流,无法对他们采取什么行动,只能在心里嘟哝。这时,酒家里又进来了个“不良份子...',
465 'timestamp': 1414538739,
466 'upload_date': '20141028',
467 'episode': '疾风怒涛 Tempestuous Temperaments',
468 'episode_number': 1,
469 },
470 }],
471 'params': {
472 'playlist_items': '1',
473 },
474 }]
475
476 @classmethod
477 def suitable(cls, url):
478 return False if BiliBiliIE.suitable(url) else super(BiliBiliBangumiIE, cls).suitable(url)
479
480 def _real_extract(self, url):
481 bangumi_id = self._match_id(url)
482
483 # Sometimes this API returns a JSONP response
484 season_info = self._download_json(
485 'http://bangumi.bilibili.com/jsonp/seasoninfo/%s.ver' % bangumi_id,
486 bangumi_id, transform_source=strip_jsonp)['result']
487
488 entries = [{
489 '_type': 'url_transparent',
490 'url': smuggle_url(episode['webplay_url'], {'no_bangumi_tip': 1}),
491 'ie_key': BiliBiliIE.ie_key(),
492 'timestamp': parse_iso8601(episode.get('update_time'), delimiter=' '),
493 'episode': episode.get('index_title'),
494 'episode_number': int_or_none(episode.get('index')),
495 } for episode in season_info['episodes']]
496
497 entries = sorted(entries, key=lambda entry: entry.get('episode_number'))
498
499 return self.playlist_result(
500 entries, bangumi_id,
501 season_info.get('bangumi_title'), season_info.get('evaluate'))
4bc15a68
RA
502
503
06167fbb 504class BilibiliChannelIE(InfoExtractor):
505 _VALID_URL = r'https?://space.bilibili\.com/(?P<id>\d+)'
6efb0711 506 _API_URL = "https://api.bilibili.com/x/space/arc/search?mid=%s&pn=%d&jsonp=jsonp"
507 _TESTS = [{
508 'url': 'https://space.bilibili.com/3985676/video',
509 'info_dict': {},
510 'playlist_mincount': 112,
511 }]
512
513 def _entries(self, list_id):
514 count, max_count = 0, None
515
516 for page_num in itertools.count(1):
517 data = self._parse_json(
518 self._download_webpage(
519 self._API_URL % (list_id, page_num), list_id,
520 note='Downloading page %d' % page_num),
521 list_id)['data']
522
523 max_count = max_count or try_get(data, lambda x: x['page']['count'])
524
525 entries = try_get(data, lambda x: x['list']['vlist'])
526 if not entries:
527 return
528 for entry in entries:
529 yield self.url_result(
530 'https://www.bilibili.com/video/%s' % entry['bvid'],
531 BiliBiliIE.ie_key(), entry['bvid'])
532
533 count += len(entries)
534 if max_count and count >= max_count:
535 return
06167fbb 536
537 def _real_extract(self, url):
538 list_id = self._match_id(url)
6efb0711 539 return self.playlist_result(self._entries(list_id), list_id)
06167fbb 540
541
c34f505b 542class BilibiliCategoryIE(InfoExtractor):
543 IE_NAME = 'Bilibili category extractor'
544 _MAX_RESULTS = 1000000
545 _VALID_URL = r'https?://www\.bilibili\.com/v/[a-zA-Z]+\/[a-zA-Z]+'
546 _TESTS = [{
547 'url': 'https://www.bilibili.com/v/kichiku/mad',
548 'info_dict': {
549 'id': 'kichiku: mad',
550 'title': 'kichiku: mad'
551 },
552 'playlist_mincount': 45,
553 'params': {
554 'playlistend': 45
555 }
556 }]
557
558 def _fetch_page(self, api_url, num_pages, query, page_num):
559 parsed_json = self._download_json(
560 api_url, query, query={'Search_key': query, 'pn': page_num},
561 note='Extracting results from page %s of %s' % (page_num, num_pages))
562
563 video_list = try_get(parsed_json, lambda x: x['data']['archives'], list)
564 if not video_list:
565 raise ExtractorError('Failed to retrieve video list for page %d' % page_num)
566
567 for video in video_list:
568 yield self.url_result(
569 'https://www.bilibili.com/video/%s' % video['bvid'], 'BiliBili', video['bvid'])
570
571 def _entries(self, category, subcategory, query):
572 # map of categories : subcategories : RIDs
573 rid_map = {
574 'kichiku': {
575 'mad': 26,
576 'manual_vocaloid': 126,
577 'guide': 22,
578 'theatre': 216,
579 'course': 127
580 },
581 }
582
583 if category not in rid_map:
584 raise ExtractorError('The supplied category, %s, is not supported. List of supported categories: %s' % (category, list(rid_map.keys())))
585
586 if subcategory not in rid_map[category]:
587 raise ExtractorError('The subcategory, %s, isn\'t supported for this category. Supported subcategories: %s' % (subcategory, list(rid_map[category].keys())))
588
589 rid_value = rid_map[category][subcategory]
590
591 api_url = 'https://api.bilibili.com/x/web-interface/newlist?rid=%d&type=1&ps=20&jsonp=jsonp' % rid_value
592 page_json = self._download_json(api_url, query, query={'Search_key': query, 'pn': '1'})
593 page_data = try_get(page_json, lambda x: x['data']['page'], dict)
594 count, size = int_or_none(page_data.get('count')), int_or_none(page_data.get('size'))
595 if count is None or not size:
596 raise ExtractorError('Failed to calculate either page count or size')
597
598 num_pages = math.ceil(count / size)
599
600 return OnDemandPagedList(functools.partial(
601 self._fetch_page, api_url, num_pages, query), size)
602
603 def _real_extract(self, url):
604 u = compat_urllib_parse_urlparse(url)
605 category, subcategory = u.path.split('/')[2:4]
606 query = '%s: %s' % (category, subcategory)
607
608 return self.playlist_result(self._entries(category, subcategory, query), query, query)
609
610
06167fbb 611class BiliBiliSearchIE(SearchInfoExtractor):
612 IE_DESC = 'Bilibili video search, "bilisearch" keyword'
613 _MAX_RESULTS = 100000
614 _SEARCH_KEY = 'bilisearch'
615 MAX_NUMBER_OF_RESULTS = 1000
616
617 def _get_n_results(self, query, n):
618 """Get a specified number of results for a query"""
619
620 entries = []
621 pageNumber = 0
622 while True:
623 pageNumber += 1
624 # FIXME
625 api_url = "https://api.bilibili.com/x/web-interface/search/type?context=&page=%s&order=pubdate&keyword=%s&duration=0&tids_2=&__refresh__=true&search_type=video&tids=0&highlight=1" % (pageNumber, query)
626 json_str = self._download_webpage(
627 api_url, "None", query={"Search_key": query},
628 note='Extracting results from page %s' % pageNumber)
629 data = json.loads(json_str)['data']
630
631 # FIXME: this is hideous
632 if "result" not in data:
633 return {
634 '_type': 'playlist',
635 'id': query,
636 'entries': entries[:n]
637 }
638
639 videos = data['result']
640 for video in videos:
adc74b3c 641 e = self.url_result(video['arcurl'], 'BiliBili', compat_str(video['aid']))
06167fbb 642 entries.append(e)
643
644 if(len(entries) >= n or len(videos) >= BiliBiliSearchIE.MAX_NUMBER_OF_RESULTS):
645 return {
646 '_type': 'playlist',
647 'id': query,
648 'entries': entries[:n]
649 }
650
651
4bc15a68
RA
652class BilibiliAudioBaseIE(InfoExtractor):
653 def _call_api(self, path, sid, query=None):
654 if not query:
655 query = {'sid': sid}
656 return self._download_json(
657 'https://www.bilibili.com/audio/music-service-c/web/' + path,
658 sid, query=query)['data']
659
660
661class BilibiliAudioIE(BilibiliAudioBaseIE):
662 _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/au(?P<id>\d+)'
663 _TEST = {
664 'url': 'https://www.bilibili.com/audio/au1003142',
665 'md5': 'fec4987014ec94ef9e666d4d158ad03b',
666 'info_dict': {
667 'id': '1003142',
668 'ext': 'm4a',
669 'title': '【tsukimi】YELLOW / 神山羊',
670 'artist': 'tsukimi',
671 'comment_count': int,
672 'description': 'YELLOW的mp3版!',
673 'duration': 183,
674 'subtitles': {
675 'origin': [{
676 'ext': 'lrc',
677 }],
678 },
679 'thumbnail': r're:^https?://.+\.jpg',
680 'timestamp': 1564836614,
681 'upload_date': '20190803',
682 'uploader': 'tsukimi-つきみぐー',
683 'view_count': int,
684 },
685 }
686
687 def _real_extract(self, url):
688 au_id = self._match_id(url)
689
690 play_data = self._call_api('url', au_id)
691 formats = [{
692 'url': play_data['cdns'][0],
693 'filesize': int_or_none(play_data.get('size')),
f0884c8b 694 'vcodec': 'none'
4bc15a68
RA
695 }]
696
697 song = self._call_api('song/info', au_id)
698 title = song['title']
699 statistic = song.get('statistic') or {}
700
701 subtitles = None
702 lyric = song.get('lyric')
703 if lyric:
704 subtitles = {
705 'origin': [{
706 'url': lyric,
707 }]
708 }
709
710 return {
711 'id': au_id,
712 'title': title,
713 'formats': formats,
714 'artist': song.get('author'),
715 'comment_count': int_or_none(statistic.get('comment')),
716 'description': song.get('intro'),
717 'duration': int_or_none(song.get('duration')),
718 'subtitles': subtitles,
719 'thumbnail': song.get('cover'),
720 'timestamp': int_or_none(song.get('passtime')),
721 'uploader': song.get('uname'),
722 'view_count': int_or_none(statistic.get('play')),
723 }
724
725
726class BilibiliAudioAlbumIE(BilibiliAudioBaseIE):
727 _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/am(?P<id>\d+)'
728 _TEST = {
729 'url': 'https://www.bilibili.com/audio/am10624',
730 'info_dict': {
731 'id': '10624',
732 'title': '每日新曲推荐(每日11:00更新)',
733 'description': '每天11:00更新,为你推送最新音乐',
734 },
735 'playlist_count': 19,
736 }
737
738 def _real_extract(self, url):
739 am_id = self._match_id(url)
740
741 songs = self._call_api(
742 'song/of-menu', am_id, {'sid': am_id, 'pn': 1, 'ps': 100})['data']
743
744 entries = []
745 for song in songs:
746 sid = str_or_none(song.get('id'))
747 if not sid:
748 continue
749 entries.append(self.url_result(
750 'https://www.bilibili.com/audio/au' + sid,
751 BilibiliAudioIE.ie_key(), sid))
752
753 if entries:
754 album_data = self._call_api('menu/info', am_id) or {}
755 album_title = album_data.get('title')
756 if album_title:
757 for entry in entries:
758 entry['album'] = album_title
759 return self.playlist_result(
760 entries, am_id, album_title, album_data.get('intro'))
761
762 return self.playlist_result(entries, am_id)
63dce309
S
763
764
765class BiliBiliPlayerIE(InfoExtractor):
766 _VALID_URL = r'https?://player\.bilibili\.com/player\.html\?.*?\baid=(?P<id>\d+)'
767 _TEST = {
768 'url': 'http://player.bilibili.com/player.html?aid=92494333&cid=157926707&page=1',
769 'only_matching': True,
770 }
771
772 def _real_extract(self, url):
773 video_id = self._match_id(url)
774 return self.url_result(
775 'http://www.bilibili.tv/video/av%s/' % video_id,
776 ie=BiliBiliIE.ie_key(), video_id=video_id)