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.

238 lines
9.7 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. if fv_el is not None:
  84. flashvars = dict(
  85. (k, v[0])
  86. for k, v in compat_parse_qs(fv_el.attrib['value']).items())
  87. else:
  88. flashvars = {}
  89. def find_param(name):
  90. if name in flashvars:
  91. return flashvars[name]
  92. node = find_xpath_attr(object_doc, './param', 'name', name)
  93. if node is not None:
  94. return node.attrib['value']
  95. return None
  96. params = {}
  97. playerID = find_param('playerID')
  98. if playerID is None:
  99. raise ExtractorError('Cannot find player ID')
  100. params['playerID'] = playerID
  101. playerKey = find_param('playerKey')
  102. # Not all pages define this value
  103. if playerKey is not None:
  104. params['playerKey'] = playerKey
  105. # The three fields hold the id of the video
  106. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
  107. if videoPlayer is not None:
  108. params['@videoPlayer'] = videoPlayer
  109. linkBase = find_param('linkBaseURL')
  110. if linkBase is not None:
  111. params['linkBaseURL'] = linkBase
  112. data = compat_urllib_parse.urlencode(params)
  113. return cls._FEDERATED_URL_TEMPLATE % data
  114. @classmethod
  115. def _extract_brightcove_url(cls, webpage):
  116. """Try to extract the brightcove url from the wepbage, returns None
  117. if it can't be found
  118. """
  119. m_brightcove = re.search(
  120. r'''(?sx)<object
  121. (?:
  122. [^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1 |
  123. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  124. ).+?</object>''',
  125. webpage)
  126. if m_brightcove is not None:
  127. return cls._build_brighcove_url(m_brightcove.group())
  128. else:
  129. return None
  130. def _real_extract(self, url):
  131. url, smuggled_data = unsmuggle_url(url, {})
  132. # Change the 'videoId' and others field to '@videoPlayer'
  133. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  134. # Change bckey (used by bcove.me urls) to playerKey
  135. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  136. mobj = re.match(self._VALID_URL, url)
  137. query_str = mobj.group('query')
  138. query = compat_urlparse.parse_qs(query_str)
  139. videoPlayer = query.get('@videoPlayer')
  140. if videoPlayer:
  141. # We set the original url as the default 'Referer' header
  142. referer = smuggled_data.get('Referer', url)
  143. return self._get_video_info(
  144. videoPlayer[0], query_str, query, referer=referer)
  145. else:
  146. player_key = query['playerKey']
  147. return self._get_playlist_info(player_key[0])
  148. def _get_video_info(self, video_id, query_str, query, referer=None):
  149. request_url = self._FEDERATED_URL_TEMPLATE % query_str
  150. req = compat_urllib_request.Request(request_url)
  151. linkBase = query.get('linkBaseURL')
  152. if linkBase is not None:
  153. referer = linkBase[0]
  154. if referer is not None:
  155. req.add_header('Referer', referer)
  156. webpage = self._download_webpage(req, video_id)
  157. self.report_extraction(video_id)
  158. info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
  159. info = json.loads(info)['data']
  160. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  161. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  162. return self._extract_video_info(video_info)
  163. def _get_playlist_info(self, player_key):
  164. playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
  165. player_key, 'Downloading playlist information')
  166. json_data = json.loads(playlist_info)
  167. if 'videoList' not in json_data:
  168. raise ExtractorError('Empty playlist')
  169. playlist_info = json_data['videoList']
  170. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  171. return self.playlist_result(videos, playlist_id=playlist_info['id'],
  172. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  173. def _extract_video_info(self, video_info):
  174. info = {
  175. 'id': compat_str(video_info['id']),
  176. 'title': video_info['displayName'].strip(),
  177. 'description': video_info.get('shortDescription'),
  178. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  179. 'uploader': video_info.get('publisherName'),
  180. }
  181. renditions = video_info.get('renditions')
  182. if renditions:
  183. renditions = sorted(renditions, key=lambda r: r['size'])
  184. info['formats'] = [{
  185. 'url': rend['defaultURL'],
  186. 'height': rend.get('frameHeight'),
  187. 'width': rend.get('frameWidth'),
  188. } for rend in renditions]
  189. elif video_info.get('FLVFullLengthURL') is not None:
  190. info.update({
  191. 'url': video_info['FLVFullLengthURL'],
  192. })
  193. if self._downloader.params.get('include_ads', False):
  194. adServerURL = video_info.get('_youtubedl_adServerURL')
  195. if adServerURL:
  196. ad_info = {
  197. '_type': 'url',
  198. 'url': adServerURL,
  199. }
  200. if 'url' in info:
  201. return {
  202. '_type': 'playlist',
  203. 'title': info['title'],
  204. 'entries': [ad_info, info],
  205. }
  206. else:
  207. return ad_info
  208. if 'url' not in info and not info.get('formats'):
  209. raise ExtractorError('Unable to extract video url for %s' % info['id'])
  210. return info