bilibili.py 45 KB

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