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.

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