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