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.

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