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.

635 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. 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')
  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. params['@videoPlayer'] = videoPlayer
  181. linkBase = find_param('linkBaseURL')
  182. if linkBase is not None:
  183. params['linkBaseURL'] = linkBase
  184. return cls._make_brightcove_url(params)
  185. @classmethod
  186. def _build_brighcove_url_from_js(cls, object_js):
  187. # The layout of JS is as follows:
  188. # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
  189. # // build Brightcove <object /> XML
  190. # }
  191. m = re.search(
  192. r'''(?x)customBC.\createVideo\(
  193. .*? # skipping width and height
  194. ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
  195. ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
  196. # in length, however it's appended to itself
  197. # in places, so truncate
  198. ["\'](?P<videoID>\d+)["\'] # @videoPlayer
  199. ''', object_js)
  200. if m:
  201. return cls._make_brightcove_url(m.groupdict())
  202. @classmethod
  203. def _make_brightcove_url(cls, params):
  204. return update_url_query(cls._FEDERATED_URL, params)
  205. @classmethod
  206. def _extract_brightcove_url(cls, webpage):
  207. """Try to extract the brightcove url from the webpage, returns None
  208. if it can't be found
  209. """
  210. urls = cls._extract_brightcove_urls(webpage)
  211. return urls[0] if urls else None
  212. @classmethod
  213. def _extract_brightcove_urls(cls, webpage):
  214. """Return a list of all Brightcove URLs from the webpage """
  215. url_m = re.search(
  216. r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
  217. webpage)
  218. if url_m:
  219. url = unescapeHTML(url_m.group(1))
  220. # Some sites don't add it, we can't download with this url, for example:
  221. # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
  222. if 'playerKey' in url or 'videoId' in url:
  223. return [url]
  224. matches = re.findall(
  225. r'''(?sx)<object
  226. (?:
  227. [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
  228. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  229. ).+?>\s*</object>''',
  230. webpage)
  231. if matches:
  232. return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
  233. return list(filter(None, [
  234. cls._build_brighcove_url_from_js(custom_bc)
  235. for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
  236. def _real_extract(self, url):
  237. url, smuggled_data = unsmuggle_url(url, {})
  238. # Change the 'videoId' and others field to '@videoPlayer'
  239. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  240. # Change bckey (used by bcove.me urls) to playerKey
  241. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  242. mobj = re.match(self._VALID_URL, url)
  243. query_str = mobj.group('query')
  244. query = compat_urlparse.parse_qs(query_str)
  245. videoPlayer = query.get('@videoPlayer')
  246. if videoPlayer:
  247. # We set the original url as the default 'Referer' header
  248. referer = smuggled_data.get('Referer', url)
  249. return self._get_video_info(
  250. videoPlayer[0], query, referer=referer)
  251. elif 'playerKey' in query:
  252. player_key = query['playerKey']
  253. return self._get_playlist_info(player_key[0])
  254. else:
  255. raise ExtractorError(
  256. 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
  257. expected=True)
  258. def _get_video_info(self, video_id, query, referer=None):
  259. headers = {}
  260. linkBase = query.get('linkBaseURL')
  261. if linkBase is not None:
  262. referer = linkBase[0]
  263. if referer is not None:
  264. headers['Referer'] = referer
  265. webpage = self._download_webpage(self._FEDERATED_URL, video_id, headers=headers, query=query)
  266. error_msg = self._html_search_regex(
  267. r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
  268. 'error message', default=None)
  269. if error_msg is not None:
  270. raise ExtractorError(
  271. 'brightcove said: %s' % error_msg, expected=True)
  272. self.report_extraction(video_id)
  273. info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
  274. info = json.loads(info)['data']
  275. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  276. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  277. return self._extract_video_info(video_info)
  278. def _get_playlist_info(self, player_key):
  279. info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
  280. playlist_info = self._download_webpage(
  281. info_url, player_key, 'Downloading playlist information')
  282. json_data = json.loads(playlist_info)
  283. if 'videoList' in json_data:
  284. playlist_info = json_data['videoList']
  285. playlist_dto = playlist_info['mediaCollectionDTO']
  286. elif 'playlistTabs' in json_data:
  287. playlist_info = json_data['playlistTabs']
  288. playlist_dto = playlist_info['lineupListDTO']['playlistDTOs'][0]
  289. else:
  290. raise ExtractorError('Empty playlist')
  291. videos = [self._extract_video_info(video_info) for video_info in playlist_dto['videoDTOs']]
  292. return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
  293. playlist_title=playlist_dto['displayName'])
  294. def _extract_video_info(self, video_info):
  295. video_id = compat_str(video_info['id'])
  296. publisher_id = video_info.get('publisherId')
  297. info = {
  298. 'id': video_id,
  299. 'title': video_info['displayName'].strip(),
  300. 'description': video_info.get('shortDescription'),
  301. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  302. 'uploader': video_info.get('publisherName'),
  303. 'uploader_id': compat_str(publisher_id) if publisher_id else None,
  304. 'duration': float_or_none(video_info.get('length'), 1000),
  305. 'timestamp': int_or_none(video_info.get('creationDate'), 1000),
  306. }
  307. renditions = video_info.get('renditions', []) + video_info.get('IOSRenditions', [])
  308. if renditions:
  309. formats = []
  310. for rend in renditions:
  311. url = rend['defaultURL']
  312. if not url:
  313. continue
  314. ext = None
  315. if rend['remote']:
  316. url_comp = compat_urllib_parse_urlparse(url)
  317. if url_comp.path.endswith('.m3u8'):
  318. formats.extend(
  319. self._extract_m3u8_formats(
  320. url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
  321. continue
  322. elif 'akamaihd.net' in url_comp.netloc:
  323. # This type of renditions are served through
  324. # akamaihd.net, but they don't use f4m manifests
  325. url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
  326. ext = 'flv'
  327. if ext is None:
  328. ext = determine_ext(url)
  329. tbr = int_or_none(rend.get('encodingRate'), 1000)
  330. a_format = {
  331. 'format_id': 'http%s' % ('-%s' % tbr if tbr else ''),
  332. 'url': url,
  333. 'ext': ext,
  334. 'filesize': int_or_none(rend.get('size')) or None,
  335. 'tbr': tbr,
  336. }
  337. if rend.get('audioOnly'):
  338. a_format.update({
  339. 'vcodec': 'none',
  340. })
  341. else:
  342. a_format.update({
  343. 'height': int_or_none(rend.get('frameHeight')),
  344. 'width': int_or_none(rend.get('frameWidth')),
  345. 'vcodec': rend.get('videoCodec'),
  346. })
  347. # m3u8 manifests with remote == false are media playlists
  348. # Not calling _extract_m3u8_formats here to save network traffic
  349. if ext == 'm3u8':
  350. a_format.update({
  351. 'format_id': 'hls%s' % ('-%s' % tbr if tbr else ''),
  352. 'ext': 'mp4',
  353. 'protocol': 'm3u8_native',
  354. })
  355. formats.append(a_format)
  356. self._sort_formats(formats)
  357. info['formats'] = formats
  358. elif video_info.get('FLVFullLengthURL') is not None:
  359. info.update({
  360. 'url': video_info['FLVFullLengthURL'],
  361. 'vcodec': self.FLV_VCODECS.get(video_info.get('FLVFullCodec')),
  362. 'filesize': int_or_none(video_info.get('FLVFullSize')),
  363. })
  364. if self._downloader.params.get('include_ads', False):
  365. adServerURL = video_info.get('_youtubedl_adServerURL')
  366. if adServerURL:
  367. ad_info = {
  368. '_type': 'url',
  369. 'url': adServerURL,
  370. }
  371. if 'url' in info:
  372. return {
  373. '_type': 'playlist',
  374. 'title': info['title'],
  375. 'entries': [ad_info, info],
  376. }
  377. else:
  378. return ad_info
  379. if 'url' not in info and not info.get('formats'):
  380. raise ExtractorError('Unable to extract video url for %s' % video_id)
  381. return info
  382. class BrightcoveNewIE(InfoExtractor):
  383. IE_NAME = 'brightcove:new'
  384. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
  385. _TESTS = [{
  386. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  387. 'md5': 'c8100925723840d4b0d243f7025703be',
  388. 'info_dict': {
  389. 'id': '4463358922001',
  390. 'ext': 'mp4',
  391. 'title': 'Meet the man behind Popcorn Time',
  392. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  393. 'duration': 165.768,
  394. 'timestamp': 1441391203,
  395. 'upload_date': '20150904',
  396. 'uploader_id': '929656772001',
  397. 'formats': 'mincount:22',
  398. },
  399. }, {
  400. # with rtmp streams
  401. 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
  402. 'info_dict': {
  403. 'id': '4279049078001',
  404. 'ext': 'mp4',
  405. 'title': 'Titansgrave: Chapter 0',
  406. 'description': 'Titansgrave: Chapter 0',
  407. 'duration': 1242.058,
  408. 'timestamp': 1433556729,
  409. 'upload_date': '20150606',
  410. 'uploader_id': '4036320279001',
  411. 'formats': 'mincount:41',
  412. },
  413. 'params': {
  414. # m3u8 download
  415. 'skip_download': True,
  416. }
  417. }, {
  418. # ref: prefixed video id
  419. 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
  420. 'only_matching': True,
  421. }, {
  422. # non numeric ref: prefixed video id
  423. 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
  424. 'only_matching': True,
  425. }, {
  426. # unavailable video without message but with error_code
  427. 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001',
  428. 'only_matching': True,
  429. }]
  430. @staticmethod
  431. def _extract_url(webpage):
  432. urls = BrightcoveNewIE._extract_urls(webpage)
  433. return urls[0] if urls else None
  434. @staticmethod
  435. def _extract_urls(webpage):
  436. # Reference:
  437. # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
  438. # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
  439. # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
  440. # 4. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
  441. entries = []
  442. # Look for iframe embeds [1]
  443. for _, url in re.findall(
  444. r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
  445. entries.append(url if url.startswith('http') else 'http:' + url)
  446. # Look for embed_in_page embeds [2]
  447. for video_id, account_id, player_id, embed in re.findall(
  448. # According to examples from [3] it's unclear whether video id
  449. # may be optional and what to do when it is
  450. # According to [4] data-video-id may be prefixed with ref:
  451. r'''(?sx)
  452. <video[^>]+
  453. data-video-id=["\'](\d+|ref:[^"\']+)["\'][^>]*>.*?
  454. </video>.*?
  455. <script[^>]+
  456. src=["\'](?:https?:)?//players\.brightcove\.net/
  457. (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
  458. ''', webpage):
  459. entries.append(
  460. 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
  461. % (account_id, player_id, embed, video_id))
  462. return entries
  463. def _real_extract(self, url):
  464. account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
  465. webpage = self._download_webpage(
  466. 'http://players.brightcove.net/%s/%s_%s/index.min.js'
  467. % (account_id, player_id, embed), video_id)
  468. policy_key = None
  469. catalog = self._search_regex(
  470. r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
  471. if catalog:
  472. catalog = self._parse_json(
  473. js_to_json(catalog), video_id, fatal=False)
  474. if catalog:
  475. policy_key = catalog.get('policyKey')
  476. if not policy_key:
  477. policy_key = self._search_regex(
  478. r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
  479. webpage, 'policy key', group='pk')
  480. api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
  481. try:
  482. json_data = self._download_json(api_url, video_id, headers={
  483. 'Accept': 'application/json;pk=%s' % policy_key
  484. })
  485. except ExtractorError as e:
  486. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  487. json_data = self._parse_json(e.cause.read().decode(), video_id)[0]
  488. raise ExtractorError(
  489. json_data.get('message') or json_data['error_code'], expected=True)
  490. raise
  491. title = json_data['name'].strip()
  492. formats = []
  493. for source in json_data.get('sources', []):
  494. container = source.get('container')
  495. ext = mimetype2ext(source.get('type'))
  496. src = source.get('src')
  497. if ext == 'ism':
  498. continue
  499. elif ext == 'm3u8' or container == 'M2TS':
  500. if not src:
  501. continue
  502. formats.extend(self._extract_m3u8_formats(
  503. src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
  504. elif ext == 'mpd':
  505. if not src:
  506. continue
  507. formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
  508. else:
  509. streaming_src = source.get('streaming_src')
  510. stream_name, app_name = source.get('stream_name'), source.get('app_name')
  511. if not src and not streaming_src and (not stream_name or not app_name):
  512. continue
  513. tbr = float_or_none(source.get('avg_bitrate'), 1000)
  514. height = int_or_none(source.get('height'))
  515. width = int_or_none(source.get('width'))
  516. f = {
  517. 'tbr': tbr,
  518. 'filesize': int_or_none(source.get('size')),
  519. 'container': container,
  520. 'ext': ext or container.lower(),
  521. }
  522. if width == 0 and height == 0:
  523. f.update({
  524. 'vcodec': 'none',
  525. })
  526. else:
  527. f.update({
  528. 'width': width,
  529. 'height': height,
  530. 'vcodec': source.get('codec'),
  531. })
  532. def build_format_id(kind):
  533. format_id = kind
  534. if tbr:
  535. format_id += '-%dk' % int(tbr)
  536. if height:
  537. format_id += '-%dp' % height
  538. return format_id
  539. if src or streaming_src:
  540. f.update({
  541. 'url': src or streaming_src,
  542. 'format_id': build_format_id('http' if src else 'http-streaming'),
  543. 'source_preference': 0 if src else -1,
  544. })
  545. else:
  546. f.update({
  547. 'url': app_name,
  548. 'play_path': stream_name,
  549. 'format_id': build_format_id('rtmp'),
  550. })
  551. formats.append(f)
  552. errors = json_data.get('errors')
  553. if not formats and errors:
  554. error = errors[0]
  555. raise ExtractorError(
  556. error.get('message') or error.get('error_subcode') or error['error_code'], expected=True)
  557. self._sort_formats(formats)
  558. subtitles = {}
  559. for text_track in json_data.get('text_tracks', []):
  560. if text_track.get('src'):
  561. subtitles.setdefault(text_track.get('srclang'), []).append({
  562. 'url': text_track['src'],
  563. })
  564. return {
  565. 'id': video_id,
  566. 'title': title,
  567. 'description': clean_html(json_data.get('description')),
  568. 'thumbnail': json_data.get('thumbnail') or json_data.get('poster'),
  569. 'duration': float_or_none(json_data.get('duration'), 1000),
  570. 'timestamp': parse_iso8601(json_data.get('published_at')),
  571. 'uploader_id': account_id,
  572. 'formats': formats,
  573. 'subtitles': subtitles,
  574. 'tags': json_data.get('tags', []),
  575. }