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.

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