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.

246 lines
10 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 webpage, returns None
  116. if it can't be found
  117. """
  118. urls = cls._extract_brightcove_urls(webpage)
  119. return urls[0] if urls else None
  120. @classmethod
  121. def _extract_brightcove_urls(cls, webpage):
  122. """Return a list of all Brightcove URLs from the webpage """
  123. url_m = re.search(r'<meta\s+property="og:video"\s+content="(http://c.brightcove.com/[^"]+)"', webpage)
  124. if url_m:
  125. return [url_m.group(1)]
  126. matches = re.findall(
  127. r'''(?sx)<object
  128. (?:
  129. [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
  130. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  131. ).+?</object>''',
  132. webpage)
  133. return [cls._build_brighcove_url(m) for m in matches]
  134. def _real_extract(self, url):
  135. url, smuggled_data = unsmuggle_url(url, {})
  136. # Change the 'videoId' and others field to '@videoPlayer'
  137. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  138. # Change bckey (used by bcove.me urls) to playerKey
  139. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  140. mobj = re.match(self._VALID_URL, url)
  141. query_str = mobj.group('query')
  142. query = compat_urlparse.parse_qs(query_str)
  143. videoPlayer = query.get('@videoPlayer')
  144. if videoPlayer:
  145. # We set the original url as the default 'Referer' header
  146. referer = smuggled_data.get('Referer', url)
  147. return self._get_video_info(
  148. videoPlayer[0], query_str, query, referer=referer)
  149. else:
  150. player_key = query['playerKey']
  151. return self._get_playlist_info(player_key[0])
  152. def _get_video_info(self, video_id, query_str, query, referer=None):
  153. request_url = self._FEDERATED_URL_TEMPLATE % query_str
  154. req = compat_urllib_request.Request(request_url)
  155. linkBase = query.get('linkBaseURL')
  156. if linkBase is not None:
  157. referer = linkBase[0]
  158. if referer is not None:
  159. req.add_header('Referer', referer)
  160. webpage = self._download_webpage(req, video_id)
  161. self.report_extraction(video_id)
  162. info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
  163. info = json.loads(info)['data']
  164. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  165. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  166. return self._extract_video_info(video_info)
  167. def _get_playlist_info(self, player_key):
  168. info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
  169. playlist_info = self._download_webpage(
  170. info_url, player_key, 'Downloading playlist information')
  171. json_data = json.loads(playlist_info)
  172. if 'videoList' not in json_data:
  173. raise ExtractorError('Empty playlist')
  174. playlist_info = json_data['videoList']
  175. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  176. return self.playlist_result(videos, playlist_id=playlist_info['id'],
  177. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  178. def _extract_video_info(self, video_info):
  179. info = {
  180. 'id': compat_str(video_info['id']),
  181. 'title': video_info['displayName'].strip(),
  182. 'description': video_info.get('shortDescription'),
  183. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  184. 'uploader': video_info.get('publisherName'),
  185. }
  186. renditions = video_info.get('renditions')
  187. if renditions:
  188. renditions = sorted(renditions, key=lambda r: r['size'])
  189. info['formats'] = [{
  190. 'url': rend['defaultURL'],
  191. 'height': rend.get('frameHeight'),
  192. 'width': rend.get('frameWidth'),
  193. } for rend in renditions]
  194. elif video_info.get('FLVFullLengthURL') is not None:
  195. info.update({
  196. 'url': video_info['FLVFullLengthURL'],
  197. })
  198. if self._downloader.params.get('include_ads', False):
  199. adServerURL = video_info.get('_youtubedl_adServerURL')
  200. if adServerURL:
  201. ad_info = {
  202. '_type': 'url',
  203. 'url': adServerURL,
  204. }
  205. if 'url' in info:
  206. return {
  207. '_type': 'playlist',
  208. 'title': info['title'],
  209. 'entries': [ad_info, info],
  210. }
  211. else:
  212. return ad_info
  213. if 'url' not in info and not info.get('formats'):
  214. raise ExtractorError('Unable to extract video url for %s' % info['id'])
  215. return info