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.

648 lines
28 KiB

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