brightcove.py 27 KB

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