brightcove.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. int_or_none,
  25. parse_iso8601,
  26. extract_attributes,
  27. )
  28. class BrightcoveIE(InfoExtractor):
  29. _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
  30. _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
  31. _TESTS = [
  32. {
  33. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  34. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  35. 'md5': '5423e113865d26e40624dce2e4b45d95',
  36. 'note': 'Test Brightcove downloads and detection in GenericIE',
  37. 'info_dict': {
  38. 'id': '2371591881001',
  39. 'ext': 'mp4',
  40. 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  41. 'uploader': '8TV',
  42. 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
  43. }
  44. },
  45. {
  46. # From http://medianetwork.oracle.com/video/player/1785452137001
  47. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  48. 'info_dict': {
  49. 'id': '1785452137001',
  50. 'ext': 'flv',
  51. 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  52. 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  53. 'uploader': 'Oracle',
  54. },
  55. },
  56. {
  57. # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
  58. 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
  59. 'info_dict': {
  60. 'id': '2750934548001',
  61. 'ext': 'mp4',
  62. 'title': 'This Bracelet Acts as a Personal Thermostat',
  63. 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
  64. 'uploader': 'Mashable',
  65. },
  66. },
  67. {
  68. # test that the default referer works
  69. # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
  70. 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
  71. 'info_dict': {
  72. 'id': '2878862109001',
  73. 'ext': 'mp4',
  74. 'title': 'Lost in Motion II',
  75. 'description': 'md5:363109c02998fee92ec02211bd8000df',
  76. 'uploader': 'National Ballet of Canada',
  77. },
  78. },
  79. {
  80. # test flv videos served by akamaihd.net
  81. # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
  82. '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',
  83. # The md5 checksum changes on each download
  84. 'info_dict': {
  85. 'id': '2996102916001',
  86. 'ext': 'flv',
  87. 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  88. 'uploader': 'Red Bull TV',
  89. 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  90. },
  91. },
  92. {
  93. # playlist test
  94. # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
  95. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
  96. 'info_dict': {
  97. 'title': 'Sealife',
  98. 'id': '3550319591001',
  99. },
  100. 'playlist_mincount': 7,
  101. },
  102. ]
  103. @classmethod
  104. def _build_brighcove_url(cls, object_str):
  105. """
  106. Build a Brightcove url from a xml string containing
  107. <object class="BrightcoveExperience">{params}</object>
  108. """
  109. # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
  110. object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
  111. lambda m: m.group(1) + '/>', object_str)
  112. # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
  113. object_str = object_str.replace('<--', '<!--')
  114. # remove namespace to simplify extraction
  115. object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
  116. object_str = fix_xml_ampersands(object_str)
  117. try:
  118. object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
  119. except compat_xml_parse_error:
  120. return
  121. fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
  122. if fv_el is not None:
  123. flashvars = dict(
  124. (k, v[0])
  125. for k, v in compat_parse_qs(fv_el.attrib['value']).items())
  126. else:
  127. flashvars = {}
  128. def find_param(name):
  129. if name in flashvars:
  130. return flashvars[name]
  131. node = find_xpath_attr(object_doc, './param', 'name', name)
  132. if node is not None:
  133. return node.attrib['value']
  134. return None
  135. params = {}
  136. playerID = find_param('playerID')
  137. if playerID is None:
  138. raise ExtractorError('Cannot find player ID')
  139. params['playerID'] = playerID
  140. playerKey = find_param('playerKey')
  141. # Not all pages define this value
  142. if playerKey is not None:
  143. params['playerKey'] = playerKey
  144. # The three fields hold the id of the video
  145. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
  146. if videoPlayer is not None:
  147. params['@videoPlayer'] = videoPlayer
  148. linkBase = find_param('linkBaseURL')
  149. if linkBase is not None:
  150. params['linkBaseURL'] = linkBase
  151. return cls._make_brightcove_url(params)
  152. @classmethod
  153. def _build_brighcove_url_from_js(cls, object_js):
  154. # The layout of JS is as follows:
  155. # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
  156. # // build Brightcove <object /> XML
  157. # }
  158. m = re.search(
  159. r'''(?x)customBC.\createVideo\(
  160. .*? # skipping width and height
  161. ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
  162. ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
  163. # in length, however it's appended to itself
  164. # in places, so truncate
  165. ["\'](?P<videoID>\d+)["\'] # @videoPlayer
  166. ''', object_js)
  167. if m:
  168. return cls._make_brightcove_url(m.groupdict())
  169. @classmethod
  170. def _make_brightcove_url(cls, params):
  171. data = compat_urllib_parse.urlencode(params)
  172. return cls._FEDERATED_URL_TEMPLATE % data
  173. @classmethod
  174. def _extract_brightcove_url(cls, webpage):
  175. """Try to extract the brightcove url from the webpage, returns None
  176. if it can't be found
  177. """
  178. urls = cls._extract_brightcove_urls(webpage)
  179. return urls[0] if urls else None
  180. @classmethod
  181. def _extract_brightcove_urls(cls, webpage):
  182. """Return a list of all Brightcove URLs from the webpage """
  183. url_m = re.search(
  184. r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
  185. webpage)
  186. if url_m:
  187. url = unescapeHTML(url_m.group(1))
  188. # Some sites don't add it, we can't download with this url, for example:
  189. # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
  190. if 'playerKey' in url or 'videoId' in url:
  191. return [url]
  192. matches = re.findall(
  193. r'''(?sx)<object
  194. (?:
  195. [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
  196. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  197. ).+?>\s*</object>''',
  198. webpage)
  199. if matches:
  200. return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
  201. return list(filter(None, [
  202. cls._build_brighcove_url_from_js(custom_bc)
  203. for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
  204. def _real_extract(self, url):
  205. url, smuggled_data = unsmuggle_url(url, {})
  206. # Change the 'videoId' and others field to '@videoPlayer'
  207. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  208. # Change bckey (used by bcove.me urls) to playerKey
  209. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  210. mobj = re.match(self._VALID_URL, url)
  211. query_str = mobj.group('query')
  212. query = compat_urlparse.parse_qs(query_str)
  213. videoPlayer = query.get('@videoPlayer')
  214. if videoPlayer:
  215. # We set the original url as the default 'Referer' header
  216. referer = smuggled_data.get('Referer', url)
  217. return self._get_video_info(
  218. videoPlayer[0], query_str, query, referer=referer)
  219. elif 'playerKey' in query:
  220. player_key = query['playerKey']
  221. return self._get_playlist_info(player_key[0])
  222. else:
  223. raise ExtractorError(
  224. 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
  225. expected=True)
  226. def _get_video_info(self, video_id, query_str, query, referer=None):
  227. request_url = self._FEDERATED_URL_TEMPLATE % query_str
  228. req = compat_urllib_request.Request(request_url)
  229. linkBase = query.get('linkBaseURL')
  230. if linkBase is not None:
  231. referer = linkBase[0]
  232. if referer is not None:
  233. req.add_header('Referer', referer)
  234. webpage = self._download_webpage(req, video_id)
  235. error_msg = self._html_search_regex(
  236. r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
  237. 'error message', default=None)
  238. if error_msg is not None:
  239. raise ExtractorError(
  240. 'brightcove said: %s' % error_msg, expected=True)
  241. self.report_extraction(video_id)
  242. info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
  243. info = json.loads(info)['data']
  244. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  245. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  246. return self._extract_video_info(video_info)
  247. def _get_playlist_info(self, player_key):
  248. info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
  249. playlist_info = self._download_webpage(
  250. info_url, player_key, 'Downloading playlist information')
  251. json_data = json.loads(playlist_info)
  252. if 'videoList' not in json_data:
  253. raise ExtractorError('Empty playlist')
  254. playlist_info = json_data['videoList']
  255. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  256. return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
  257. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  258. def _extract_video_info(self, video_info):
  259. info = {
  260. 'id': compat_str(video_info['id']),
  261. 'title': video_info['displayName'].strip(),
  262. 'description': video_info.get('shortDescription'),
  263. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  264. 'uploader': video_info.get('publisherName'),
  265. }
  266. renditions = video_info.get('renditions')
  267. if renditions:
  268. formats = []
  269. for rend in renditions:
  270. url = rend['defaultURL']
  271. if not url:
  272. continue
  273. ext = None
  274. if rend['remote']:
  275. url_comp = compat_urllib_parse_urlparse(url)
  276. if url_comp.path.endswith('.m3u8'):
  277. formats.extend(
  278. self._extract_m3u8_formats(url, info['id'], 'mp4'))
  279. continue
  280. elif 'akamaihd.net' in url_comp.netloc:
  281. # This type of renditions are served through
  282. # akamaihd.net, but they don't use f4m manifests
  283. url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
  284. ext = 'flv'
  285. if ext is None:
  286. ext = determine_ext(url)
  287. size = rend.get('size')
  288. formats.append({
  289. 'url': url,
  290. 'ext': ext,
  291. 'height': rend.get('frameHeight'),
  292. 'width': rend.get('frameWidth'),
  293. 'filesize': size if size != 0 else None,
  294. })
  295. self._sort_formats(formats)
  296. info['formats'] = formats
  297. elif video_info.get('FLVFullLengthURL') is not None:
  298. info.update({
  299. 'url': video_info['FLVFullLengthURL'],
  300. })
  301. if self._downloader.params.get('include_ads', False):
  302. adServerURL = video_info.get('_youtubedl_adServerURL')
  303. if adServerURL:
  304. ad_info = {
  305. '_type': 'url',
  306. 'url': adServerURL,
  307. }
  308. if 'url' in info:
  309. return {
  310. '_type': 'playlist',
  311. 'title': info['title'],
  312. 'entries': [ad_info, info],
  313. }
  314. else:
  315. return ad_info
  316. if 'url' not in info and not info.get('formats'):
  317. raise ExtractorError('Unable to extract video url for %s' % info['id'])
  318. return info
  319. class BrightcoveInPageEmbedIE(InfoExtractor):
  320. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/([a-z0-9-]+)_([a-z]+)/index.html?.*videoId=(?P<video_id>\d+)'
  321. _TEST = {
  322. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  323. 'md5': 'c8100925723840d4b0d243f7025703be',
  324. 'info_dict': {
  325. 'id': '4463358922001',
  326. 'ext': 'mp4',
  327. 'title': 'Meet the man behind Popcorn Time',
  328. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  329. 'timestamp': 1441391203,
  330. 'upload_date': '20150904',
  331. 'duration': 165768,
  332. 'uploader_id': '929656772001',
  333. }
  334. }
  335. @staticmethod
  336. def _extract_url(webpage):
  337. video_attributes = re.search(r'(?s)<video([^>]*)>.*?</(?:video|audio)>', webpage)
  338. if video_attributes:
  339. video_attributes = extract_attributes(video_attributes.group(), r'(?s)\s*data-(account|video-id|playlist-id|policy-key|player|embed)\s*=\s*["\']([^"\']+)["\']')
  340. account_id = video_attributes.get('account')
  341. player_id = video_attributes.get('player')
  342. embed = video_attributes.get('embed')
  343. video_id = video_attributes.get('video-id')
  344. if account_id and player_id and embed and video_id:
  345. return 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s' % (account_id, player_id, embed, video_id)
  346. return None
  347. def _real_extract(self, url):
  348. account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
  349. webpage = self._download_webpage('http://players.brightcove.net/%s/%s_%s/index.min.js' % (account_id, player_id, embed), video_id)
  350. catalog = self._parse_json(
  351. js_to_json(
  352. self._search_regex(
  353. r'catalog\(({[^}]+})\);',
  354. webpage,
  355. 'catalog'
  356. )
  357. ),
  358. video_id
  359. )
  360. policy_key = catalog['policyKey']
  361. req = compat_urllib_request.Request(
  362. 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id),
  363. headers={'Accept': 'application/json;pk=%s' % policy_key})
  364. json_data = self._download_json(req, video_id)
  365. title = json_data['name']
  366. description = json_data.get('description')
  367. thumbnail = json_data.get('thumbnail')
  368. timestamp = parse_iso8601(json_data.get('published_at'))
  369. duration = int_or_none(json_data.get('duration'))
  370. formats = []
  371. for source in json_data.get('sources'):
  372. source_type = source.get('type')
  373. if source_type == 'application/x-mpegURL':
  374. formats.extend(self._extract_m3u8_formats(source.get('src'), video_id))
  375. else:
  376. src = source.get('src') or source.get('streaming_src')
  377. if src:
  378. formats.append({
  379. 'url': src,
  380. 'tbr': source.get('avg_bitrate'),
  381. 'width': int_or_none(source.get('width')),
  382. 'height': int_or_none(source.get('height')),
  383. 'filesize': source.get('size'),
  384. 'container': source.get('container'),
  385. 'vcodec': source.get('codec'),
  386. 'ext': source.get('container').lower(),
  387. })
  388. self._sort_formats(formats)
  389. return {
  390. 'id': video_id,
  391. 'title': title,
  392. 'description': description,
  393. 'thumbnail': thumbnail,
  394. 'timestamp': timestamp,
  395. 'duration': duration,
  396. 'formats': formats,
  397. 'uploader_id': account_id,
  398. }