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.

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