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.

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