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.

198 lines
8.5 KiB

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