bilibili.py 43 KB

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