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.

320 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 ..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. data = compat_urllib_parse.urlencode(params)
  147. return cls._FEDERATED_URL_TEMPLATE % data
  148. @classmethod
  149. def _extract_brightcove_url(cls, webpage):
  150. """Try to extract the brightcove url from the webpage, returns None
  151. if it can't be found
  152. """
  153. urls = cls._extract_brightcove_urls(webpage)
  154. return urls[0] if urls else None
  155. @classmethod
  156. def _extract_brightcove_urls(cls, webpage):
  157. """Return a list of all Brightcove URLs from the webpage """
  158. url_m = re.search(
  159. r'<meta\s+property="og:video"\s+content="(https?://(?:secure|c)\.brightcove.com/[^"]+)"',
  160. webpage)
  161. if url_m:
  162. url = unescapeHTML(url_m.group(1))
  163. # Some sites don't add it, we can't download with this url, for example:
  164. # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
  165. if 'playerKey' in url or 'videoId' in url:
  166. return [url]
  167. matches = re.findall(
  168. r'''(?sx)<object
  169. (?:
  170. [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
  171. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  172. ).+?>\s*</object>''',
  173. webpage)
  174. return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
  175. def _real_extract(self, url):
  176. url, smuggled_data = unsmuggle_url(url, {})
  177. # Change the 'videoId' and others field to '@videoPlayer'
  178. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  179. # Change bckey (used by bcove.me urls) to playerKey
  180. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  181. mobj = re.match(self._VALID_URL, url)
  182. query_str = mobj.group('query')
  183. query = compat_urlparse.parse_qs(query_str)
  184. videoPlayer = query.get('@videoPlayer')
  185. if videoPlayer:
  186. # We set the original url as the default 'Referer' header
  187. referer = smuggled_data.get('Referer', url)
  188. return self._get_video_info(
  189. videoPlayer[0], query_str, query, referer=referer)
  190. elif 'playerKey' in query:
  191. player_key = query['playerKey']
  192. return self._get_playlist_info(player_key[0])
  193. else:
  194. raise ExtractorError(
  195. 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
  196. expected=True)
  197. def _get_video_info(self, video_id, query_str, query, referer=None):
  198. request_url = self._FEDERATED_URL_TEMPLATE % query_str
  199. req = compat_urllib_request.Request(request_url)
  200. linkBase = query.get('linkBaseURL')
  201. if linkBase is not None:
  202. referer = linkBase[0]
  203. if referer is not None:
  204. req.add_header('Referer', referer)
  205. webpage = self._download_webpage(req, video_id)
  206. error_msg = self._html_search_regex(
  207. r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
  208. 'error message', default=None)
  209. if error_msg is not None:
  210. raise ExtractorError(
  211. 'brightcove said: %s' % error_msg, expected=True)
  212. self.report_extraction(video_id)
  213. info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
  214. info = json.loads(info)['data']
  215. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  216. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  217. return self._extract_video_info(video_info)
  218. def _get_playlist_info(self, player_key):
  219. info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
  220. playlist_info = self._download_webpage(
  221. info_url, player_key, 'Downloading playlist information')
  222. json_data = json.loads(playlist_info)
  223. if 'videoList' not in json_data:
  224. raise ExtractorError('Empty playlist')
  225. playlist_info = json_data['videoList']
  226. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  227. return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
  228. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  229. def _extract_video_info(self, video_info):
  230. info = {
  231. 'id': compat_str(video_info['id']),
  232. 'title': video_info['displayName'].strip(),
  233. 'description': video_info.get('shortDescription'),
  234. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  235. 'uploader': video_info.get('publisherName'),
  236. }
  237. renditions = video_info.get('renditions')
  238. if renditions:
  239. formats = []
  240. for rend in renditions:
  241. url = rend['defaultURL']
  242. if not url:
  243. continue
  244. ext = None
  245. if rend['remote']:
  246. url_comp = compat_urllib_parse_urlparse(url)
  247. if url_comp.path.endswith('.m3u8'):
  248. formats.extend(
  249. self._extract_m3u8_formats(url, info['id'], 'mp4'))
  250. continue
  251. elif 'akamaihd.net' in url_comp.netloc:
  252. # This type of renditions are served through
  253. # akamaihd.net, but they don't use f4m manifests
  254. url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
  255. ext = 'flv'
  256. if ext is None:
  257. ext = determine_ext(url)
  258. size = rend.get('size')
  259. formats.append({
  260. 'url': url,
  261. 'ext': ext,
  262. 'height': rend.get('frameHeight'),
  263. 'width': rend.get('frameWidth'),
  264. 'filesize': size if size != 0 else None,
  265. })
  266. self._sort_formats(formats)
  267. info['formats'] = formats
  268. elif video_info.get('FLVFullLengthURL') is not None:
  269. info.update({
  270. 'url': video_info['FLVFullLengthURL'],
  271. })
  272. if self._downloader.params.get('include_ads', False):
  273. adServerURL = video_info.get('_youtubedl_adServerURL')
  274. if adServerURL:
  275. ad_info = {
  276. '_type': 'url',
  277. 'url': adServerURL,
  278. }
  279. if 'url' in info:
  280. return {
  281. '_type': 'playlist',
  282. 'title': info['title'],
  283. 'entries': [ad_info, info],
  284. }
  285. else:
  286. return ad_info
  287. if 'url' not in info and not info.get('formats'):
  288. raise ExtractorError('Unable to extract video url for %s' % info['id'])
  289. return info