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.

563 lines
24 KiB

  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import json
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_etree_fromstring,
  8. compat_parse_qs,
  9. compat_str,
  10. compat_urllib_parse_urlparse,
  11. compat_urlparse,
  12. compat_xml_parse_error,
  13. compat_HTTPError,
  14. )
  15. from ..utils import (
  16. determine_ext,
  17. ExtractorError,
  18. find_xpath_attr,
  19. fix_xml_ampersands,
  20. float_or_none,
  21. js_to_json,
  22. int_or_none,
  23. parse_iso8601,
  24. unescapeHTML,
  25. unsmuggle_url,
  26. update_url_query,
  27. )
  28. class BrightcoveLegacyIE(InfoExtractor):
  29. IE_NAME = 'brightcove:legacy'
  30. _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
  31. _FEDERATED_URL = 'http://c.brightcove.com/services/viewer/htmlFederated'
  32. _TESTS = [
  33. {
  34. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  35. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  36. 'md5': '5423e113865d26e40624dce2e4b45d95',
  37. 'note': 'Test Brightcove downloads and detection in GenericIE',
  38. 'info_dict': {
  39. 'id': '2371591881001',
  40. 'ext': 'mp4',
  41. 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  42. 'uploader': '8TV',
  43. 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
  44. }
  45. },
  46. {
  47. # From http://medianetwork.oracle.com/video/player/1785452137001
  48. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  49. 'info_dict': {
  50. 'id': '1785452137001',
  51. 'ext': 'flv',
  52. 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  53. 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  54. 'uploader': 'Oracle',
  55. },
  56. },
  57. {
  58. # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
  59. 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
  60. 'info_dict': {
  61. 'id': '2750934548001',
  62. 'ext': 'mp4',
  63. 'title': 'This Bracelet Acts as a Personal Thermostat',
  64. 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
  65. 'uploader': 'Mashable',
  66. },
  67. },
  68. {
  69. # test that the default referer works
  70. # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
  71. 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
  72. 'info_dict': {
  73. 'id': '2878862109001',
  74. 'ext': 'mp4',
  75. 'title': 'Lost in Motion II',
  76. 'description': 'md5:363109c02998fee92ec02211bd8000df',
  77. 'uploader': 'National Ballet of Canada',
  78. },
  79. },
  80. {
  81. # test flv videos served by akamaihd.net
  82. # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
  83. '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',
  84. # The md5 checksum changes on each download
  85. 'info_dict': {
  86. 'id': '2996102916001',
  87. 'ext': 'flv',
  88. 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  89. 'uploader': 'Red Bull TV',
  90. 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  91. },
  92. },
  93. {
  94. # playlist test
  95. # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
  96. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
  97. 'info_dict': {
  98. 'title': 'Sealife',
  99. 'id': '3550319591001',
  100. },
  101. 'playlist_mincount': 7,
  102. },
  103. ]
  104. @classmethod
  105. def _build_brighcove_url(cls, object_str):
  106. """
  107. Build a Brightcove url from a xml string containing
  108. <object class="BrightcoveExperience">{params}</object>
  109. """
  110. # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
  111. object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
  112. lambda m: m.group(1) + '/>', object_str)
  113. # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
  114. object_str = object_str.replace('<--', '<!--')
  115. # remove namespace to simplify extraction
  116. object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
  117. object_str = fix_xml_ampersands(object_str)
  118. try:
  119. object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
  120. except compat_xml_parse_error:
  121. return
  122. fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
  123. if fv_el is not None:
  124. flashvars = dict(
  125. (k, v[0])
  126. for k, v in compat_parse_qs(fv_el.attrib['value']).items())
  127. else:
  128. flashvars = {}
  129. data_url = object_doc.attrib.get('data', '')
  130. data_url_params = compat_parse_qs(compat_urllib_parse_urlparse(data_url).query)
  131. def find_param(name):
  132. if name in flashvars:
  133. return flashvars[name]
  134. node = find_xpath_attr(object_doc, './param', 'name', name)
  135. if node is not None:
  136. return node.attrib['value']
  137. return data_url_params.get(name)
  138. params = {}
  139. playerID = find_param('playerID')
  140. if playerID is None:
  141. raise ExtractorError('Cannot find player ID')
  142. params['playerID'] = playerID
  143. playerKey = find_param('playerKey')
  144. # Not all pages define this value
  145. if playerKey is not None:
  146. params['playerKey'] = playerKey
  147. # These fields hold the id of the video
  148. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
  149. if videoPlayer is not None:
  150. params['@videoPlayer'] = videoPlayer
  151. linkBase = find_param('linkBaseURL')
  152. if linkBase is not None:
  153. params['linkBaseURL'] = linkBase
  154. return cls._make_brightcove_url(params)
  155. @classmethod
  156. def _build_brighcove_url_from_js(cls, object_js):
  157. # The layout of JS is as follows:
  158. # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
  159. # // build Brightcove <object /> XML
  160. # }
  161. m = re.search(
  162. r'''(?x)customBC.\createVideo\(
  163. .*? # skipping width and height
  164. ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
  165. ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
  166. # in length, however it's appended to itself
  167. # in places, so truncate
  168. ["\'](?P<videoID>\d+)["\'] # @videoPlayer
  169. ''', object_js)
  170. if m:
  171. return cls._make_brightcove_url(m.groupdict())
  172. @classmethod
  173. def _make_brightcove_url(cls, params):
  174. return update_url_query(cls._FEDERATED_URL, params)
  175. @classmethod
  176. def _extract_brightcove_url(cls, webpage):
  177. """Try to extract the brightcove url from the webpage, returns None
  178. if it can't be found
  179. """
  180. urls = cls._extract_brightcove_urls(webpage)
  181. return urls[0] if urls else None
  182. @classmethod
  183. def _extract_brightcove_urls(cls, webpage):
  184. """Return a list of all Brightcove URLs from the webpage """
  185. url_m = re.search(
  186. r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
  187. webpage)
  188. if url_m:
  189. url = unescapeHTML(url_m.group(1))
  190. # Some sites don't add it, we can't download with this url, for example:
  191. # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
  192. if 'playerKey' in url or 'videoId' in url:
  193. return [url]
  194. matches = re.findall(
  195. r'''(?sx)<object
  196. (?:
  197. [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
  198. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  199. ).+?>\s*</object>''',
  200. webpage)
  201. if matches:
  202. return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
  203. return list(filter(None, [
  204. cls._build_brighcove_url_from_js(custom_bc)
  205. for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
  206. def _real_extract(self, url):
  207. url, smuggled_data = unsmuggle_url(url, {})
  208. # Change the 'videoId' and others field to '@videoPlayer'
  209. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  210. # Change bckey (used by bcove.me urls) to playerKey
  211. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  212. mobj = re.match(self._VALID_URL, url)
  213. query_str = mobj.group('query')
  214. query = compat_urlparse.parse_qs(query_str)
  215. videoPlayer = query.get('@videoPlayer')
  216. if videoPlayer:
  217. # We set the original url as the default 'Referer' header
  218. referer = smuggled_data.get('Referer', url)
  219. return self._get_video_info(
  220. videoPlayer[0], query, referer=referer)
  221. elif 'playerKey' in query:
  222. player_key = query['playerKey']
  223. return self._get_playlist_info(player_key[0])
  224. else:
  225. raise ExtractorError(
  226. 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
  227. expected=True)
  228. def _get_video_info(self, video_id, query, referer=None):
  229. headers = {}
  230. linkBase = query.get('linkBaseURL')
  231. if linkBase is not None:
  232. referer = linkBase[0]
  233. if referer is not None:
  234. headers['Referer'] = referer
  235. webpage = self._download_webpage(self._FEDERATED_URL, video_id, headers=headers, query=query)
  236. error_msg = self._html_search_regex(
  237. r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
  238. 'error message', default=None)
  239. if error_msg is not None:
  240. raise ExtractorError(
  241. 'brightcove said: %s' % error_msg, expected=True)
  242. self.report_extraction(video_id)
  243. info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
  244. info = json.loads(info)['data']
  245. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  246. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  247. return self._extract_video_info(video_info)
  248. def _get_playlist_info(self, player_key):
  249. info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
  250. playlist_info = self._download_webpage(
  251. info_url, player_key, 'Downloading playlist information')
  252. json_data = json.loads(playlist_info)
  253. if 'videoList' not in json_data:
  254. raise ExtractorError('Empty playlist')
  255. playlist_info = json_data['videoList']
  256. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  257. return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
  258. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  259. def _extract_video_info(self, video_info):
  260. info = {
  261. 'id': compat_str(video_info['id']),
  262. 'title': video_info['displayName'].strip(),
  263. 'description': video_info.get('shortDescription'),
  264. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  265. 'uploader': video_info.get('publisherName'),
  266. }
  267. renditions = video_info.get('renditions', []) + video_info.get('IOSRenditions', [])
  268. if renditions:
  269. formats = []
  270. for rend in renditions:
  271. url = rend['defaultURL']
  272. if not url:
  273. continue
  274. ext = None
  275. if rend['remote']:
  276. url_comp = compat_urllib_parse_urlparse(url)
  277. if url_comp.path.endswith('.m3u8'):
  278. formats.extend(
  279. self._extract_m3u8_formats(url, info['id'], 'mp4'))
  280. continue
  281. elif 'akamaihd.net' in url_comp.netloc:
  282. # This type of renditions are served through
  283. # akamaihd.net, but they don't use f4m manifests
  284. url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
  285. ext = 'flv'
  286. if ext is None:
  287. ext = determine_ext(url)
  288. size = rend.get('size')
  289. a_format = {
  290. 'url': url,
  291. 'ext': ext,
  292. 'height': rend.get('frameHeight'),
  293. 'width': rend.get('frameWidth'),
  294. 'filesize': size if size != 0 else None,
  295. }
  296. # m3u8 manifests with remote == false are media playlists
  297. # Not calling _extract_m3u8_formats here to save network traffic
  298. if ext == 'm3u8':
  299. a_format.update({
  300. 'ext': 'mp4',
  301. 'protocol': 'm3u8',
  302. })
  303. formats.append(a_format)
  304. self._sort_formats(formats)
  305. info['formats'] = formats
  306. elif video_info.get('FLVFullLengthURL') is not None:
  307. info.update({
  308. 'url': video_info['FLVFullLengthURL'],
  309. })
  310. if self._downloader.params.get('include_ads', False):
  311. adServerURL = video_info.get('_youtubedl_adServerURL')
  312. if adServerURL:
  313. ad_info = {
  314. '_type': 'url',
  315. 'url': adServerURL,
  316. }
  317. if 'url' in info:
  318. return {
  319. '_type': 'playlist',
  320. 'title': info['title'],
  321. 'entries': [ad_info, info],
  322. }
  323. else:
  324. return ad_info
  325. if 'url' not in info and not info.get('formats'):
  326. raise ExtractorError('Unable to extract video url for %s' % info['id'])
  327. return info
  328. class BrightcoveNewIE(InfoExtractor):
  329. IE_NAME = 'brightcove:new'
  330. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
  331. _TESTS = [{
  332. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  333. 'md5': 'c8100925723840d4b0d243f7025703be',
  334. 'info_dict': {
  335. 'id': '4463358922001',
  336. 'ext': 'mp4',
  337. 'title': 'Meet the man behind Popcorn Time',
  338. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  339. 'duration': 165.768,
  340. 'timestamp': 1441391203,
  341. 'upload_date': '20150904',
  342. 'uploader_id': '929656772001',
  343. 'formats': 'mincount:22',
  344. },
  345. }, {
  346. # with rtmp streams
  347. 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
  348. 'info_dict': {
  349. 'id': '4279049078001',
  350. 'ext': 'mp4',
  351. 'title': 'Titansgrave: Chapter 0',
  352. 'description': 'Titansgrave: Chapter 0',
  353. 'duration': 1242.058,
  354. 'timestamp': 1433556729,
  355. 'upload_date': '20150606',
  356. 'uploader_id': '4036320279001',
  357. 'formats': 'mincount:41',
  358. },
  359. 'params': {
  360. 'skip_download': True,
  361. }
  362. }, {
  363. # ref: prefixed video id
  364. 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
  365. 'only_matching': True,
  366. }, {
  367. # non numeric ref: prefixed video id
  368. 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
  369. 'only_matching': True,
  370. }]
  371. @staticmethod
  372. def _extract_url(webpage):
  373. urls = BrightcoveNewIE._extract_urls(webpage)
  374. return urls[0] if urls else None
  375. @staticmethod
  376. def _extract_urls(webpage):
  377. # Reference:
  378. # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
  379. # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
  380. # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
  381. # 4. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
  382. entries = []
  383. # Look for iframe embeds [1]
  384. for _, url in re.findall(
  385. r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
  386. entries.append(url if url.startswith('http') else 'http:' + url)
  387. # Look for embed_in_page embeds [2]
  388. for video_id, account_id, player_id, embed in re.findall(
  389. # According to examples from [3] it's unclear whether video id
  390. # may be optional and what to do when it is
  391. # According to [4] data-video-id may be prefixed with ref:
  392. r'''(?sx)
  393. <video[^>]+
  394. data-video-id=["\'](\d+|ref:[^"\']+)["\'][^>]*>.*?
  395. </video>.*?
  396. <script[^>]+
  397. src=["\'](?:https?:)?//players\.brightcove\.net/
  398. (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
  399. ''', webpage):
  400. entries.append(
  401. 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
  402. % (account_id, player_id, embed, video_id))
  403. return entries
  404. def _real_extract(self, url):
  405. account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
  406. webpage = self._download_webpage(
  407. 'http://players.brightcove.net/%s/%s_%s/index.min.js'
  408. % (account_id, player_id, embed), video_id)
  409. policy_key = None
  410. catalog = self._search_regex(
  411. r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
  412. if catalog:
  413. catalog = self._parse_json(
  414. js_to_json(catalog), video_id, fatal=False)
  415. if catalog:
  416. policy_key = catalog.get('policyKey')
  417. if not policy_key:
  418. policy_key = self._search_regex(
  419. r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
  420. webpage, 'policy key', group='pk')
  421. api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
  422. try:
  423. json_data = self._download_json(api_url, video_id, headers={
  424. 'Accept': 'application/json;pk=%s' % policy_key
  425. })
  426. except ExtractorError as e:
  427. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  428. json_data = self._parse_json(e.cause.read().decode(), video_id)
  429. raise ExtractorError(json_data[0]['message'], expected=True)
  430. raise
  431. title = json_data['name']
  432. formats = []
  433. for source in json_data.get('sources', []):
  434. container = source.get('container')
  435. source_type = source.get('type')
  436. src = source.get('src')
  437. if source_type == 'application/x-mpegURL' or container == 'M2TS':
  438. if not src:
  439. continue
  440. formats.extend(self._extract_m3u8_formats(
  441. src, video_id, 'mp4', m3u8_id='hls', fatal=False))
  442. elif source_type == 'application/dash+xml':
  443. if not src:
  444. continue
  445. formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
  446. else:
  447. streaming_src = source.get('streaming_src')
  448. stream_name, app_name = source.get('stream_name'), source.get('app_name')
  449. if not src and not streaming_src and (not stream_name or not app_name):
  450. continue
  451. tbr = float_or_none(source.get('avg_bitrate'), 1000)
  452. height = int_or_none(source.get('height'))
  453. width = int_or_none(source.get('width'))
  454. f = {
  455. 'tbr': tbr,
  456. 'filesize': int_or_none(source.get('size')),
  457. 'container': container,
  458. 'ext': container.lower(),
  459. }
  460. if width == 0 and height == 0:
  461. f.update({
  462. 'vcodec': 'none',
  463. })
  464. else:
  465. f.update({
  466. 'width': width,
  467. 'height': height,
  468. 'vcodec': source.get('codec'),
  469. })
  470. def build_format_id(kind):
  471. format_id = kind
  472. if tbr:
  473. format_id += '-%dk' % int(tbr)
  474. if height:
  475. format_id += '-%dp' % height
  476. return format_id
  477. if src or streaming_src:
  478. f.update({
  479. 'url': src or streaming_src,
  480. 'format_id': build_format_id('http' if src else 'http-streaming'),
  481. 'preference': 2 if src else 1,
  482. })
  483. else:
  484. f.update({
  485. 'url': app_name,
  486. 'play_path': stream_name,
  487. 'format_id': build_format_id('rtmp'),
  488. })
  489. formats.append(f)
  490. self._sort_formats(formats)
  491. description = json_data.get('description')
  492. thumbnail = json_data.get('thumbnail')
  493. timestamp = parse_iso8601(json_data.get('published_at'))
  494. duration = float_or_none(json_data.get('duration'), 1000)
  495. tags = json_data.get('tags', [])
  496. return {
  497. 'id': video_id,
  498. 'title': title,
  499. 'description': description,
  500. 'thumbnail': thumbnail,
  501. 'duration': duration,
  502. 'timestamp': timestamp,
  503. 'uploader_id': account_id,
  504. 'formats': formats,
  505. 'tags': tags,
  506. }