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.

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