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.

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