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.

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