bilibili.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import calendar
  4. import datetime
  5. import re
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_etree_fromstring,
  9. compat_str,
  10. compat_parse_qs,
  11. compat_xml_parse_error,
  12. )
  13. from ..utils import (
  14. ExtractorError,
  15. int_or_none,
  16. float_or_none,
  17. xpath_text,
  18. )
  19. class BiliBiliIE(InfoExtractor):
  20. _VALID_URL = r'https?://www\.bilibili\.(?:tv|com)/video/av(?P<id>\d+)'
  21. _TESTS = [{
  22. 'url': 'http://www.bilibili.tv/video/av1074402/',
  23. 'md5': '5f7d29e1a2872f3df0cf76b1f87d3788',
  24. 'info_dict': {
  25. 'id': '1554319',
  26. 'ext': 'flv',
  27. 'title': '【金坷垃】金泡沫',
  28. 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
  29. 'duration': 308.067,
  30. 'timestamp': 1398012660,
  31. 'upload_date': '20140420',
  32. 'thumbnail': 're:^https?://.+\.jpg',
  33. 'uploader': '菊子桑',
  34. 'uploader_id': '156160',
  35. },
  36. }, {
  37. 'url': 'http://www.bilibili.com/video/av1041170/',
  38. 'info_dict': {
  39. 'id': '1041170',
  40. 'title': '【BD1080P】刀语【诸神&异域】',
  41. 'description': '这是个神奇的故事~每个人不留弹幕不给走哦~切利哦!~',
  42. },
  43. 'playlist_count': 9,
  44. }]
  45. # BiliBili blocks keys from time to time. The current key is extracted from
  46. # the Android client
  47. # TODO: find the sign algorithm used in the flash player
  48. _APP_KEY = '86385cdc024c0f6c'
  49. def _real_extract(self, url):
  50. mobj = re.match(self._VALID_URL, url)
  51. video_id = mobj.group('id')
  52. webpage = self._download_webpage(url, video_id)
  53. params = compat_parse_qs(self._search_regex(
  54. [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
  55. r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
  56. webpage, 'player parameters'))
  57. cid = params['cid'][0]
  58. info_xml_str = self._download_webpage(
  59. 'http://interface.bilibili.com/v_cdn_play',
  60. cid, query={'appkey': self._APP_KEY, 'cid': cid},
  61. note='Downloading video info page')
  62. err_msg = None
  63. durls = None
  64. info_xml = None
  65. try:
  66. info_xml = compat_etree_fromstring(info_xml_str.encode('utf-8'))
  67. except compat_xml_parse_error:
  68. info_json = self._parse_json(info_xml_str, video_id, fatal=False)
  69. err_msg = (info_json or {}).get('error_text')
  70. else:
  71. err_msg = xpath_text(info_xml, './message')
  72. if info_xml is not None:
  73. durls = info_xml.findall('./durl')
  74. if not durls:
  75. if err_msg:
  76. raise ExtractorError('%s said: %s' % (self.IE_NAME, err_msg), expected=True)
  77. else:
  78. raise ExtractorError('No videos found!')
  79. entries = []
  80. for durl in durls:
  81. size = xpath_text(durl, ['./filesize', './size'])
  82. formats = [{
  83. 'url': durl.find('./url').text,
  84. 'filesize': int_or_none(size),
  85. }]
  86. for backup_url in durl.findall('./backup_url/url'):
  87. formats.append({
  88. 'url': backup_url.text,
  89. # backup URLs have lower priorities
  90. 'preference': -2 if 'hd.mp4' in backup_url.text else -3,
  91. })
  92. self._sort_formats(formats)
  93. entries.append({
  94. 'id': '%s_part%s' % (cid, xpath_text(durl, './order')),
  95. 'duration': int_or_none(xpath_text(durl, './length'), 1000),
  96. 'formats': formats,
  97. })
  98. title = self._html_search_regex('<h1[^>]+title="([^"]+)">', webpage, 'title')
  99. description = self._html_search_meta('description', webpage)
  100. datetime_str = self._html_search_regex(
  101. r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time', fatal=False)
  102. if datetime_str:
  103. timestamp = calendar.timegm(datetime.datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M').timetuple())
  104. # TODO 'view_count' requires deobfuscating Javascript
  105. info = {
  106. 'id': compat_str(cid),
  107. 'title': title,
  108. 'description': description,
  109. 'timestamp': timestamp,
  110. 'thumbnail': self._html_search_meta('thumbnailUrl', webpage),
  111. 'duration': float_or_none(xpath_text(info_xml, './timelength'), scale=1000),
  112. }
  113. uploader_mobj = re.search(
  114. r'<a[^>]+href="https?://space\.bilibili\.com/(?P<id>\d+)"[^>]+title="(?P<name>[^"]+)"',
  115. webpage)
  116. if uploader_mobj:
  117. info.update({
  118. 'uploader': uploader_mobj.group('name'),
  119. 'uploader_id': uploader_mobj.group('id'),
  120. })
  121. for entry in entries:
  122. entry.update(info)
  123. if len(entries) == 1:
  124. return entries[0]
  125. else:
  126. return {
  127. '_type': 'multi_video',
  128. 'id': video_id,
  129. 'title': title,
  130. 'description': description,
  131. 'entries': entries,
  132. }