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.

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