You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

189 lines
6.8 KiB

  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': '9fa226fe2b8a9a4d5a69b4c6a183417e',
  24. 'info_dict': {
  25. 'id': '1554319',
  26. 'ext': 'mp4',
  27. 'title': '【金坷垃】金泡沫',
  28. 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
  29. 'duration': 308.315,
  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': '1507019',
  40. 'ext': 'mp4',
  41. 'title': '【BD1080P】刀语【诸神&异域】',
  42. 'description': '这是个神奇的故事~每个人不留弹幕不给走哦~切利哦!~',
  43. 'timestamp': 1396530060,
  44. 'upload_date': '20140403',
  45. 'uploader': '枫叶逝去',
  46. 'uploader_id': '520116',
  47. },
  48. }, {
  49. 'url': 'http://www.bilibili.com/video/av4808130/',
  50. 'info_dict': {
  51. 'id': '7802182',
  52. 'ext': 'mp4',
  53. 'title': '【长篇】哆啦A梦443【钉铛】',
  54. 'description': '(2016.05.27)来组合客人的脸吧&amp;amp;寻母六千里锭 抱歉,又轮到周日上班现在才到家 封面www.pixiv.net/member_illust.php?mode=medium&amp;amp;illust_id=56912929',
  55. 'timestamp': 1464564180,
  56. 'upload_date': '20160529',
  57. 'uploader': '喜欢拉面',
  58. 'uploader_id': '151066',
  59. },
  60. }, {
  61. # Missing upload time
  62. 'url': 'http://www.bilibili.com/video/av1867637/',
  63. 'info_dict': {
  64. 'id': '2880301',
  65. 'ext': 'mp4',
  66. 'title': '【HDTV】【喜剧】岳父岳母真难当 (2014)【法国票房冠军】',
  67. 'description': '一个信奉天主教的法国旧式传统资产阶级家庭中有四个女儿。三个女儿却分别找了阿拉伯、犹太、中国丈夫,老夫老妻唯独期盼剩下未嫁的小女儿能找一个信奉天主教的法国白人,结果没想到小女儿找了一位非裔黑人……【这次应该不会跳帧了】',
  68. 'uploader': '黑夜为猫',
  69. 'uploader_id': '610729',
  70. },
  71. 'params': {
  72. # Just to test metadata extraction
  73. 'skip_download': True,
  74. },
  75. 'expected_warnings': ['upload time'],
  76. }]
  77. # BiliBili blocks keys from time to time. The current key is extracted from
  78. # the Android client
  79. # TODO: find the sign algorithm used in the flash player
  80. _APP_KEY = '86385cdc024c0f6c'
  81. def _real_extract(self, url):
  82. mobj = re.match(self._VALID_URL, url)
  83. video_id = mobj.group('id')
  84. webpage = self._download_webpage(url, video_id)
  85. params = compat_parse_qs(self._search_regex(
  86. [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
  87. r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
  88. webpage, 'player parameters'))
  89. cid = params['cid'][0]
  90. info_xml_str = self._download_webpage(
  91. 'http://interface.bilibili.com/v_cdn_play',
  92. cid, query={'appkey': self._APP_KEY, 'cid': cid},
  93. note='Downloading video info page')
  94. err_msg = None
  95. durls = None
  96. info_xml = None
  97. try:
  98. info_xml = compat_etree_fromstring(info_xml_str.encode('utf-8'))
  99. except compat_xml_parse_error:
  100. info_json = self._parse_json(info_xml_str, video_id, fatal=False)
  101. err_msg = (info_json or {}).get('error_text')
  102. else:
  103. err_msg = xpath_text(info_xml, './message')
  104. if info_xml is not None:
  105. durls = info_xml.findall('./durl')
  106. if not durls:
  107. if err_msg:
  108. raise ExtractorError('%s said: %s' % (self.IE_NAME, err_msg), expected=True)
  109. else:
  110. raise ExtractorError('No videos found!')
  111. entries = []
  112. for durl in durls:
  113. size = xpath_text(durl, ['./filesize', './size'])
  114. formats = [{
  115. 'url': durl.find('./url').text,
  116. 'filesize': int_or_none(size),
  117. }]
  118. for backup_url in durl.findall('./backup_url/url'):
  119. formats.append({
  120. 'url': backup_url.text,
  121. # backup URLs have lower priorities
  122. 'preference': -2 if 'hd.mp4' in backup_url.text else -3,
  123. })
  124. self._sort_formats(formats)
  125. entries.append({
  126. 'id': '%s_part%s' % (cid, xpath_text(durl, './order')),
  127. 'duration': int_or_none(xpath_text(durl, './length'), 1000),
  128. 'formats': formats,
  129. })
  130. title = self._html_search_regex('<h1[^>]+title="([^"]+)">', webpage, 'title')
  131. description = self._html_search_meta('description', webpage)
  132. datetime_str = self._html_search_regex(
  133. r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time', fatal=False)
  134. timestamp = None
  135. if datetime_str:
  136. timestamp = calendar.timegm(datetime.datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M').timetuple())
  137. # TODO 'view_count' requires deobfuscating Javascript
  138. info = {
  139. 'id': compat_str(cid),
  140. 'title': title,
  141. 'description': description,
  142. 'timestamp': timestamp,
  143. 'thumbnail': self._html_search_meta('thumbnailUrl', webpage),
  144. 'duration': float_or_none(xpath_text(info_xml, './timelength'), scale=1000),
  145. }
  146. uploader_mobj = re.search(
  147. r'<a[^>]+href="https?://space\.bilibili\.com/(?P<id>\d+)"[^>]+title="(?P<name>[^"]+)"',
  148. webpage)
  149. if uploader_mobj:
  150. info.update({
  151. 'uploader': uploader_mobj.group('name'),
  152. 'uploader_id': uploader_mobj.group('id'),
  153. })
  154. for entry in entries:
  155. entry.update(info)
  156. if len(entries) == 1:
  157. return entries[0]
  158. else:
  159. for idx, entry in enumerate(entries):
  160. entry['id'] = '%s_part%d' % (video_id, (idx + 1))
  161. return {
  162. '_type': 'multi_video',
  163. 'id': video_id,
  164. 'title': title,
  165. 'description': description,
  166. 'entries': entries,
  167. }