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.

193 lines
8.4 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. # test that the default referer works
  54. # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
  55. u'url': u'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
  56. u'info_dict': {
  57. u'id': u'2878862109001',
  58. u'ext': u'mp4',
  59. u'title': u'Lost in Motion II',
  60. u'description': u'md5:363109c02998fee92ec02211bd8000df',
  61. u'uploader': u'National Ballet of Canada',
  62. },
  63. },
  64. ]
  65. @classmethod
  66. def _build_brighcove_url(cls, object_str):
  67. """
  68. Build a Brightcove url from a xml string containing
  69. <object class="BrightcoveExperience">{params}</object>
  70. """
  71. # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
  72. object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
  73. lambda m: m.group(1) + '/>', object_str)
  74. # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
  75. object_str = object_str.replace(u'<--', u'<!--')
  76. object_doc = xml.etree.ElementTree.fromstring(object_str)
  77. assert u'BrightcoveExperience' in object_doc.attrib['class']
  78. params = {'flashID': object_doc.attrib['id'],
  79. 'playerID': find_xpath_attr(object_doc, './param', 'name', 'playerID').attrib['value'],
  80. }
  81. def find_param(name):
  82. node = find_xpath_attr(object_doc, './param', 'name', name)
  83. if node is not None:
  84. return node.attrib['value']
  85. return None
  86. playerKey = find_param('playerKey')
  87. # Not all pages define this value
  88. if playerKey is not None:
  89. params['playerKey'] = playerKey
  90. # The three fields hold the id of the video
  91. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
  92. if videoPlayer is not None:
  93. params['@videoPlayer'] = videoPlayer
  94. linkBase = find_param('linkBaseURL')
  95. if linkBase is not None:
  96. params['linkBaseURL'] = linkBase
  97. data = compat_urllib_parse.urlencode(params)
  98. return cls._FEDERATED_URL_TEMPLATE % data
  99. @classmethod
  100. def _extract_brightcove_url(cls, webpage):
  101. """Try to extract the brightcove url from the wepbage, returns None
  102. if it can't be found
  103. """
  104. m_brightcove = re.search(
  105. r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>',
  106. webpage, re.DOTALL)
  107. if m_brightcove is not None:
  108. return cls._build_brighcove_url(m_brightcove.group())
  109. else:
  110. return None
  111. def _real_extract(self, url):
  112. # Change the 'videoId' and others field to '@videoPlayer'
  113. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  114. # Change bckey (used by bcove.me urls) to playerKey
  115. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  116. mobj = re.match(self._VALID_URL, url)
  117. query_str = mobj.group('query')
  118. query = compat_urlparse.parse_qs(query_str)
  119. videoPlayer = query.get('@videoPlayer')
  120. if videoPlayer:
  121. return self._get_video_info(videoPlayer[0], query_str, query,
  122. # We set the original url as the default 'Referer' header
  123. referer=url)
  124. else:
  125. player_key = query['playerKey']
  126. return self._get_playlist_info(player_key[0])
  127. def _get_video_info(self, video_id, query_str, query, referer=None):
  128. request_url = self._FEDERATED_URL_TEMPLATE % query_str
  129. req = compat_urllib_request.Request(request_url)
  130. linkBase = query.get('linkBaseURL')
  131. if linkBase is not None:
  132. referer = linkBase[0]
  133. if referer is not None:
  134. req.add_header('Referer', referer)
  135. webpage = self._download_webpage(req, video_id)
  136. self.report_extraction(video_id)
  137. info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
  138. info = json.loads(info)['data']
  139. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  140. return self._extract_video_info(video_info)
  141. def _get_playlist_info(self, player_key):
  142. playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
  143. player_key, u'Downloading playlist information')
  144. json_data = json.loads(playlist_info)
  145. if 'videoList' not in json_data:
  146. raise ExtractorError(u'Empty playlist')
  147. playlist_info = json_data['videoList']
  148. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  149. return self.playlist_result(videos, playlist_id=playlist_info['id'],
  150. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  151. def _extract_video_info(self, video_info):
  152. info = {
  153. 'id': compat_str(video_info['id']),
  154. 'title': video_info['displayName'],
  155. 'description': video_info.get('shortDescription'),
  156. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  157. 'uploader': video_info.get('publisherName'),
  158. }
  159. renditions = video_info.get('renditions')
  160. if renditions:
  161. renditions = sorted(renditions, key=lambda r: r['size'])
  162. info['formats'] = [{
  163. 'url': rend['defaultURL'],
  164. 'height': rend.get('frameHeight'),
  165. 'width': rend.get('frameWidth'),
  166. } for rend in renditions]
  167. elif video_info.get('FLVFullLengthURL') is not None:
  168. info.update({
  169. 'url': video_info['FLVFullLengthURL'],
  170. })
  171. else:
  172. raise ExtractorError(u'Unable to extract video url for %s' % info['id'])
  173. return info