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.

177 lines
7.7 KiB

  1. # encoding: utf-8
  2. import re
  3. import json
  4. import xml.etree.ElementTree
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. compat_urllib_parse,
  8. find_xpath_attr,
  9. compat_urlparse,
  10. compat_str,
  11. compat_urllib_request,
  12. ExtractorError,
  13. )
  14. class BrightcoveIE(InfoExtractor):
  15. _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
  16. _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
  17. _PLAYLIST_URL_TEMPLATE = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s'
  18. _TESTS = [
  19. {
  20. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  21. u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  22. u'file': u'2371591881001.mp4',
  23. u'md5': u'8eccab865181d29ec2958f32a6a754f5',
  24. u'note': u'Test Brightcove downloads and detection in GenericIE',
  25. u'info_dict': {
  26. u'title': u'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  27. u'uploader': u'8TV',
  28. u'description': u'md5:a950cc4285c43e44d763d036710cd9cd',
  29. }
  30. },
  31. {
  32. # From http://medianetwork.oracle.com/video/player/1785452137001
  33. u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  34. u'file': u'1785452137001.flv',
  35. u'info_dict': {
  36. u'title': u'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  37. u'description': u'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  38. u'uploader': u'Oracle',
  39. },
  40. },
  41. {
  42. # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
  43. u'url': u'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
  44. u'info_dict': {
  45. u'id': u'2750934548001',
  46. u'ext': u'mp4',
  47. u'title': u'This Bracelet Acts as a Personal Thermostat',
  48. u'description': u'md5:547b78c64f4112766ccf4e151c20b6a0',
  49. u'uploader': u'Mashable',
  50. },
  51. },
  52. ]
  53. @classmethod
  54. def _build_brighcove_url(cls, object_str):
  55. """
  56. Build a Brightcove url from a xml string containing
  57. <object class="BrightcoveExperience">{params}</object>
  58. """
  59. # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
  60. object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
  61. lambda m: m.group(1) + '/>', object_str)
  62. # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
  63. object_str = object_str.replace(u'<--', u'<!--')
  64. object_doc = xml.etree.ElementTree.fromstring(object_str)
  65. assert u'BrightcoveExperience' in object_doc.attrib['class']
  66. params = {'flashID': object_doc.attrib['id'],
  67. 'playerID': find_xpath_attr(object_doc, './param', 'name', 'playerID').attrib['value'],
  68. }
  69. def find_param(name):
  70. node = find_xpath_attr(object_doc, './param', 'name', name)
  71. if node is not None:
  72. return node.attrib['value']
  73. return None
  74. playerKey = find_param('playerKey')
  75. # Not all pages define this value
  76. if playerKey is not None:
  77. params['playerKey'] = playerKey
  78. # The three fields hold the id of the video
  79. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
  80. if videoPlayer is not None:
  81. params['@videoPlayer'] = videoPlayer
  82. linkBase = find_param('linkBaseURL')
  83. if linkBase is not None:
  84. params['linkBaseURL'] = linkBase
  85. data = compat_urllib_parse.urlencode(params)
  86. return cls._FEDERATED_URL_TEMPLATE % data
  87. @classmethod
  88. def _extract_brightcove_url(cls, webpage):
  89. """Try to extract the brightcove url from the wepbage, returns None
  90. if it can't be found
  91. """
  92. m_brightcove = re.search(
  93. r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>',
  94. webpage, re.DOTALL)
  95. if m_brightcove is not None:
  96. return cls._build_brighcove_url(m_brightcove.group())
  97. else:
  98. return None
  99. def _real_extract(self, url):
  100. # Change the 'videoId' and others field to '@videoPlayer'
  101. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  102. # Change bckey (used by bcove.me urls) to playerKey
  103. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  104. mobj = re.match(self._VALID_URL, url)
  105. query_str = mobj.group('query')
  106. query = compat_urlparse.parse_qs(query_str)
  107. videoPlayer = query.get('@videoPlayer')
  108. if videoPlayer:
  109. return self._get_video_info(videoPlayer[0], query_str, query)
  110. else:
  111. player_key = query['playerKey']
  112. return self._get_playlist_info(player_key[0])
  113. def _get_video_info(self, video_id, query_str, query):
  114. request_url = self._FEDERATED_URL_TEMPLATE % query_str
  115. req = compat_urllib_request.Request(request_url)
  116. linkBase = query.get('linkBaseURL')
  117. if linkBase is not None:
  118. req.add_header('Referer', linkBase[0])
  119. webpage = self._download_webpage(req, video_id)
  120. self.report_extraction(video_id)
  121. info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
  122. info = json.loads(info)['data']
  123. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  124. return self._extract_video_info(video_info)
  125. def _get_playlist_info(self, player_key):
  126. playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
  127. player_key, u'Downloading playlist information')
  128. json_data = json.loads(playlist_info)
  129. if 'videoList' not in json_data:
  130. raise ExtractorError(u'Empty playlist')
  131. playlist_info = json_data['videoList']
  132. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  133. return self.playlist_result(videos, playlist_id=playlist_info['id'],
  134. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  135. def _extract_video_info(self, video_info):
  136. info = {
  137. 'id': compat_str(video_info['id']),
  138. 'title': video_info['displayName'],
  139. 'description': video_info.get('shortDescription'),
  140. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  141. 'uploader': video_info.get('publisherName'),
  142. }
  143. renditions = video_info.get('renditions')
  144. if renditions:
  145. renditions = sorted(renditions, key=lambda r: r['size'])
  146. info['formats'] = [{
  147. 'url': rend['defaultURL'],
  148. 'height': rend.get('frameHeight'),
  149. 'width': rend.get('frameWidth'),
  150. } for rend in renditions]
  151. elif video_info.get('FLVFullLengthURL') is not None:
  152. info.update({
  153. 'url': video_info['FLVFullLengthURL'],
  154. })
  155. else:
  156. raise ExtractorError(u'Unable to extract video url for %s' % info['id'])
  157. return info