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.

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