brightcove.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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,
  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. js_to_json,
  24. float_or_none,
  25. int_or_none,
  26. parse_iso8601,
  27. extract_attributes,
  28. )
  29. class BrightcoveLegacyIE(InfoExtractor):
  30. IE_NAME = 'brightcove:legacy'
  31. _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
  32. _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
  33. _TESTS = [
  34. {
  35. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  36. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  37. 'md5': '5423e113865d26e40624dce2e4b45d95',
  38. 'note': 'Test Brightcove downloads and detection in GenericIE',
  39. 'info_dict': {
  40. 'id': '2371591881001',
  41. 'ext': 'mp4',
  42. 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  43. 'uploader': '8TV',
  44. 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
  45. }
  46. },
  47. {
  48. # From http://medianetwork.oracle.com/video/player/1785452137001
  49. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  50. 'info_dict': {
  51. 'id': '1785452137001',
  52. 'ext': 'flv',
  53. 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  54. 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  55. 'uploader': 'Oracle',
  56. },
  57. },
  58. {
  59. # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
  60. 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
  61. 'info_dict': {
  62. 'id': '2750934548001',
  63. 'ext': 'mp4',
  64. 'title': 'This Bracelet Acts as a Personal Thermostat',
  65. 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
  66. 'uploader': 'Mashable',
  67. },
  68. },
  69. {
  70. # test that the default referer works
  71. # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
  72. 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
  73. 'info_dict': {
  74. 'id': '2878862109001',
  75. 'ext': 'mp4',
  76. 'title': 'Lost in Motion II',
  77. 'description': 'md5:363109c02998fee92ec02211bd8000df',
  78. 'uploader': 'National Ballet of Canada',
  79. },
  80. },
  81. {
  82. # test flv videos served by akamaihd.net
  83. # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
  84. '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',
  85. # The md5 checksum changes on each download
  86. 'info_dict': {
  87. 'id': '2996102916001',
  88. 'ext': 'flv',
  89. 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  90. 'uploader': 'Red Bull TV',
  91. 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  92. },
  93. },
  94. {
  95. # playlist test
  96. # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
  97. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
  98. 'info_dict': {
  99. 'title': 'Sealife',
  100. 'id': '3550319591001',
  101. },
  102. 'playlist_mincount': 7,
  103. },
  104. ]
  105. @classmethod
  106. def _build_brighcove_url(cls, object_str):
  107. """
  108. Build a Brightcove url from a xml string containing
  109. <object class="BrightcoveExperience">{params}</object>
  110. """
  111. # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
  112. object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
  113. lambda m: m.group(1) + '/>', object_str)
  114. # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
  115. object_str = object_str.replace('<--', '<!--')
  116. # remove namespace to simplify extraction
  117. object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
  118. object_str = fix_xml_ampersands(object_str)
  119. try:
  120. object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
  121. except compat_xml_parse_error:
  122. return
  123. fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
  124. if fv_el is not None:
  125. flashvars = dict(
  126. (k, v[0])
  127. for k, v in compat_parse_qs(fv_el.attrib['value']).items())
  128. else:
  129. flashvars = {}
  130. def find_param(name):
  131. if name in flashvars:
  132. return flashvars[name]
  133. node = find_xpath_attr(object_doc, './param', 'name', name)
  134. if node is not None:
  135. return node.attrib['value']
  136. return None
  137. params = {}
  138. playerID = find_param('playerID')
  139. if playerID is None:
  140. raise ExtractorError('Cannot find player ID')
  141. params['playerID'] = playerID
  142. playerKey = find_param('playerKey')
  143. # Not all pages define this value
  144. if playerKey is not None:
  145. params['playerKey'] = playerKey
  146. # The three fields hold the id of the video
  147. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
  148. if videoPlayer is not None:
  149. params['@videoPlayer'] = videoPlayer
  150. linkBase = find_param('linkBaseURL')
  151. if linkBase is not None:
  152. params['linkBaseURL'] = linkBase
  153. return cls._make_brightcove_url(params)
  154. @classmethod
  155. def _build_brighcove_url_from_js(cls, object_js):
  156. # The layout of JS is as follows:
  157. # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
  158. # // build Brightcove <object /> XML
  159. # }
  160. m = re.search(
  161. r'''(?x)customBC.\createVideo\(
  162. .*? # skipping width and height
  163. ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
  164. ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
  165. # in length, however it's appended to itself
  166. # in places, so truncate
  167. ["\'](?P<videoID>\d+)["\'] # @videoPlayer
  168. ''', object_js)
  169. if m:
  170. return cls._make_brightcove_url(m.groupdict())
  171. @classmethod
  172. def _make_brightcove_url(cls, params):
  173. data = compat_urllib_parse.urlencode(params)
  174. return cls._FEDERATED_URL_TEMPLATE % data
  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_str, 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_str, query, referer=None):
  229. request_url = self._FEDERATED_URL_TEMPLATE % query_str
  230. req = compat_urllib_request.Request(request_url)
  231. linkBase = query.get('linkBaseURL')
  232. if linkBase is not None:
  233. referer = linkBase[0]
  234. if referer is not None:
  235. req.add_header('Referer', referer)
  236. webpage = self._download_webpage(req, video_id)
  237. error_msg = self._html_search_regex(
  238. r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
  239. 'error message', default=None)
  240. if error_msg is not None:
  241. raise ExtractorError(
  242. 'brightcove said: %s' % error_msg, expected=True)
  243. self.report_extraction(video_id)
  244. info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
  245. info = json.loads(info)['data']
  246. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  247. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  248. return self._extract_video_info(video_info)
  249. def _get_playlist_info(self, player_key):
  250. info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
  251. playlist_info = self._download_webpage(
  252. info_url, player_key, 'Downloading playlist information')
  253. json_data = json.loads(playlist_info)
  254. if 'videoList' not in json_data:
  255. raise ExtractorError('Empty playlist')
  256. playlist_info = json_data['videoList']
  257. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  258. return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
  259. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  260. def _extract_video_info(self, video_info):
  261. info = {
  262. 'id': compat_str(video_info['id']),
  263. 'title': video_info['displayName'].strip(),
  264. 'description': video_info.get('shortDescription'),
  265. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  266. 'uploader': video_info.get('publisherName'),
  267. }
  268. renditions = video_info.get('renditions')
  269. if renditions:
  270. formats = []
  271. for rend in renditions:
  272. url = rend['defaultURL']
  273. if not url:
  274. continue
  275. ext = None
  276. if rend['remote']:
  277. url_comp = compat_urllib_parse_urlparse(url)
  278. if url_comp.path.endswith('.m3u8'):
  279. formats.extend(
  280. self._extract_m3u8_formats(url, info['id'], 'mp4'))
  281. continue
  282. elif 'akamaihd.net' in url_comp.netloc:
  283. # This type of renditions are served through
  284. # akamaihd.net, but they don't use f4m manifests
  285. url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
  286. ext = 'flv'
  287. if ext is None:
  288. ext = determine_ext(url)
  289. size = rend.get('size')
  290. formats.append({
  291. 'url': url,
  292. 'ext': ext,
  293. 'height': rend.get('frameHeight'),
  294. 'width': rend.get('frameWidth'),
  295. 'filesize': size if size != 0 else None,
  296. })
  297. self._sort_formats(formats)
  298. info['formats'] = formats
  299. elif video_info.get('FLVFullLengthURL') is not None:
  300. info.update({
  301. 'url': video_info['FLVFullLengthURL'],
  302. })
  303. if self._downloader.params.get('include_ads', False):
  304. adServerURL = video_info.get('_youtubedl_adServerURL')
  305. if adServerURL:
  306. ad_info = {
  307. '_type': 'url',
  308. 'url': adServerURL,
  309. }
  310. if 'url' in info:
  311. return {
  312. '_type': 'playlist',
  313. 'title': info['title'],
  314. 'entries': [ad_info, info],
  315. }
  316. else:
  317. return ad_info
  318. if 'url' not in info and not info.get('formats'):
  319. raise ExtractorError('Unable to extract video url for %s' % info['id'])
  320. return info
  321. class BrightcoveNewIE(InfoExtractor):
  322. IE_NAME = 'brightcove:new'
  323. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+)'
  324. _TEST = {
  325. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  326. 'md5': 'c8100925723840d4b0d243f7025703be',
  327. 'info_dict': {
  328. 'id': '4463358922001',
  329. 'ext': 'mp4',
  330. 'title': 'Meet the man behind Popcorn Time',
  331. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  332. 'timestamp': 1441391203,
  333. 'upload_date': '20150904',
  334. 'duration': 165768,
  335. 'uploader_id': '929656772001',
  336. }
  337. }
  338. @staticmethod
  339. def _extract_urls(webpage):
  340. # Reference:
  341. # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
  342. # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript)
  343. # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
  344. entries = []
  345. # Look for iframe embeds [1]
  346. for _, url in re.findall(
  347. r'<iframe[^>]+src=(["\'])((?:https?:)//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
  348. entries.append(url)
  349. # Look for embed_in_page embeds [2]
  350. # According to examples from [3] it's unclear whether video id may be optional
  351. # and what to do when it is
  352. for video_id, account_id, player_id, embed in re.findall(
  353. r'''(?sx)
  354. <video[^>]+
  355. data-video-id=["\'](\d+)["\'][^>]*>.*?
  356. </video>.*?
  357. <script[^>]+
  358. src=["\'](?:https?:)?//players\.brightcove\.net/
  359. (\d+)/([\da-f-]+)_([^/]+)/index\.min\.js
  360. ''', webpage):
  361. entries.append(
  362. 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
  363. % (account_id, player_id, embed, video_id))
  364. return entries
  365. def _real_extract(self, url):
  366. account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
  367. webpage = self._download_webpage(
  368. 'http://players.brightcove.net/%s/%s_%s/index.min.js'
  369. % (account_id, player_id, embed), video_id)
  370. policy_key = None
  371. catalog = self._search_regex(
  372. r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
  373. if catalog:
  374. catalog = self._parse_json(
  375. js_to_json(catalog), video_id, fatal=False)
  376. if catalog:
  377. policy_key = catalog.get('policyKey')
  378. if not policy_key:
  379. policy_key = self._search_regex(
  380. r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
  381. webpage, 'policy key', group='pk')
  382. req = compat_urllib_request.Request(
  383. 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s'
  384. % (account_id, video_id),
  385. headers={'Accept': 'application/json;pk=%s' % policy_key})
  386. json_data = self._download_json(req, video_id)
  387. title = json_data['name']
  388. formats = []
  389. for source in json_data.get('sources', []):
  390. source_type = source.get('type')
  391. src = source.get('src')
  392. if source_type == 'application/x-mpegURL':
  393. if not src:
  394. continue
  395. m3u8_formats = self._extract_m3u8_formats(
  396. src, video_id, 'mp4', entry_protocol='m3u8_native',
  397. m3u8_id='hls', fatal=False)
  398. if m3u8_formats:
  399. formats.extend(m3u8_formats)
  400. else:
  401. streaming_src = source.get('streaming_src')
  402. stream_name, app_name = source.get('stream_name'), source.get('app_name')
  403. if not src and not streaming_src and (not stream_name or not app_name):
  404. continue
  405. tbr = float_or_none(source.get('avg_bitrate'), 1000)
  406. height = int_or_none(source.get('height'))
  407. f = {
  408. 'tbr': tbr,
  409. 'width': int_or_none(source.get('width')),
  410. 'height': height,
  411. 'filesize': int_or_none(source.get('size')),
  412. 'container': source.get('container'),
  413. 'vcodec': source.get('codec'),
  414. 'ext': source.get('container').lower(),
  415. }
  416. def build_format_id(kind):
  417. format_id = kind
  418. if tbr:
  419. format_id += '-%dk' % int(tbr)
  420. if height:
  421. format_id += '-%dp' % height
  422. return format_id
  423. if src or streaming_src:
  424. f.update({
  425. 'url': src or streaming_src,
  426. 'format_id': build_format_id('http' if src else 'http-streaming'),
  427. 'preference': 2 if src else 1,
  428. })
  429. else:
  430. f.update({
  431. 'url': app_name,
  432. 'play_path': stream_name,
  433. 'format_id': build_format_id('rtmp'),
  434. })
  435. formats.append(f)
  436. self._sort_formats(formats)
  437. description = json_data.get('description')
  438. thumbnail = json_data.get('thumbnail')
  439. timestamp = parse_iso8601(json_data.get('published_at'))
  440. duration = float_or_none(json_data.get('duration'), 1000)
  441. tags = json_data.get('tags', [])
  442. return {
  443. 'id': video_id,
  444. 'title': title,
  445. 'description': description,
  446. 'thumbnail': thumbnail,
  447. 'duration': duration,
  448. 'timestamp': timestamp,
  449. 'uploader_id': account_id,
  450. 'formats': formats,
  451. 'tags': tags,
  452. }