]>
Commit | Line | Data |
---|---|---|
cfcf60ea | 1 | import base64 |
c34f505b | 2 | import functools |
ad974876 | 3 | import itertools |
c34f505b | 4 | import math |
ad974876 L |
5 | import urllib.error |
6 | import urllib.parse | |
28746fbd | 7 | |
06167fbb | 8 | from .common import InfoExtractor, SearchInfoExtractor |
28746fbd | 9 | from ..utils import ( |
bd8f48c7 | 10 | ExtractorError, |
ad974876 | 11 | GeoRestrictedError, |
2b9d0216 L |
12 | InAdvancePagedList, |
13 | OnDemandPagedList, | |
f5f15c99 | 14 | filter_dict, |
6461f2b7 | 15 | float_or_none, |
ad974876 | 16 | format_field, |
2b9d0216 | 17 | int_or_none, |
ad974876 | 18 | make_archive_id, |
f8580bf0 | 19 | mimetype2ext, |
2b9d0216 | 20 | parse_count, |
ad974876 | 21 | parse_qs, |
b4f53662 | 22 | qualities, |
efc947fb | 23 | srt_subtitles_timecode, |
4bc15a68 | 24 | str_or_none, |
2b9d0216 | 25 | traverse_obj, |
c62ecf0d | 26 | url_or_none, |
ad974876 | 27 | urlencode_postdata, |
28746fbd PH |
28 | ) |
29 | ||
30 | ||
ad974876 L |
31 | class BilibiliBaseIE(InfoExtractor): |
32 | def extract_formats(self, play_info): | |
33 | format_names = { | |
34 | r['quality']: traverse_obj(r, 'new_description', 'display_desc') | |
35 | for r in traverse_obj(play_info, ('support_formats', lambda _, v: v['quality'])) | |
36 | } | |
37 | ||
38 | audios = traverse_obj(play_info, ('dash', 'audio', ...)) | |
39 | flac_audio = traverse_obj(play_info, ('dash', 'flac', 'audio')) | |
40 | if flac_audio: | |
41 | audios.append(flac_audio) | |
42 | formats = [{ | |
43 | 'url': traverse_obj(audio, 'baseUrl', 'base_url', 'url'), | |
44 | 'ext': mimetype2ext(traverse_obj(audio, 'mimeType', 'mime_type')), | |
45 | 'acodec': audio.get('codecs'), | |
46 | 'vcodec': 'none', | |
47 | 'tbr': float_or_none(audio.get('bandwidth'), scale=1000), | |
48 | 'filesize': int_or_none(audio.get('size')) | |
49 | } for audio in audios] | |
50 | ||
51 | formats.extend({ | |
52 | 'url': traverse_obj(video, 'baseUrl', 'base_url', 'url'), | |
53 | 'ext': mimetype2ext(traverse_obj(video, 'mimeType', 'mime_type')), | |
54 | 'fps': float_or_none(traverse_obj(video, 'frameRate', 'frame_rate')), | |
55 | 'width': int_or_none(video.get('width')), | |
56 | 'height': int_or_none(video.get('height')), | |
57 | 'vcodec': video.get('codecs'), | |
58 | 'acodec': 'none' if audios else None, | |
59 | 'tbr': float_or_none(video.get('bandwidth'), scale=1000), | |
60 | 'filesize': int_or_none(video.get('size')), | |
61 | 'quality': int_or_none(video.get('id')), | |
62 | 'format': format_names.get(video.get('id')), | |
63 | } for video in traverse_obj(play_info, ('dash', 'video', ...))) | |
64 | ||
65 | missing_formats = format_names.keys() - set(traverse_obj(formats, (..., 'quality'))) | |
66 | if missing_formats: | |
67 | self.to_screen(f'Format(s) {", ".join(format_names[i] for i in missing_formats)} are missing; ' | |
6368e2e6 | 68 | f'you have to login or become premium member to download them. {self._login_hint()}') |
ad974876 | 69 | |
ad974876 L |
70 | return formats |
71 | ||
72 | def json2srt(self, json_data): | |
73 | srt_data = '' | |
74 | for idx, line in enumerate(json_data.get('body') or []): | |
75 | srt_data += (f'{idx + 1}\n' | |
76 | f'{srt_subtitles_timecode(line["from"])} --> {srt_subtitles_timecode(line["to"])}\n' | |
77 | f'{line["content"]}\n\n') | |
78 | return srt_data | |
79 | ||
80 | def _get_subtitles(self, video_id, initial_state, cid): | |
81 | subtitles = { | |
82 | 'danmaku': [{ | |
83 | 'ext': 'xml', | |
84 | 'url': f'https://comment.bilibili.com/{cid}.xml', | |
85 | }] | |
86 | } | |
87 | ||
88 | for s in traverse_obj(initial_state, ('videoData', 'subtitle', 'list')) or []: | |
89 | subtitles.setdefault(s['lan'], []).append({ | |
90 | 'ext': 'srt', | |
91 | 'data': self.json2srt(self._download_json(s['subtitle_url'], video_id)) | |
92 | }) | |
93 | return subtitles | |
94 | ||
c90c5b9b | 95 | def _get_chapters(self, aid, cid): |
96 | chapters = aid and cid and self._download_json( | |
97 | 'https://api.bilibili.com/x/player/v2', aid, query={'aid': aid, 'cid': cid}, | |
98 | note='Extracting chapters', fatal=False) | |
99 | return traverse_obj(chapters, ('data', 'view_points', ..., { | |
100 | 'title': 'content', | |
101 | 'start_time': 'from', | |
102 | 'end_time': 'to', | |
103 | })) or None | |
104 | ||
ad974876 L |
105 | def _get_comments(self, aid): |
106 | for idx in itertools.count(1): | |
107 | replies = traverse_obj( | |
108 | self._download_json( | |
109 | f'https://api.bilibili.com/x/v2/reply?pn={idx}&oid={aid}&type=1&jsonp=jsonp&sort=2&_=1567227301685', | |
110 | aid, note=f'Extracting comments from page {idx}', fatal=False), | |
111 | ('data', 'replies')) | |
112 | if not replies: | |
113 | return | |
114 | for children in map(self._get_all_children, replies): | |
115 | yield from children | |
116 | ||
117 | def _get_all_children(self, reply): | |
118 | yield { | |
119 | 'author': traverse_obj(reply, ('member', 'uname')), | |
120 | 'author_id': traverse_obj(reply, ('member', 'mid')), | |
121 | 'id': reply.get('rpid'), | |
122 | 'text': traverse_obj(reply, ('content', 'message')), | |
123 | 'timestamp': reply.get('ctime'), | |
124 | 'parent': reply.get('parent') or 'root', | |
125 | } | |
126 | for children in map(self._get_all_children, traverse_obj(reply, ('replies', ...))): | |
127 | yield from children | |
128 | ||
ad974876 L |
129 | |
130 | class BiliBiliIE(BilibiliBaseIE): | |
131 | _VALID_URL = r'https?://www\.bilibili\.com/video/[aAbB][vV](?P<id>[^/?#&]+)' | |
28746fbd | 132 | |
bd8f48c7 | 133 | _TESTS = [{ |
ad974876 L |
134 | 'url': 'https://www.bilibili.com/video/BV13x41117TL', |
135 | 'info_dict': { | |
136 | 'id': 'BV13x41117TL', | |
137 | 'title': '阿滴英文|英文歌分享#6 "Closer', | |
138 | 'ext': 'mp4', | |
139 | 'description': '滴妹今天唱Closer給你聽! 有史以来,被推最多次也是最久的歌曲,其实歌词跟我原本想像差蛮多的,不过还是好听! 微博@阿滴英文', | |
140 | 'uploader_id': '65880958', | |
141 | 'uploader': '阿滴英文', | |
142 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg|png)$', | |
143 | 'duration': 554.117, | |
144 | 'tags': list, | |
145 | 'comment_count': int, | |
146 | 'upload_date': '20170301', | |
147 | 'timestamp': 1488353834, | |
148 | 'like_count': int, | |
149 | 'view_count': int, | |
150 | }, | |
151 | }, { | |
152 | # old av URL version | |
06167fbb | 153 | 'url': 'http://www.bilibili.com/video/av1074402/', |
28746fbd | 154 | 'info_dict': { |
ad974876 | 155 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg)$', |
f8580bf0 | 156 | 'ext': 'mp4', |
f8580bf0 | 157 | 'uploader': '菊子桑', |
ad974876 L |
158 | 'uploader_id': '156160', |
159 | 'id': 'BV11x411K7CN', | |
160 | 'title': '【金坷垃】金泡沫', | |
161 | 'duration': 308.36, | |
f8580bf0 | 162 | 'upload_date': '20140420', |
ad974876 | 163 | 'timestamp': 1397983878, |
6461f2b7 | 164 | 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923', |
ad974876 L |
165 | 'like_count': int, |
166 | 'comment_count': int, | |
167 | 'view_count': int, | |
168 | 'tags': list, | |
169 | }, | |
c90c5b9b | 170 | 'params': {'skip_download': True}, |
bd8f48c7 | 171 | }, { |
ad974876 L |
172 | 'note': 'Anthology', |
173 | 'url': 'https://www.bilibili.com/video/BV1bK411W797', | |
174 | 'info_dict': { | |
175 | 'id': 'BV1bK411W797', | |
176 | 'title': '物语中的人物是如何吐槽自己的OP的' | |
177 | }, | |
178 | 'playlist_count': 18, | |
179 | 'playlist': [{ | |
180 | 'info_dict': { | |
181 | 'id': 'BV1bK411W797_p1', | |
182 | 'ext': 'mp4', | |
183 | 'title': '物语中的人物是如何吐槽自己的OP的 p01 Staple Stable/战场原+羽川', | |
184 | 'tags': 'count:11', | |
185 | 'timestamp': 1589601697, | |
186 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg|png)$', | |
187 | 'uploader': '打牌还是打桩', | |
188 | 'uploader_id': '150259984', | |
189 | 'like_count': int, | |
190 | 'comment_count': int, | |
191 | 'upload_date': '20200516', | |
192 | 'view_count': int, | |
193 | 'description': 'md5:e3c401cf7bc363118d1783dd74068a68', | |
194 | 'duration': 90.314, | |
195 | } | |
196 | }] | |
06167fbb | 197 | }, { |
ad974876 L |
198 | 'note': 'Specific page of Anthology', |
199 | 'url': 'https://www.bilibili.com/video/BV1bK411W797?p=1', | |
200 | 'info_dict': { | |
201 | 'id': 'BV1bK411W797_p1', | |
202 | 'ext': 'mp4', | |
203 | 'title': '物语中的人物是如何吐槽自己的OP的 p01 Staple Stable/战场原+羽川', | |
204 | 'tags': 'count:11', | |
205 | 'timestamp': 1589601697, | |
206 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg|png)$', | |
207 | 'uploader': '打牌还是打桩', | |
208 | 'uploader_id': '150259984', | |
209 | 'like_count': int, | |
210 | 'comment_count': int, | |
211 | 'upload_date': '20200516', | |
212 | 'view_count': int, | |
213 | 'description': 'md5:e3c401cf7bc363118d1783dd74068a68', | |
214 | 'duration': 90.314, | |
215 | } | |
bd8f48c7 | 216 | }, { |
ad974876 L |
217 | 'note': 'video has subtitles', |
218 | 'url': 'https://www.bilibili.com/video/BV12N4y1M7rh', | |
bd8f48c7 | 219 | 'info_dict': { |
ad974876 | 220 | 'id': 'BV12N4y1M7rh', |
bd8f48c7 | 221 | 'ext': 'mp4', |
c90c5b9b | 222 | 'title': 'md5:96e8bb42c2b432c0d4ce3434a61479c1', |
ad974876 L |
223 | 'tags': list, |
224 | 'description': 'md5:afde2b7ba9025c01d9e3dde10de221e4', | |
225 | 'duration': 313.557, | |
226 | 'upload_date': '20220709', | |
227 | 'uploader': '小夫Tech', | |
228 | 'timestamp': 1657347907, | |
229 | 'uploader_id': '1326814124', | |
230 | 'comment_count': int, | |
231 | 'view_count': int, | |
232 | 'like_count': int, | |
233 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg|png)$', | |
234 | 'subtitles': 'count:2' | |
bd8f48c7 | 235 | }, |
ad974876 | 236 | 'params': {'listsubtitles': True}, |
ca270371 | 237 | }, { |
ad974876 | 238 | 'url': 'https://www.bilibili.com/video/av8903802/', |
ca270371 | 239 | 'info_dict': { |
ad974876 | 240 | 'id': 'BV13x41117TL', |
f8580bf0 | 241 | 'ext': 'mp4', |
ca270371 | 242 | 'title': '阿滴英文|英文歌分享#6 "Closer', |
f8580bf0 | 243 | 'upload_date': '20170301', |
c90c5b9b | 244 | 'description': 'md5:3b1b9e25b78da4ef87e9b548b88ee76a', |
ad974876 | 245 | 'timestamp': 1488353834, |
f8580bf0 | 246 | 'uploader_id': '65880958', |
247 | 'uploader': '阿滴英文', | |
ad974876 | 248 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg|png)$', |
89fabf11 | 249 | 'duration': 554.117, |
ad974876 L |
250 | 'tags': list, |
251 | 'comment_count': int, | |
252 | 'view_count': int, | |
253 | 'like_count': int, | |
89fabf11 JN |
254 | }, |
255 | 'params': { | |
256 | 'skip_download': True, | |
257 | }, | |
c90c5b9b | 258 | }, { |
259 | 'note': 'video has chapter', | |
260 | 'url': 'https://www.bilibili.com/video/BV1vL411G7N7/', | |
261 | 'info_dict': { | |
262 | 'id': 'BV1vL411G7N7', | |
263 | 'ext': 'mp4', | |
264 | 'title': '如何为你的B站视频添加进度条分段', | |
265 | 'timestamp': 1634554558, | |
266 | 'upload_date': '20211018', | |
267 | 'description': 'md5:a9a3d6702b3a94518d419b2e9c320a6d', | |
268 | 'tags': list, | |
269 | 'uploader': '爱喝咖啡的当麻', | |
270 | 'duration': 669.482, | |
271 | 'uploader_id': '1680903', | |
272 | 'chapters': 'count:6', | |
273 | 'comment_count': int, | |
274 | 'view_count': int, | |
275 | 'like_count': int, | |
276 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg|png)$', | |
277 | }, | |
278 | 'params': {'skip_download': True}, | |
bd8f48c7 | 279 | }] |
28746fbd | 280 | |
520e7533 | 281 | def _real_extract(self, url): |
ad974876 | 282 | video_id = self._match_id(url) |
6461f2b7 | 283 | webpage = self._download_webpage(url, video_id) |
c90c5b9b | 284 | initial_state = self._search_json(r'window\.__INITIAL_STATE__\s*=', webpage, 'initial state', video_id) |
285 | play_info = self._search_json(r'window\.__playinfo__\s*=', webpage, 'play info', video_id)['data'] | |
ad974876 L |
286 | |
287 | video_data = initial_state['videoData'] | |
288 | video_id, title = video_data['bvid'], video_data.get('title') | |
6461f2b7 | 289 | |
adc74b3c | 290 | # Bilibili anthologies are similar to playlists but all videos share the same video ID as the anthology itself. |
ad974876 L |
291 | page_list_json = traverse_obj( |
292 | self._download_json( | |
293 | 'https://api.bilibili.com/x/player/pagelist', video_id, | |
294 | fatal=False, query={'bvid': video_id, 'jsonp': 'jsonp'}, | |
295 | note='Extracting videos in anthology'), | |
296 | 'data', expected_type=list) or [] | |
297 | is_anthology = len(page_list_json) > 1 | |
298 | ||
299 | part_id = int_or_none(parse_qs(url).get('p', [None])[-1]) | |
300 | if is_anthology and not part_id and self._yes_playlist(video_id, video_id): | |
301 | return self.playlist_from_matches( | |
302 | page_list_json, video_id, title, ie=BiliBiliIE, | |
303 | getter=lambda entry: f'https://www.bilibili.com/video/{video_id}?p={entry["page"]}') | |
10db0d2f | 304 | |
ad974876 L |
305 | if is_anthology: |
306 | title += f' p{part_id:02d} {traverse_obj(page_list_json, ((part_id or 1) - 1, "part")) or ""}' | |
f8580bf0 | 307 | |
ad974876 L |
308 | aid = video_data.get('aid') |
309 | old_video_id = format_field(aid, None, f'%s_part{part_id or 1}') | |
f8580bf0 | 310 | |
c90c5b9b | 311 | cid = traverse_obj(video_data, ('pages', part_id - 1, 'cid')) if part_id else video_data.get('cid') |
312 | ||
ad974876 L |
313 | return { |
314 | 'id': f'{video_id}{format_field(part_id, None, "_p%d")}', | |
315 | 'formats': self.extract_formats(play_info), | |
316 | '_old_archive_ids': [make_archive_id(self, old_video_id)] if old_video_id else None, | |
d90e4030 | 317 | 'title': title, |
c90c5b9b | 318 | 'description': traverse_obj(initial_state, ('videoData', 'desc')), |
319 | 'view_count': traverse_obj(initial_state, ('videoData', 'stat', 'view')), | |
320 | 'uploader': traverse_obj(initial_state, ('upData', 'name')), | |
321 | 'uploader_id': traverse_obj(initial_state, ('upData', 'mid')), | |
322 | 'like_count': traverse_obj(initial_state, ('videoData', 'stat', 'like')), | |
323 | 'comment_count': traverse_obj(initial_state, ('videoData', 'stat', 'reply')), | |
324 | 'tags': traverse_obj(initial_state, ('tags', ..., 'tag_name')), | |
325 | 'thumbnail': traverse_obj(initial_state, ('videoData', 'pic')), | |
326 | 'timestamp': traverse_obj(initial_state, ('videoData', 'pubdate')), | |
327 | 'duration': float_or_none(play_info.get('timelength'), scale=1000), | |
328 | 'chapters': self._get_chapters(aid, cid), | |
329 | 'subtitles': self.extract_subtitles(video_id, initial_state, cid), | |
330 | '__post_extractor': self.extract_comments(aid), | |
331 | 'http_headers': {'Referer': url}, | |
06167fbb | 332 | } |
277d6ff5 | 333 | |
06167fbb | 334 | |
ad974876 L |
335 | class BiliBiliBangumiIE(BilibiliBaseIE): |
336 | _VALID_URL = r'(?x)https?://www\.bilibili\.com/bangumi/play/(?P<id>(?:ss|ep)\d+)' | |
e88d44c6 | 337 | |
ad974876 L |
338 | _TESTS = [{ |
339 | 'url': 'https://www.bilibili.com/bangumi/play/ss897', | |
340 | 'info_dict': { | |
341 | 'id': 'ss897', | |
342 | 'ext': 'mp4', | |
343 | 'series': '神的记事本', | |
344 | 'season': '神的记事本', | |
345 | 'season_id': 897, | |
346 | 'season_number': 1, | |
347 | 'episode': '你与旅行包', | |
348 | 'episode_number': 2, | |
349 | 'title': '神的记事本:第2话 你与旅行包', | |
350 | 'duration': 1428.487, | |
351 | 'timestamp': 1310809380, | |
352 | 'upload_date': '20110716', | |
353 | 'thumbnail': r're:^https?://.*\.(jpg|jpeg|png)$', | |
354 | }, | |
355 | }, { | |
356 | 'url': 'https://www.bilibili.com/bangumi/play/ep508406', | |
357 | 'only_matching': True, | |
358 | }] | |
06167fbb | 359 | |
ad974876 L |
360 | def _real_extract(self, url): |
361 | video_id = self._match_id(url) | |
362 | webpage = self._download_webpage(url, video_id) | |
e88d44c6 | 363 | |
ad974876 L |
364 | if '您所在的地区无法观看本片' in webpage: |
365 | raise GeoRestrictedError('This video is restricted') | |
366 | elif ('开通大会员观看' in webpage and '__playinfo__' not in webpage | |
367 | or '正在观看预览,大会员免费看全片' in webpage): | |
368 | self.raise_login_required('This video is for premium members only') | |
6461f2b7 | 369 | |
46d09f87 | 370 | play_info = self._search_json(r'window\.__playinfo__\s*=', webpage, 'play info', video_id)['data'] |
ad974876 L |
371 | formats = self.extract_formats(play_info) |
372 | if (not formats and '成为大会员抢先看' in webpage | |
373 | and play_info.get('durl') and not play_info.get('dash')): | |
374 | self.raise_login_required('This video is for premium members only') | |
bd8f48c7 | 375 | |
c90c5b9b | 376 | initial_state = self._search_json(r'window\.__INITIAL_STATE__\s*=', webpage, 'initial state', video_id) |
377 | ||
378 | season_id = traverse_obj(initial_state, ('mediaInfo', 'season_id')) | |
379 | season_number = season_id and next(( | |
380 | idx + 1 for idx, e in enumerate( | |
381 | traverse_obj(initial_state, ('mediaInfo', 'seasons', ...))) | |
382 | if e.get('season_id') == season_id | |
383 | ), None) | |
06167fbb | 384 | |
e88d44c6 | 385 | return { |
ad974876 L |
386 | 'id': video_id, |
387 | 'formats': formats, | |
c90c5b9b | 388 | 'title': traverse_obj(initial_state, 'h1Title'), |
389 | 'episode': traverse_obj(initial_state, ('epInfo', 'long_title')), | |
390 | 'episode_number': int_or_none(traverse_obj(initial_state, ('epInfo', 'title'))), | |
391 | 'series': traverse_obj(initial_state, ('mediaInfo', 'series')), | |
392 | 'season': traverse_obj(initial_state, ('mediaInfo', 'season_title')), | |
393 | 'season_id': season_id, | |
394 | 'season_number': season_number, | |
395 | 'thumbnail': traverse_obj(initial_state, ('epInfo', 'cover')), | |
396 | 'timestamp': traverse_obj(initial_state, ('epInfo', 'pub_time')), | |
397 | 'duration': float_or_none(play_info.get('timelength'), scale=1000), | |
398 | 'subtitles': self.extract_subtitles( | |
399 | video_id, initial_state, traverse_obj(initial_state, ('epInfo', 'cid'))), | |
400 | '__post_extractor': self.extract_comments(traverse_obj(initial_state, ('epInfo', 'aid'))), | |
ad974876 | 401 | 'http_headers': {'Referer': url, **self.geo_verification_headers()}, |
e88d44c6 | 402 | } |
bd8f48c7 | 403 | |
bd8f48c7 | 404 | |
ad974876 L |
405 | class BiliBiliBangumiMediaIE(InfoExtractor): |
406 | _VALID_URL = r'https?://www\.bilibili\.com/bangumi/media/md(?P<id>\d+)' | |
bd8f48c7 | 407 | _TESTS = [{ |
ad974876 | 408 | 'url': 'https://www.bilibili.com/bangumi/media/md24097891', |
bd8f48c7 | 409 | 'info_dict': { |
ad974876 | 410 | 'id': '24097891', |
bd8f48c7 | 411 | }, |
ad974876 | 412 | 'playlist_mincount': 25, |
bd8f48c7 YCH |
413 | }] |
414 | ||
bd8f48c7 | 415 | def _real_extract(self, url): |
ad974876 L |
416 | media_id = self._match_id(url) |
417 | webpage = self._download_webpage(url, media_id) | |
bd8f48c7 | 418 | |
c90c5b9b | 419 | initial_state = self._search_json(r'window\.__INITIAL_STATE__\s*=', webpage, 'initial_state', media_id) |
ad974876 L |
420 | episode_list = self._download_json( |
421 | 'https://api.bilibili.com/pgc/web/season/section', media_id, | |
422 | query={'season_id': initial_state['mediaInfo']['season_id']}, | |
423 | note='Downloading season info')['result']['main_section']['episodes'] | |
bd8f48c7 | 424 | |
ad974876 L |
425 | return self.playlist_result(( |
426 | self.url_result(entry['share_url'], BiliBiliBangumiIE, entry['aid']) | |
427 | for entry in episode_list), media_id) | |
4bc15a68 RA |
428 | |
429 | ||
2b9d0216 L |
430 | class BilibiliSpaceBaseIE(InfoExtractor): |
431 | def _extract_playlist(self, fetch_page, get_metadata, get_entries): | |
12f153a8 | 432 | first_page = fetch_page(0) |
2b9d0216 L |
433 | metadata = get_metadata(first_page) |
434 | ||
435 | paged_list = InAdvancePagedList( | |
12f153a8 | 436 | lambda idx: get_entries(fetch_page(idx) if idx else first_page), |
2b9d0216 L |
437 | metadata['page_count'], metadata['page_size']) |
438 | ||
439 | return metadata, paged_list | |
440 | ||
441 | ||
442 | class BilibiliSpaceVideoIE(BilibiliSpaceBaseIE): | |
443 | _VALID_URL = r'https?://space\.bilibili\.com/(?P<id>\d+)(?P<video>/video)?/?(?:[?#]|$)' | |
6efb0711 | 444 | _TESTS = [{ |
445 | 'url': 'https://space.bilibili.com/3985676/video', | |
2b9d0216 L |
446 | 'info_dict': { |
447 | 'id': '3985676', | |
448 | }, | |
449 | 'playlist_mincount': 178, | |
6efb0711 | 450 | }] |
451 | ||
2b9d0216 L |
452 | def _real_extract(self, url): |
453 | playlist_id, is_video_url = self._match_valid_url(url).group('id', 'video') | |
454 | if not is_video_url: | |
455 | self.to_screen('A channel URL was given. Only the channel\'s videos will be downloaded. ' | |
456 | 'To download audios, add a "/audio" to the URL') | |
457 | ||
458 | def fetch_page(page_idx): | |
12f153a8 L |
459 | try: |
460 | response = self._download_json('https://api.bilibili.com/x/space/arc/search', | |
461 | playlist_id, note=f'Downloading page {page_idx}', | |
462 | query={'mid': playlist_id, 'pn': page_idx + 1, 'jsonp': 'jsonp'}) | |
463 | except ExtractorError as e: | |
464 | if isinstance(e.cause, urllib.error.HTTPError) and e.cause.code == 412: | |
465 | raise ExtractorError( | |
466 | 'Request is blocked by server (412), please add cookies, wait and try later.', expected=True) | |
467 | raise | |
468 | if response['code'] == -401: | |
469 | raise ExtractorError( | |
470 | 'Request is blocked by server (401), please add cookies, wait and try later.', expected=True) | |
471 | return response['data'] | |
2b9d0216 L |
472 | |
473 | def get_metadata(page_data): | |
474 | page_size = page_data['page']['ps'] | |
475 | entry_count = page_data['page']['count'] | |
476 | return { | |
477 | 'page_count': math.ceil(entry_count / page_size), | |
478 | 'page_size': page_size, | |
479 | } | |
6efb0711 | 480 | |
2b9d0216 L |
481 | def get_entries(page_data): |
482 | for entry in traverse_obj(page_data, ('list', 'vlist')) or []: | |
483 | yield self.url_result(f'https://www.bilibili.com/video/{entry["bvid"]}', BiliBiliIE, entry['bvid']) | |
6efb0711 | 484 | |
2b9d0216 L |
485 | metadata, paged_list = self._extract_playlist(fetch_page, get_metadata, get_entries) |
486 | return self.playlist_result(paged_list, playlist_id) | |
6efb0711 | 487 | |
6efb0711 | 488 | |
2b9d0216 L |
489 | class BilibiliSpaceAudioIE(BilibiliSpaceBaseIE): |
490 | _VALID_URL = r'https?://space\.bilibili\.com/(?P<id>\d+)/audio' | |
491 | _TESTS = [{ | |
492 | 'url': 'https://space.bilibili.com/3985676/audio', | |
493 | 'info_dict': { | |
494 | 'id': '3985676', | |
495 | }, | |
496 | 'playlist_mincount': 1, | |
497 | }] | |
498 | ||
499 | def _real_extract(self, url): | |
500 | playlist_id = self._match_id(url) | |
501 | ||
502 | def fetch_page(page_idx): | |
503 | return self._download_json( | |
504 | 'https://api.bilibili.com/audio/music-service/web/song/upper', playlist_id, | |
505 | note=f'Downloading page {page_idx}', | |
12f153a8 | 506 | query={'uid': playlist_id, 'pn': page_idx + 1, 'ps': 30, 'order': 1, 'jsonp': 'jsonp'})['data'] |
2b9d0216 L |
507 | |
508 | def get_metadata(page_data): | |
509 | return { | |
510 | 'page_count': page_data['pageCount'], | |
511 | 'page_size': page_data['pageSize'], | |
512 | } | |
513 | ||
514 | def get_entries(page_data): | |
515 | for entry in page_data.get('data', []): | |
516 | yield self.url_result(f'https://www.bilibili.com/audio/au{entry["id"]}', BilibiliAudioIE, entry['id']) | |
517 | ||
518 | metadata, paged_list = self._extract_playlist(fetch_page, get_metadata, get_entries) | |
519 | return self.playlist_result(paged_list, playlist_id) | |
520 | ||
521 | ||
522 | class BilibiliSpacePlaylistIE(BilibiliSpaceBaseIE): | |
523 | _VALID_URL = r'https?://space.bilibili\.com/(?P<mid>\d+)/channel/collectiondetail\?sid=(?P<sid>\d+)' | |
524 | _TESTS = [{ | |
525 | 'url': 'https://space.bilibili.com/2142762/channel/collectiondetail?sid=57445', | |
526 | 'info_dict': { | |
527 | 'id': '2142762_57445', | |
528 | 'title': '《底特律 变人》' | |
529 | }, | |
530 | 'playlist_mincount': 31, | |
531 | }] | |
06167fbb | 532 | |
533 | def _real_extract(self, url): | |
2b9d0216 L |
534 | mid, sid = self._match_valid_url(url).group('mid', 'sid') |
535 | playlist_id = f'{mid}_{sid}' | |
536 | ||
537 | def fetch_page(page_idx): | |
538 | return self._download_json( | |
539 | 'https://api.bilibili.com/x/polymer/space/seasons_archives_list', | |
540 | playlist_id, note=f'Downloading page {page_idx}', | |
12f153a8 | 541 | query={'mid': mid, 'season_id': sid, 'page_num': page_idx + 1, 'page_size': 30})['data'] |
2b9d0216 L |
542 | |
543 | def get_metadata(page_data): | |
544 | page_size = page_data['page']['page_size'] | |
545 | entry_count = page_data['page']['total'] | |
546 | return { | |
547 | 'page_count': math.ceil(entry_count / page_size), | |
548 | 'page_size': page_size, | |
549 | 'title': traverse_obj(page_data, ('meta', 'name')) | |
550 | } | |
551 | ||
552 | def get_entries(page_data): | |
553 | for entry in page_data.get('archives', []): | |
554 | yield self.url_result(f'https://www.bilibili.com/video/{entry["bvid"]}', | |
555 | BiliBiliIE, entry['bvid']) | |
556 | ||
557 | metadata, paged_list = self._extract_playlist(fetch_page, get_metadata, get_entries) | |
558 | return self.playlist_result(paged_list, playlist_id, metadata['title']) | |
06167fbb | 559 | |
560 | ||
c34f505b | 561 | class BilibiliCategoryIE(InfoExtractor): |
562 | IE_NAME = 'Bilibili category extractor' | |
563 | _MAX_RESULTS = 1000000 | |
564 | _VALID_URL = r'https?://www\.bilibili\.com/v/[a-zA-Z]+\/[a-zA-Z]+' | |
565 | _TESTS = [{ | |
566 | 'url': 'https://www.bilibili.com/v/kichiku/mad', | |
567 | 'info_dict': { | |
568 | 'id': 'kichiku: mad', | |
569 | 'title': 'kichiku: mad' | |
570 | }, | |
571 | 'playlist_mincount': 45, | |
572 | 'params': { | |
573 | 'playlistend': 45 | |
574 | } | |
575 | }] | |
576 | ||
577 | def _fetch_page(self, api_url, num_pages, query, page_num): | |
578 | parsed_json = self._download_json( | |
579 | api_url, query, query={'Search_key': query, 'pn': page_num}, | |
580 | note='Extracting results from page %s of %s' % (page_num, num_pages)) | |
581 | ||
f8580bf0 | 582 | video_list = traverse_obj(parsed_json, ('data', 'archives'), expected_type=list) |
c34f505b | 583 | if not video_list: |
584 | raise ExtractorError('Failed to retrieve video list for page %d' % page_num) | |
585 | ||
586 | for video in video_list: | |
587 | yield self.url_result( | |
588 | 'https://www.bilibili.com/video/%s' % video['bvid'], 'BiliBili', video['bvid']) | |
589 | ||
590 | def _entries(self, category, subcategory, query): | |
591 | # map of categories : subcategories : RIDs | |
592 | rid_map = { | |
593 | 'kichiku': { | |
594 | 'mad': 26, | |
595 | 'manual_vocaloid': 126, | |
596 | 'guide': 22, | |
597 | 'theatre': 216, | |
598 | 'course': 127 | |
599 | }, | |
600 | } | |
601 | ||
602 | if category not in rid_map: | |
e88d44c6 | 603 | raise ExtractorError( |
604 | f'The category {category} isn\'t supported. Supported categories: {list(rid_map.keys())}') | |
c34f505b | 605 | if subcategory not in rid_map[category]: |
e88d44c6 | 606 | raise ExtractorError( |
607 | f'The subcategory {subcategory} isn\'t supported for this category. Supported subcategories: {list(rid_map[category].keys())}') | |
c34f505b | 608 | rid_value = rid_map[category][subcategory] |
609 | ||
610 | api_url = 'https://api.bilibili.com/x/web-interface/newlist?rid=%d&type=1&ps=20&jsonp=jsonp' % rid_value | |
611 | page_json = self._download_json(api_url, query, query={'Search_key': query, 'pn': '1'}) | |
f8580bf0 | 612 | page_data = traverse_obj(page_json, ('data', 'page'), expected_type=dict) |
c34f505b | 613 | count, size = int_or_none(page_data.get('count')), int_or_none(page_data.get('size')) |
614 | if count is None or not size: | |
615 | raise ExtractorError('Failed to calculate either page count or size') | |
616 | ||
617 | num_pages = math.ceil(count / size) | |
618 | ||
619 | return OnDemandPagedList(functools.partial( | |
620 | self._fetch_page, api_url, num_pages, query), size) | |
621 | ||
622 | def _real_extract(self, url): | |
ad974876 | 623 | category, subcategory = urllib.parse.urlparse(url).path.split('/')[2:4] |
c34f505b | 624 | query = '%s: %s' % (category, subcategory) |
625 | ||
626 | return self.playlist_result(self._entries(category, subcategory, query), query, query) | |
627 | ||
628 | ||
06167fbb | 629 | class BiliBiliSearchIE(SearchInfoExtractor): |
96565c7e | 630 | IE_DESC = 'Bilibili video search' |
06167fbb | 631 | _MAX_RESULTS = 100000 |
632 | _SEARCH_KEY = 'bilisearch' | |
06167fbb | 633 | |
e88d44c6 | 634 | def _search_results(self, query): |
635 | for page_num in itertools.count(1): | |
636 | videos = self._download_json( | |
637 | 'https://api.bilibili.com/x/web-interface/search/type', query, | |
638 | note=f'Extracting results from page {page_num}', query={ | |
639 | 'Search_key': query, | |
640 | 'keyword': query, | |
641 | 'page': page_num, | |
642 | 'context': '', | |
e88d44c6 | 643 | 'duration': 0, |
644 | 'tids_2': '', | |
645 | '__refresh__': 'true', | |
646 | 'search_type': 'video', | |
647 | 'tids': 0, | |
648 | 'highlight': 1, | |
2d101954 | 649 | })['data'].get('result') |
650 | if not videos: | |
651 | break | |
06167fbb | 652 | for video in videos: |
e88d44c6 | 653 | yield self.url_result(video['arcurl'], 'BiliBili', str(video['aid'])) |
06167fbb | 654 | |
655 | ||
4bc15a68 RA |
656 | class BilibiliAudioBaseIE(InfoExtractor): |
657 | def _call_api(self, path, sid, query=None): | |
658 | if not query: | |
659 | query = {'sid': sid} | |
660 | return self._download_json( | |
661 | 'https://www.bilibili.com/audio/music-service-c/web/' + path, | |
662 | sid, query=query)['data'] | |
663 | ||
664 | ||
665 | class BilibiliAudioIE(BilibiliAudioBaseIE): | |
666 | _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/au(?P<id>\d+)' | |
667 | _TEST = { | |
668 | 'url': 'https://www.bilibili.com/audio/au1003142', | |
669 | 'md5': 'fec4987014ec94ef9e666d4d158ad03b', | |
670 | 'info_dict': { | |
671 | 'id': '1003142', | |
672 | 'ext': 'm4a', | |
673 | 'title': '【tsukimi】YELLOW / 神山羊', | |
674 | 'artist': 'tsukimi', | |
675 | 'comment_count': int, | |
676 | 'description': 'YELLOW的mp3版!', | |
677 | 'duration': 183, | |
678 | 'subtitles': { | |
679 | 'origin': [{ | |
680 | 'ext': 'lrc', | |
681 | }], | |
682 | }, | |
683 | 'thumbnail': r're:^https?://.+\.jpg', | |
684 | 'timestamp': 1564836614, | |
685 | 'upload_date': '20190803', | |
686 | 'uploader': 'tsukimi-つきみぐー', | |
687 | 'view_count': int, | |
688 | }, | |
689 | } | |
690 | ||
691 | def _real_extract(self, url): | |
692 | au_id = self._match_id(url) | |
693 | ||
694 | play_data = self._call_api('url', au_id) | |
695 | formats = [{ | |
696 | 'url': play_data['cdns'][0], | |
697 | 'filesize': int_or_none(play_data.get('size')), | |
f0884c8b | 698 | 'vcodec': 'none' |
4bc15a68 RA |
699 | }] |
700 | ||
6d1b3489 | 701 | for a_format in formats: |
702 | a_format.setdefault('http_headers', {}).update({ | |
703 | 'Referer': url, | |
704 | }) | |
705 | ||
4bc15a68 RA |
706 | song = self._call_api('song/info', au_id) |
707 | title = song['title'] | |
708 | statistic = song.get('statistic') or {} | |
709 | ||
710 | subtitles = None | |
711 | lyric = song.get('lyric') | |
712 | if lyric: | |
713 | subtitles = { | |
714 | 'origin': [{ | |
715 | 'url': lyric, | |
716 | }] | |
717 | } | |
718 | ||
719 | return { | |
720 | 'id': au_id, | |
721 | 'title': title, | |
722 | 'formats': formats, | |
723 | 'artist': song.get('author'), | |
724 | 'comment_count': int_or_none(statistic.get('comment')), | |
725 | 'description': song.get('intro'), | |
726 | 'duration': int_or_none(song.get('duration')), | |
727 | 'subtitles': subtitles, | |
728 | 'thumbnail': song.get('cover'), | |
729 | 'timestamp': int_or_none(song.get('passtime')), | |
730 | 'uploader': song.get('uname'), | |
731 | 'view_count': int_or_none(statistic.get('play')), | |
732 | } | |
733 | ||
734 | ||
735 | class BilibiliAudioAlbumIE(BilibiliAudioBaseIE): | |
736 | _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/am(?P<id>\d+)' | |
737 | _TEST = { | |
738 | 'url': 'https://www.bilibili.com/audio/am10624', | |
739 | 'info_dict': { | |
740 | 'id': '10624', | |
741 | 'title': '每日新曲推荐(每日11:00更新)', | |
742 | 'description': '每天11:00更新,为你推送最新音乐', | |
743 | }, | |
744 | 'playlist_count': 19, | |
745 | } | |
746 | ||
747 | def _real_extract(self, url): | |
748 | am_id = self._match_id(url) | |
749 | ||
750 | songs = self._call_api( | |
751 | 'song/of-menu', am_id, {'sid': am_id, 'pn': 1, 'ps': 100})['data'] | |
752 | ||
753 | entries = [] | |
754 | for song in songs: | |
755 | sid = str_or_none(song.get('id')) | |
756 | if not sid: | |
757 | continue | |
758 | entries.append(self.url_result( | |
759 | 'https://www.bilibili.com/audio/au' + sid, | |
760 | BilibiliAudioIE.ie_key(), sid)) | |
761 | ||
762 | if entries: | |
763 | album_data = self._call_api('menu/info', am_id) or {} | |
764 | album_title = album_data.get('title') | |
765 | if album_title: | |
766 | for entry in entries: | |
767 | entry['album'] = album_title | |
768 | return self.playlist_result( | |
769 | entries, am_id, album_title, album_data.get('intro')) | |
770 | ||
771 | return self.playlist_result(entries, am_id) | |
63dce309 S |
772 | |
773 | ||
774 | class BiliBiliPlayerIE(InfoExtractor): | |
775 | _VALID_URL = r'https?://player\.bilibili\.com/player\.html\?.*?\baid=(?P<id>\d+)' | |
776 | _TEST = { | |
777 | 'url': 'http://player.bilibili.com/player.html?aid=92494333&cid=157926707&page=1', | |
778 | 'only_matching': True, | |
779 | } | |
780 | ||
781 | def _real_extract(self, url): | |
782 | video_id = self._match_id(url) | |
783 | return self.url_result( | |
784 | 'http://www.bilibili.tv/video/av%s/' % video_id, | |
785 | ie=BiliBiliIE.ie_key(), video_id=video_id) | |
16f7e6be AG |
786 | |
787 | ||
788 | class BiliIntlBaseIE(InfoExtractor): | |
c62ecf0d | 789 | _API_URL = 'https://api.bilibili.tv/intl/gateway' |
cfcf60ea | 790 | _NETRC_MACHINE = 'biliintl' |
16f7e6be | 791 | |
c62ecf0d | 792 | def _call_api(self, endpoint, *args, **kwargs): |
cfcf60ea M |
793 | json = self._download_json(self._API_URL + endpoint, *args, **kwargs) |
794 | if json.get('code'): | |
795 | if json['code'] in (10004004, 10004005, 10023006): | |
796 | self.raise_login_required() | |
797 | elif json['code'] == 10004001: | |
798 | self.raise_geo_restricted() | |
799 | else: | |
800 | if json.get('message') and str(json['code']) != json['message']: | |
801 | errmsg = f'{kwargs.get("errnote", "Unable to download JSON metadata")}: {self.IE_NAME} said: {json["message"]}' | |
802 | else: | |
803 | errmsg = kwargs.get('errnote', 'Unable to download JSON metadata') | |
804 | if kwargs.get('fatal'): | |
805 | raise ExtractorError(errmsg) | |
806 | else: | |
807 | self.report_warning(errmsg) | |
808 | return json.get('data') | |
16f7e6be | 809 | |
efc947fb | 810 | def json2srt(self, json): |
811 | data = '\n\n'.join( | |
812 | f'{i + 1}\n{srt_subtitles_timecode(line["from"])} --> {srt_subtitles_timecode(line["to"])}\n{line["content"]}' | |
dfb855b4 | 813 | for i, line in enumerate(traverse_obj(json, ( |
814 | 'body', lambda _, l: l['content'] and l['from'] and l['to'])))) | |
efc947fb | 815 | return data |
816 | ||
f5f15c99 LR |
817 | def _get_subtitles(self, *, ep_id=None, aid=None): |
818 | sub_json = self._call_api( | |
fbb888a3 | 819 | '/web/v2/subtitle', ep_id or aid, fatal=False, |
820 | note='Downloading subtitles list', errnote='Unable to download subtitles list', | |
821 | query=filter_dict({ | |
f5f15c99 | 822 | 'platform': 'web', |
fbb888a3 | 823 | 's_locale': 'en_US', |
f5f15c99 LR |
824 | 'episode_id': ep_id, |
825 | 'aid': aid, | |
fbb888a3 | 826 | })) or {} |
16f7e6be | 827 | subtitles = {} |
c62ecf0d | 828 | for sub in sub_json.get('subtitles') or []: |
16f7e6be AG |
829 | sub_url = sub.get('url') |
830 | if not sub_url: | |
831 | continue | |
c62ecf0d | 832 | sub_data = self._download_json( |
f5f15c99 | 833 | sub_url, ep_id or aid, errnote='Unable to download subtitles', fatal=False, |
c62ecf0d | 834 | note='Downloading subtitles%s' % f' for {sub["lang"]}' if sub.get('lang') else '') |
efc947fb | 835 | if not sub_data: |
836 | continue | |
c62ecf0d | 837 | subtitles.setdefault(sub.get('lang_key', 'en'), []).append({ |
efc947fb | 838 | 'ext': 'srt', |
839 | 'data': self.json2srt(sub_data) | |
16f7e6be AG |
840 | }) |
841 | return subtitles | |
842 | ||
f5f15c99 LR |
843 | def _get_formats(self, *, ep_id=None, aid=None): |
844 | video_json = self._call_api( | |
845 | '/web/playurl', ep_id or aid, note='Downloading video formats', | |
846 | errnote='Unable to download video formats', query=filter_dict({ | |
847 | 'platform': 'web', | |
848 | 'ep_id': ep_id, | |
849 | 'aid': aid, | |
850 | })) | |
16f7e6be AG |
851 | video_json = video_json['playurl'] |
852 | formats = [] | |
c62ecf0d | 853 | for vid in video_json.get('video') or []: |
16f7e6be AG |
854 | video_res = vid.get('video_resource') or {} |
855 | video_info = vid.get('stream_info') or {} | |
856 | if not video_res.get('url'): | |
857 | continue | |
858 | formats.append({ | |
859 | 'url': video_res['url'], | |
860 | 'ext': 'mp4', | |
861 | 'format_note': video_info.get('desc_words'), | |
862 | 'width': video_res.get('width'), | |
863 | 'height': video_res.get('height'), | |
864 | 'vbr': video_res.get('bandwidth'), | |
865 | 'acodec': 'none', | |
866 | 'vcodec': video_res.get('codecs'), | |
867 | 'filesize': video_res.get('size'), | |
868 | }) | |
c62ecf0d | 869 | for aud in video_json.get('audio_resource') or []: |
16f7e6be AG |
870 | if not aud.get('url'): |
871 | continue | |
872 | formats.append({ | |
873 | 'url': aud['url'], | |
874 | 'ext': 'mp4', | |
875 | 'abr': aud.get('bandwidth'), | |
876 | 'acodec': aud.get('codecs'), | |
877 | 'vcodec': 'none', | |
878 | 'filesize': aud.get('size'), | |
879 | }) | |
880 | ||
16f7e6be AG |
881 | return formats |
882 | ||
f5f15c99 | 883 | def _extract_video_info(self, video_data, *, ep_id=None, aid=None): |
16f7e6be | 884 | return { |
f5f15c99 LR |
885 | 'id': ep_id or aid, |
886 | 'title': video_data.get('title_display') or video_data.get('title'), | |
887 | 'thumbnail': video_data.get('cover'), | |
c62ecf0d | 888 | 'episode_number': int_or_none(self._search_regex( |
f5f15c99 LR |
889 | r'^E(\d+)(?:$| - )', video_data.get('title_display') or '', 'episode number', default=None)), |
890 | 'formats': self._get_formats(ep_id=ep_id, aid=aid), | |
891 | 'subtitles': self._get_subtitles(ep_id=ep_id, aid=aid), | |
16f7e6be AG |
892 | 'extractor_key': BiliIntlIE.ie_key(), |
893 | } | |
894 | ||
52efa4b3 | 895 | def _perform_login(self, username, password): |
cfcf60ea M |
896 | try: |
897 | from Cryptodome.PublicKey import RSA | |
898 | from Cryptodome.Cipher import PKCS1_v1_5 | |
899 | except ImportError: | |
900 | try: | |
901 | from Crypto.PublicKey import RSA | |
902 | from Crypto.Cipher import PKCS1_v1_5 | |
903 | except ImportError: | |
904 | raise ExtractorError('pycryptodomex not found. Please install', expected=True) | |
905 | ||
906 | key_data = self._download_json( | |
907 | 'https://passport.bilibili.tv/x/intl/passport-login/web/key?lang=en-US', None, | |
908 | note='Downloading login key', errnote='Unable to download login key')['data'] | |
909 | ||
910 | public_key = RSA.importKey(key_data['key']) | |
911 | password_hash = PKCS1_v1_5.new(public_key).encrypt((key_data['hash'] + password).encode('utf-8')) | |
912 | login_post = self._download_json( | |
913 | 'https://passport.bilibili.tv/x/intl/passport-login/web/login/password?lang=en-US', None, data=urlencode_postdata({ | |
914 | 'username': username, | |
915 | 'password': base64.b64encode(password_hash).decode('ascii'), | |
916 | 'keep_me': 'true', | |
917 | 's_locale': 'en_US', | |
918 | 'isTrusted': 'true' | |
919 | }), note='Logging in', errnote='Unable to log in') | |
920 | if login_post.get('code'): | |
921 | if login_post.get('message'): | |
922 | raise ExtractorError(f'Unable to log in: {self.IE_NAME} said: {login_post["message"]}', expected=True) | |
923 | else: | |
924 | raise ExtractorError('Unable to log in') | |
925 | ||
16f7e6be AG |
926 | |
927 | class BiliIntlIE(BiliIntlBaseIE): | |
0831d95c | 928 | _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 | 929 | _TESTS = [{ |
cfcf60ea | 930 | # Bstation page |
16f7e6be AG |
931 | 'url': 'https://www.bilibili.tv/en/play/34613/341736', |
932 | 'info_dict': { | |
933 | 'id': '341736', | |
934 | 'ext': 'mp4', | |
c62ecf0d M |
935 | 'title': 'E2 - The First Night', |
936 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
16f7e6be | 937 | 'episode_number': 2, |
c62ecf0d | 938 | } |
16f7e6be | 939 | }, { |
cfcf60ea | 940 | # Non-Bstation page |
c62ecf0d | 941 | 'url': 'https://www.bilibili.tv/en/play/1033760/11005006', |
16f7e6be | 942 | 'info_dict': { |
c62ecf0d | 943 | 'id': '11005006', |
16f7e6be | 944 | 'ext': 'mp4', |
c62ecf0d M |
945 | 'title': 'E3 - Who?', |
946 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
947 | 'episode_number': 3, | |
948 | } | |
cfcf60ea M |
949 | }, { |
950 | # Subtitle with empty content | |
951 | 'url': 'https://www.bilibili.tv/en/play/1005144/10131790', | |
952 | 'info_dict': { | |
953 | 'id': '10131790', | |
954 | 'ext': 'mp4', | |
955 | 'title': 'E140 - Two Heartbeats: Kabuto\'s Trap', | |
956 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
957 | 'episode_number': 140, | |
958 | }, | |
959 | 'skip': 'According to the copyright owner\'s request, you may only watch the video after you log in.' | |
c62ecf0d M |
960 | }, { |
961 | 'url': 'https://www.biliintl.com/en/play/34613/341736', | |
962 | 'only_matching': True, | |
f5f15c99 LR |
963 | }, { |
964 | # User-generated content (as opposed to a series licensed from a studio) | |
965 | 'url': 'https://bilibili.tv/en/video/2019955076', | |
966 | 'only_matching': True, | |
967 | }, { | |
968 | # No language in URL | |
969 | 'url': 'https://www.bilibili.tv/video/2019955076', | |
970 | 'only_matching': True, | |
0831d95c | 971 | }, { |
972 | # Uppercase language in URL | |
973 | 'url': 'https://www.bilibili.tv/EN/video/2019955076', | |
974 | 'only_matching': True, | |
16f7e6be AG |
975 | }] |
976 | ||
977 | def _real_extract(self, url): | |
f5f15c99 LR |
978 | season_id, ep_id, aid = self._match_valid_url(url).group('season_id', 'ep_id', 'aid') |
979 | video_id = ep_id or aid | |
c62ecf0d M |
980 | webpage = self._download_webpage(url, video_id) |
981 | # Bstation layout | |
8072ef2b | 982 | initial_data = ( |
983 | self._search_json(r'window\.__INITIAL_(?:DATA|STATE)__\s*=', webpage, 'preload state', video_id, default={}) | |
984 | or self._search_nuxt_data(webpage, video_id, '__initialState', fatal=False, traverse=None)) | |
985 | video_data = traverse_obj( | |
986 | initial_data, ('OgvVideo', 'epDetail'), ('UgcVideo', 'videoData'), ('ugc', 'archive'), expected_type=dict) | |
c62ecf0d | 987 | |
f5f15c99 | 988 | if season_id and not video_data: |
c62ecf0d M |
989 | # Non-Bstation layout, read through episode list |
990 | season_json = self._call_api(f'/web/v2/ogv/play/episodes?season_id={season_id}&platform=web', video_id) | |
a44ca5a4 | 991 | video_data = traverse_obj(season_json, |
992 | ('sections', ..., 'episodes', lambda _, v: str(v['episode_id']) == ep_id), | |
993 | expected_type=dict, get_all=False) | |
8072ef2b | 994 | return self._extract_video_info(video_data or {}, ep_id=ep_id, aid=aid) |
16f7e6be AG |
995 | |
996 | ||
997 | class BiliIntlSeriesIE(BiliIntlBaseIE): | |
0831d95c | 998 | _VALID_URL = r'https?://(?:www\.)?bili(?:bili\.tv|intl\.com)/(?:[a-zA-Z]{2}/)?play/(?P<id>\d+)/?(?:[?#]|$)' |
16f7e6be AG |
999 | _TESTS = [{ |
1000 | 'url': 'https://www.bilibili.tv/en/play/34613', | |
1001 | 'playlist_mincount': 15, | |
1002 | 'info_dict': { | |
1003 | 'id': '34613', | |
c62ecf0d M |
1004 | 'title': 'Fly Me to the Moon', |
1005 | 'description': 'md5:a861ee1c4dc0acfad85f557cc42ac627', | |
1006 | 'categories': ['Romance', 'Comedy', 'Slice of life'], | |
1007 | 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$', | |
1008 | 'view_count': int, | |
16f7e6be AG |
1009 | }, |
1010 | 'params': { | |
1011 | 'skip_download': True, | |
16f7e6be AG |
1012 | }, |
1013 | }, { | |
1014 | 'url': 'https://www.biliintl.com/en/play/34613', | |
c62ecf0d | 1015 | 'only_matching': True, |
0831d95c | 1016 | }, { |
1017 | 'url': 'https://www.biliintl.com/EN/play/34613', | |
1018 | 'only_matching': True, | |
16f7e6be AG |
1019 | }] |
1020 | ||
c62ecf0d M |
1021 | def _entries(self, series_id): |
1022 | series_json = self._call_api(f'/web/v2/ogv/play/episodes?season_id={series_id}&platform=web', series_id) | |
1023 | for episode in traverse_obj(series_json, ('sections', ..., 'episodes', ...), expected_type=dict, default=[]): | |
1024 | episode_id = str(episode.get('episode_id')) | |
f5f15c99 | 1025 | yield self._extract_video_info(episode, ep_id=episode_id) |
16f7e6be AG |
1026 | |
1027 | def _real_extract(self, url): | |
c62ecf0d M |
1028 | series_id = self._match_id(url) |
1029 | series_info = self._call_api(f'/web/v2/ogv/play/season_info?season_id={series_id}&platform=web', series_id).get('season') or {} | |
1030 | return self.playlist_result( | |
1031 | self._entries(series_id), series_id, series_info.get('title'), series_info.get('description'), | |
1032 | categories=traverse_obj(series_info, ('styles', ..., 'title'), expected_type=str_or_none), | |
1033 | thumbnail=url_or_none(series_info.get('horizontal_cover')), view_count=parse_count(series_info.get('view'))) | |
b4f53662 H |
1034 | |
1035 | ||
1036 | class BiliLiveIE(InfoExtractor): | |
1037 | _VALID_URL = r'https?://live.bilibili.com/(?P<id>\d+)' | |
1038 | ||
1039 | _TESTS = [{ | |
1040 | 'url': 'https://live.bilibili.com/196', | |
1041 | 'info_dict': { | |
1042 | 'id': '33989', | |
1043 | 'description': "周六杂谈回,其他时候随机游戏。 | \n录播:@下播型泛式录播组。 | \n直播通知群(全员禁言):666906670,902092584,59971⑧481 (功能一样,别多加)", | |
1044 | 'ext': 'flv', | |
1045 | 'title': "太空狼人杀联动,不被爆杀就算赢", | |
1046 | 'thumbnail': "https://i0.hdslb.com/bfs/live/new_room_cover/e607bc1529057ef4b332e1026e62cf46984c314d.jpg", | |
1047 | 'timestamp': 1650802769, | |
1048 | }, | |
1049 | 'skip': 'not live' | |
1050 | }, { | |
1051 | 'url': 'https://live.bilibili.com/196?broadcast_type=0&is_room_feed=1?spm_id_from=333.999.space_home.strengthen_live_card.click', | |
1052 | 'only_matching': True | |
1053 | }] | |
1054 | ||
1055 | _FORMATS = { | |
1056 | 80: {'format_id': 'low', 'format_note': '流畅'}, | |
1057 | 150: {'format_id': 'high_res', 'format_note': '高清'}, | |
1058 | 250: {'format_id': 'ultra_high_res', 'format_note': '超清'}, | |
1059 | 400: {'format_id': 'blue_ray', 'format_note': '蓝光'}, | |
1060 | 10000: {'format_id': 'source', 'format_note': '原画'}, | |
1061 | 20000: {'format_id': '4K', 'format_note': '4K'}, | |
1062 | 30000: {'format_id': 'dolby', 'format_note': '杜比'}, | |
1063 | } | |
1064 | ||
1065 | _quality = staticmethod(qualities(list(_FORMATS))) | |
1066 | ||
1067 | def _call_api(self, path, room_id, query): | |
1068 | api_result = self._download_json(f'https://api.live.bilibili.com/{path}', room_id, query=query) | |
1069 | if api_result.get('code') != 0: | |
1070 | raise ExtractorError(api_result.get('message') or 'Unable to download JSON metadata') | |
1071 | return api_result.get('data') or {} | |
1072 | ||
1073 | def _parse_formats(self, qn, fmt): | |
1074 | for codec in fmt.get('codec') or []: | |
1075 | if codec.get('current_qn') != qn: | |
1076 | continue | |
1077 | for url_info in codec['url_info']: | |
1078 | yield { | |
1079 | 'url': f'{url_info["host"]}{codec["base_url"]}{url_info["extra"]}', | |
1080 | 'ext': fmt.get('format_name'), | |
1081 | 'vcodec': codec.get('codec_name'), | |
1082 | 'quality': self._quality(qn), | |
1083 | **self._FORMATS[qn], | |
1084 | } | |
1085 | ||
1086 | def _real_extract(self, url): | |
1087 | room_id = self._match_id(url) | |
1088 | room_data = self._call_api('room/v1/Room/get_info', room_id, {'id': room_id}) | |
1089 | if room_data.get('live_status') == 0: | |
1090 | raise ExtractorError('Streamer is not live', expected=True) | |
1091 | ||
1092 | formats = [] | |
1093 | for qn in self._FORMATS.keys(): | |
1094 | stream_data = self._call_api('xlive/web-room/v2/index/getRoomPlayInfo', room_id, { | |
1095 | 'room_id': room_id, | |
1096 | 'qn': qn, | |
1097 | 'codec': '0,1', | |
1098 | 'format': '0,2', | |
1099 | 'mask': '0', | |
1100 | 'no_playurl': '0', | |
1101 | 'platform': 'web', | |
1102 | 'protocol': '0,1', | |
1103 | }) | |
1104 | for fmt in traverse_obj(stream_data, ('playurl_info', 'playurl', 'stream', ..., 'format', ...)) or []: | |
1105 | formats.extend(self._parse_formats(qn, fmt)) | |
b4f53662 H |
1106 | |
1107 | return { | |
1108 | 'id': room_id, | |
1109 | 'title': room_data.get('title'), | |
1110 | 'description': room_data.get('description'), | |
1111 | 'thumbnail': room_data.get('user_cover'), | |
1112 | 'timestamp': stream_data.get('live_time'), | |
1113 | 'formats': formats, | |
1114 | 'http_headers': { | |
1115 | 'Referer': url, | |
1116 | }, | |
1117 | } |