logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

bilibili.py (16761B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import hashlib
  4. import re
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_parse_qs,
  8. compat_urlparse,
  9. )
  10. from ..utils import (
  11. ExtractorError,
  12. int_or_none,
  13. float_or_none,
  14. parse_iso8601,
  15. smuggle_url,
  16. str_or_none,
  17. strip_jsonp,
  18. unified_timestamp,
  19. unsmuggle_url,
  20. urlencode_postdata,
  21. )
  22. class BiliBiliIE(InfoExtractor):
  23. _VALID_URL = r'''(?x)
  24. https?://
  25. (?:(?:www|bangumi)\.)?
  26. bilibili\.(?:tv|com)/
  27. (?:
  28. (?:
  29. video/[aA][vV]|
  30. anime/(?P<anime_id>\d+)/play\#
  31. )(?P<id_bv>\d+)|
  32. video/[bB][vV](?P<id>[^/?#&]+)
  33. )
  34. '''
  35. _TESTS = [{
  36. 'url': 'http://www.bilibili.tv/video/av1074402/',
  37. 'md5': '5f7d29e1a2872f3df0cf76b1f87d3788',
  38. 'info_dict': {
  39. 'id': '1074402',
  40. 'ext': 'flv',
  41. 'title': '【金坷垃】金泡沫',
  42. 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
  43. 'duration': 308.067,
  44. 'timestamp': 1398012678,
  45. 'upload_date': '20140420',
  46. 'thumbnail': r're:^https?://.+\.jpg',
  47. 'uploader': '菊子桑',
  48. 'uploader_id': '156160',
  49. },
  50. }, {
  51. # Tested in BiliBiliBangumiIE
  52. 'url': 'http://bangumi.bilibili.com/anime/1869/play#40062',
  53. 'only_matching': True,
  54. }, {
  55. 'url': 'http://bangumi.bilibili.com/anime/5802/play#100643',
  56. 'md5': '3f721ad1e75030cc06faf73587cfec57',
  57. 'info_dict': {
  58. 'id': '100643',
  59. 'ext': 'mp4',
  60. 'title': 'CHAOS;CHILD',
  61. 'description': '如果你是神明,并且能够让妄想成为现实。那你会进行怎么样的妄想?是淫靡的世界?独裁社会?毁灭性的制裁?还是……2015年,涩谷。从6年前发生的大灾害“涩谷地震”之后复兴了的这个街区里新设立的私立高中...',
  62. },
  63. 'skip': 'Geo-restricted to China',
  64. }, {
  65. # Title with double quotes
  66. 'url': 'http://www.bilibili.com/video/av8903802/',
  67. 'info_dict': {
  68. 'id': '8903802',
  69. 'title': '阿滴英文|英文歌分享#6 "Closer',
  70. 'description': '滴妹今天唱Closer給你聽! 有史以来,被推最多次也是最久的歌曲,其实歌词跟我原本想像差蛮多的,不过还是好听! 微博@阿滴英文',
  71. },
  72. 'playlist': [{
  73. 'info_dict': {
  74. 'id': '8903802_part1',
  75. 'ext': 'flv',
  76. 'title': '阿滴英文|英文歌分享#6 "Closer',
  77. 'description': 'md5:3b1b9e25b78da4ef87e9b548b88ee76a',
  78. 'uploader': '阿滴英文',
  79. 'uploader_id': '65880958',
  80. 'timestamp': 1488382634,
  81. 'upload_date': '20170301',
  82. },
  83. 'params': {
  84. 'skip_download': True, # Test metadata only
  85. },
  86. }, {
  87. 'info_dict': {
  88. 'id': '8903802_part2',
  89. 'ext': 'flv',
  90. 'title': '阿滴英文|英文歌分享#6 "Closer',
  91. 'description': 'md5:3b1b9e25b78da4ef87e9b548b88ee76a',
  92. 'uploader': '阿滴英文',
  93. 'uploader_id': '65880958',
  94. 'timestamp': 1488382634,
  95. 'upload_date': '20170301',
  96. },
  97. 'params': {
  98. 'skip_download': True, # Test metadata only
  99. },
  100. }]
  101. }, {
  102. # new BV video id format
  103. 'url': 'https://www.bilibili.com/video/BV1JE411F741',
  104. 'only_matching': True,
  105. }]
  106. _APP_KEY = 'iVGUTjsxvpLeuDCf'
  107. _BILIBILI_KEY = 'aHRmhWMLkdeMuILqORnYZocwMBpMEOdt'
  108. def _report_error(self, result):
  109. if 'message' in result:
  110. raise ExtractorError('%s said: %s' % (self.IE_NAME, result['message']), expected=True)
  111. elif 'code' in result:
  112. raise ExtractorError('%s returns error %d' % (self.IE_NAME, result['code']), expected=True)
  113. else:
  114. raise ExtractorError('Can\'t extract Bangumi episode ID')
  115. def _real_extract(self, url):
  116. url, smuggled_data = unsmuggle_url(url, {})
  117. mobj = re.match(self._VALID_URL, url)
  118. video_id = mobj.group('id') or mobj.group('id_bv')
  119. anime_id = mobj.group('anime_id')
  120. webpage = self._download_webpage(url, video_id)
  121. if 'anime/' not in url:
  122. cid = self._search_regex(
  123. r'\bcid(?:["\']:|=)(\d+)', webpage, 'cid',
  124. default=None
  125. ) or compat_parse_qs(self._search_regex(
  126. [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
  127. r'EmbedPlayer\([^)]+,\s*\\"([^"]+)\\"\)',
  128. r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
  129. webpage, 'player parameters'))['cid'][0]
  130. else:
  131. if 'no_bangumi_tip' not in smuggled_data:
  132. self.to_screen('Downloading episode %s. To download all videos in anime %s, re-run youtube-dl with %s' % (
  133. video_id, anime_id, compat_urlparse.urljoin(url, '//bangumi.bilibili.com/anime/%s' % anime_id)))
  134. headers = {
  135. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  136. 'Referer': url
  137. }
  138. headers.update(self.geo_verification_headers())
  139. js = self._download_json(
  140. 'http://bangumi.bilibili.com/web_api/get_source', video_id,
  141. data=urlencode_postdata({'episode_id': video_id}),
  142. headers=headers)
  143. if 'result' not in js:
  144. self._report_error(js)
  145. cid = js['result']['cid']
  146. headers = {
  147. 'Accept': 'application/json',
  148. 'Referer': url
  149. }
  150. headers.update(self.geo_verification_headers())
  151. entries = []
  152. RENDITIONS = ('qn=80&quality=80&type=', 'quality=2&type=mp4')
  153. for num, rendition in enumerate(RENDITIONS, start=1):
  154. payload = 'appkey=%s&cid=%s&otype=json&%s' % (self._APP_KEY, cid, rendition)
  155. sign = hashlib.md5((payload + self._BILIBILI_KEY).encode('utf-8')).hexdigest()
  156. video_info = self._download_json(
  157. 'http://interface.bilibili.com/v2/playurl?%s&sign=%s' % (payload, sign),
  158. video_id, note='Downloading video info page',
  159. headers=headers, fatal=num == len(RENDITIONS))
  160. if not video_info:
  161. continue
  162. if 'durl' not in video_info:
  163. if num < len(RENDITIONS):
  164. continue
  165. self._report_error(video_info)
  166. for idx, durl in enumerate(video_info['durl']):
  167. formats = [{
  168. 'url': durl['url'],
  169. 'filesize': int_or_none(durl['size']),
  170. }]
  171. for backup_url in durl.get('backup_url', []):
  172. formats.append({
  173. 'url': backup_url,
  174. # backup URLs have lower priorities
  175. 'preference': -2 if 'hd.mp4' in backup_url else -3,
  176. })
  177. for a_format in formats:
  178. a_format.setdefault('http_headers', {}).update({
  179. 'Referer': url,
  180. })
  181. self._sort_formats(formats)
  182. entries.append({
  183. 'id': '%s_part%s' % (video_id, idx),
  184. 'duration': float_or_none(durl.get('length'), 1000),
  185. 'formats': formats,
  186. })
  187. break
  188. title = self._html_search_regex(
  189. ('<h1[^>]+\btitle=(["\'])(?P<title>(?:(?!\1).)+)\1',
  190. '(?s)<h1[^>]*>(?P<title>.+?)</h1>'), webpage, 'title',
  191. group='title')
  192. description = self._html_search_meta('description', webpage)
  193. timestamp = unified_timestamp(self._html_search_regex(
  194. r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time',
  195. default=None) or self._html_search_meta(
  196. 'uploadDate', webpage, 'timestamp', default=None))
  197. thumbnail = self._html_search_meta(['og:image', 'thumbnailUrl'], webpage)
  198. # TODO 'view_count' requires deobfuscating Javascript
  199. info = {
  200. 'id': video_id,
  201. 'title': title,
  202. 'description': description,
  203. 'timestamp': timestamp,
  204. 'thumbnail': thumbnail,
  205. 'duration': float_or_none(video_info.get('timelength'), scale=1000),
  206. }
  207. uploader_mobj = re.search(
  208. r'<a[^>]+href="(?:https?:)?//space\.bilibili\.com/(?P<id>\d+)"[^>]*>(?P<name>[^<]+)',
  209. webpage)
  210. if uploader_mobj:
  211. info.update({
  212. 'uploader': uploader_mobj.group('name').strip(),
  213. 'uploader_id': uploader_mobj.group('id'),
  214. })
  215. if not info.get('uploader'):
  216. info['uploader'] = self._html_search_meta(
  217. 'author', webpage, 'uploader', default=None)
  218. for entry in entries:
  219. entry.update(info)
  220. if len(entries) == 1:
  221. return entries[0]
  222. else:
  223. for idx, entry in enumerate(entries):
  224. entry['id'] = '%s_part%d' % (video_id, (idx + 1))
  225. return {
  226. '_type': 'multi_video',
  227. 'id': video_id,
  228. 'title': title,
  229. 'description': description,
  230. 'entries': entries,
  231. }
  232. class BiliBiliBangumiIE(InfoExtractor):
  233. _VALID_URL = r'https?://bangumi\.bilibili\.com/anime/(?P<id>\d+)'
  234. IE_NAME = 'bangumi.bilibili.com'
  235. IE_DESC = 'BiliBili番剧'
  236. _TESTS = [{
  237. 'url': 'http://bangumi.bilibili.com/anime/1869',
  238. 'info_dict': {
  239. 'id': '1869',
  240. 'title': '混沌武士',
  241. 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
  242. },
  243. 'playlist_count': 26,
  244. }, {
  245. 'url': 'http://bangumi.bilibili.com/anime/1869',
  246. 'info_dict': {
  247. 'id': '1869',
  248. 'title': '混沌武士',
  249. 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
  250. },
  251. 'playlist': [{
  252. 'md5': '91da8621454dd58316851c27c68b0c13',
  253. 'info_dict': {
  254. 'id': '40062',
  255. 'ext': 'mp4',
  256. 'title': '混沌武士',
  257. 'description': '故事发生在日本的江户时代。风是一个小酒馆的打工女。一日,酒馆里来了一群恶霸,虽然他们的举动令风十分不满,但是毕竟风只是一届女流,无法对他们采取什么行动,只能在心里嘟哝。这时,酒家里又进来了个“不良份子...',
  258. 'timestamp': 1414538739,
  259. 'upload_date': '20141028',
  260. 'episode': '疾风怒涛 Tempestuous Temperaments',
  261. 'episode_number': 1,
  262. },
  263. }],
  264. 'params': {
  265. 'playlist_items': '1',
  266. },
  267. }]
  268. @classmethod
  269. def suitable(cls, url):
  270. return False if BiliBiliIE.suitable(url) else super(BiliBiliBangumiIE, cls).suitable(url)
  271. def _real_extract(self, url):
  272. bangumi_id = self._match_id(url)
  273. # Sometimes this API returns a JSONP response
  274. season_info = self._download_json(
  275. 'http://bangumi.bilibili.com/jsonp/seasoninfo/%s.ver' % bangumi_id,
  276. bangumi_id, transform_source=strip_jsonp)['result']
  277. entries = [{
  278. '_type': 'url_transparent',
  279. 'url': smuggle_url(episode['webplay_url'], {'no_bangumi_tip': 1}),
  280. 'ie_key': BiliBiliIE.ie_key(),
  281. 'timestamp': parse_iso8601(episode.get('update_time'), delimiter=' '),
  282. 'episode': episode.get('index_title'),
  283. 'episode_number': int_or_none(episode.get('index')),
  284. } for episode in season_info['episodes']]
  285. entries = sorted(entries, key=lambda entry: entry.get('episode_number'))
  286. return self.playlist_result(
  287. entries, bangumi_id,
  288. season_info.get('bangumi_title'), season_info.get('evaluate'))
  289. class BilibiliAudioBaseIE(InfoExtractor):
  290. def _call_api(self, path, sid, query=None):
  291. if not query:
  292. query = {'sid': sid}
  293. return self._download_json(
  294. 'https://www.bilibili.com/audio/music-service-c/web/' + path,
  295. sid, query=query)['data']
  296. class BilibiliAudioIE(BilibiliAudioBaseIE):
  297. _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/au(?P<id>\d+)'
  298. _TEST = {
  299. 'url': 'https://www.bilibili.com/audio/au1003142',
  300. 'md5': 'fec4987014ec94ef9e666d4d158ad03b',
  301. 'info_dict': {
  302. 'id': '1003142',
  303. 'ext': 'm4a',
  304. 'title': '【tsukimi】YELLOW / 神山羊',
  305. 'artist': 'tsukimi',
  306. 'comment_count': int,
  307. 'description': 'YELLOW的mp3版!',
  308. 'duration': 183,
  309. 'subtitles': {
  310. 'origin': [{
  311. 'ext': 'lrc',
  312. }],
  313. },
  314. 'thumbnail': r're:^https?://.+\.jpg',
  315. 'timestamp': 1564836614,
  316. 'upload_date': '20190803',
  317. 'uploader': 'tsukimi-つきみぐー',
  318. 'view_count': int,
  319. },
  320. }
  321. def _real_extract(self, url):
  322. au_id = self._match_id(url)
  323. play_data = self._call_api('url', au_id)
  324. formats = [{
  325. 'url': play_data['cdns'][0],
  326. 'filesize': int_or_none(play_data.get('size')),
  327. }]
  328. for a_format in formats:
  329. a_format.setdefault('http_headers', {}).update({
  330. 'Referer': url,
  331. })
  332. song = self._call_api('song/info', au_id)
  333. title = song['title']
  334. statistic = song.get('statistic') or {}
  335. subtitles = None
  336. lyric = song.get('lyric')
  337. if lyric:
  338. subtitles = {
  339. 'origin': [{
  340. 'url': lyric,
  341. }]
  342. }
  343. return {
  344. 'id': au_id,
  345. 'title': title,
  346. 'formats': formats,
  347. 'artist': song.get('author'),
  348. 'comment_count': int_or_none(statistic.get('comment')),
  349. 'description': song.get('intro'),
  350. 'duration': int_or_none(song.get('duration')),
  351. 'subtitles': subtitles,
  352. 'thumbnail': song.get('cover'),
  353. 'timestamp': int_or_none(song.get('passtime')),
  354. 'uploader': song.get('uname'),
  355. 'view_count': int_or_none(statistic.get('play')),
  356. }
  357. class BilibiliAudioAlbumIE(BilibiliAudioBaseIE):
  358. _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/am(?P<id>\d+)'
  359. _TEST = {
  360. 'url': 'https://www.bilibili.com/audio/am10624',
  361. 'info_dict': {
  362. 'id': '10624',
  363. 'title': '每日新曲推荐(每日11:00更新)',
  364. 'description': '每天11:00更新,为你推送最新音乐',
  365. },
  366. 'playlist_count': 19,
  367. }
  368. def _real_extract(self, url):
  369. am_id = self._match_id(url)
  370. songs = self._call_api(
  371. 'song/of-menu', am_id, {'sid': am_id, 'pn': 1, 'ps': 100})['data']
  372. entries = []
  373. for song in songs:
  374. sid = str_or_none(song.get('id'))
  375. if not sid:
  376. continue
  377. entries.append(self.url_result(
  378. 'https://www.bilibili.com/audio/au' + sid,
  379. BilibiliAudioIE.ie_key(), sid))
  380. if entries:
  381. album_data = self._call_api('menu/info', am_id) or {}
  382. album_title = album_data.get('title')
  383. if album_title:
  384. for entry in entries:
  385. entry['album'] = album_title
  386. return self.playlist_result(
  387. entries, am_id, album_title, album_data.get('intro'))
  388. return self.playlist_result(entries, am_id)
  389. class BiliBiliPlayerIE(InfoExtractor):
  390. _VALID_URL = r'https?://player\.bilibili\.com/player\.html\?.*?\baid=(?P<id>\d+)'
  391. _TEST = {
  392. 'url': 'http://player.bilibili.com/player.html?aid=92494333&cid=157926707&page=1',
  393. 'only_matching': True,
  394. }
  395. def _real_extract(self, url):
  396. video_id = self._match_id(url)
  397. return self.url_result(
  398. 'http://www.bilibili.tv/video/av%s/' % video_id,
  399. ie=BiliBiliIE.ie_key(), video_id=video_id)