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.

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