bilibili.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. 'url': 'http://www.bilibili.com/video/av4808130/',
  46. 'info_dict': {
  47. 'id': '4808130',
  48. 'title': '【长篇】哆啦A梦443【钉铛】',
  49. 'description': '(2016.05.27)来组合客人的脸吧&amp;amp;寻母六千里锭 抱歉,又轮到周日上班现在才到家 封面www.pixiv.net/member_illust.php?mode=medium&amp;amp;illust_id=56912929',
  50. },
  51. 'playlist': [{
  52. 'md5': '55cdadedf3254caaa0d5d27cf20a8f9c',
  53. 'info_dict': {
  54. 'id': '4808130_part1',
  55. 'ext': 'flv',
  56. 'title': '【长篇】哆啦A梦443【钉铛】',
  57. 'description': '(2016.05.27)来组合客人的脸吧&amp;amp;寻母六千里锭 抱歉,又轮到周日上班现在才到家 封面www.pixiv.net/member_illust.php?mode=medium&amp;amp;illust_id=56912929',
  58. 'timestamp': 1464564180,
  59. 'upload_date': '20160529',
  60. 'uploader': '喜欢拉面',
  61. 'uploader_id': '151066',
  62. },
  63. }, {
  64. 'md5': '926f9f67d0c482091872fbd8eca7ea3d',
  65. 'info_dict': {
  66. 'id': '4808130_part2',
  67. 'ext': 'flv',
  68. 'title': '【长篇】哆啦A梦443【钉铛】',
  69. 'description': '(2016.05.27)来组合客人的脸吧&amp;amp;寻母六千里锭 抱歉,又轮到周日上班现在才到家 封面www.pixiv.net/member_illust.php?mode=medium&amp;amp;illust_id=56912929',
  70. 'timestamp': 1464564180,
  71. 'upload_date': '20160529',
  72. 'uploader': '喜欢拉面',
  73. 'uploader_id': '151066',
  74. },
  75. }, {
  76. 'md5': '4b7b225b968402d7c32348c646f1fd83',
  77. 'info_dict': {
  78. 'id': '4808130_part3',
  79. 'ext': 'flv',
  80. 'title': '【长篇】哆啦A梦443【钉铛】',
  81. 'description': '(2016.05.27)来组合客人的脸吧&amp;amp;寻母六千里锭 抱歉,又轮到周日上班现在才到家 封面www.pixiv.net/member_illust.php?mode=medium&amp;amp;illust_id=56912929',
  82. 'timestamp': 1464564180,
  83. 'upload_date': '20160529',
  84. 'uploader': '喜欢拉面',
  85. 'uploader_id': '151066',
  86. },
  87. }, {
  88. 'md5': '7b795e214166501e9141139eea236e91',
  89. 'info_dict': {
  90. 'id': '4808130_part4',
  91. 'ext': 'flv',
  92. 'title': '【长篇】哆啦A梦443【钉铛】',
  93. 'description': '(2016.05.27)来组合客人的脸吧&amp;amp;寻母六千里锭 抱歉,又轮到周日上班现在才到家 封面www.pixiv.net/member_illust.php?mode=medium&amp;amp;illust_id=56912929',
  94. 'timestamp': 1464564180,
  95. 'upload_date': '20160529',
  96. 'uploader': '喜欢拉面',
  97. 'uploader_id': '151066',
  98. },
  99. }],
  100. }]
  101. # BiliBili blocks keys from time to time. The current key is extracted from
  102. # the Android client
  103. # TODO: find the sign algorithm used in the flash player
  104. _APP_KEY = '86385cdc024c0f6c'
  105. def _real_extract(self, url):
  106. mobj = re.match(self._VALID_URL, url)
  107. video_id = mobj.group('id')
  108. webpage = self._download_webpage(url, video_id)
  109. params = compat_parse_qs(self._search_regex(
  110. [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
  111. r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
  112. webpage, 'player parameters'))
  113. cid = params['cid'][0]
  114. info_xml_str = self._download_webpage(
  115. 'http://interface.bilibili.com/v_cdn_play',
  116. cid, query={'appkey': self._APP_KEY, 'cid': cid},
  117. note='Downloading video info page')
  118. err_msg = None
  119. durls = None
  120. info_xml = None
  121. try:
  122. info_xml = compat_etree_fromstring(info_xml_str.encode('utf-8'))
  123. except compat_xml_parse_error:
  124. info_json = self._parse_json(info_xml_str, video_id, fatal=False)
  125. err_msg = (info_json or {}).get('error_text')
  126. else:
  127. err_msg = xpath_text(info_xml, './message')
  128. if info_xml is not None:
  129. durls = info_xml.findall('./durl')
  130. if not durls:
  131. if err_msg:
  132. raise ExtractorError('%s said: %s' % (self.IE_NAME, err_msg), expected=True)
  133. else:
  134. raise ExtractorError('No videos found!')
  135. entries = []
  136. for durl in durls:
  137. size = xpath_text(durl, ['./filesize', './size'])
  138. formats = [{
  139. 'url': durl.find('./url').text,
  140. 'filesize': int_or_none(size),
  141. }]
  142. for backup_url in durl.findall('./backup_url/url'):
  143. formats.append({
  144. 'url': backup_url.text,
  145. # backup URLs have lower priorities
  146. 'preference': -2 if 'hd.mp4' in backup_url.text else -3,
  147. })
  148. self._sort_formats(formats)
  149. entries.append({
  150. 'id': '%s_part%s' % (cid, xpath_text(durl, './order')),
  151. 'duration': int_or_none(xpath_text(durl, './length'), 1000),
  152. 'formats': formats,
  153. })
  154. title = self._html_search_regex('<h1[^>]+title="([^"]+)">', webpage, 'title')
  155. description = self._html_search_meta('description', webpage)
  156. datetime_str = self._html_search_regex(
  157. r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time', fatal=False)
  158. if datetime_str:
  159. timestamp = calendar.timegm(datetime.datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M').timetuple())
  160. # TODO 'view_count' requires deobfuscating Javascript
  161. info = {
  162. 'id': compat_str(cid),
  163. 'title': title,
  164. 'description': description,
  165. 'timestamp': timestamp,
  166. 'thumbnail': self._html_search_meta('thumbnailUrl', webpage),
  167. 'duration': float_or_none(xpath_text(info_xml, './timelength'), scale=1000),
  168. }
  169. uploader_mobj = re.search(
  170. r'<a[^>]+href="https?://space\.bilibili\.com/(?P<id>\d+)"[^>]+title="(?P<name>[^"]+)"',
  171. webpage)
  172. if uploader_mobj:
  173. info.update({
  174. 'uploader': uploader_mobj.group('name'),
  175. 'uploader_id': uploader_mobj.group('id'),
  176. })
  177. for entry in entries:
  178. entry.update(info)
  179. if len(entries) == 1:
  180. return entries[0]
  181. else:
  182. for idx, entry in enumerate(entries):
  183. entry['id'] = '%s_part%d' % (video_id, (idx + 1))
  184. return {
  185. '_type': 'multi_video',
  186. 'id': video_id,
  187. 'title': title,
  188. 'description': description,
  189. 'entries': entries,
  190. }