logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

brightcove.py (30520B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. import re
  5. import struct
  6. from .adobepass import AdobePassIE
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_etree_fromstring,
  10. compat_HTTPError,
  11. compat_parse_qs,
  12. compat_urllib_parse_urlparse,
  13. compat_urlparse,
  14. compat_xml_parse_error,
  15. )
  16. from ..utils import (
  17. clean_html,
  18. extract_attributes,
  19. ExtractorError,
  20. find_xpath_attr,
  21. fix_xml_ampersands,
  22. float_or_none,
  23. int_or_none,
  24. js_to_json,
  25. mimetype2ext,
  26. parse_iso8601,
  27. smuggle_url,
  28. str_or_none,
  29. try_get,
  30. unescapeHTML,
  31. unsmuggle_url,
  32. UnsupportedError,
  33. update_url_query,
  34. url_or_none,
  35. )
  36. class BrightcoveLegacyIE(InfoExtractor):
  37. IE_NAME = 'brightcove:legacy'
  38. _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
  39. _TESTS = [
  40. {
  41. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  42. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  43. 'md5': '5423e113865d26e40624dce2e4b45d95',
  44. 'note': 'Test Brightcove downloads and detection in GenericIE',
  45. 'info_dict': {
  46. 'id': '2371591881001',
  47. 'ext': 'mp4',
  48. 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  49. 'uploader': '8TV',
  50. 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
  51. 'timestamp': 1368213670,
  52. 'upload_date': '20130510',
  53. 'uploader_id': '1589608506001',
  54. },
  55. 'skip': 'The player has been deactivated by the content owner',
  56. },
  57. {
  58. # From http://medianetwork.oracle.com/video/player/1785452137001
  59. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  60. 'info_dict': {
  61. 'id': '1785452137001',
  62. 'ext': 'flv',
  63. 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  64. 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  65. 'uploader': 'Oracle',
  66. 'timestamp': 1344975024,
  67. 'upload_date': '20120814',
  68. 'uploader_id': '1460825906',
  69. },
  70. 'skip': 'video not playable',
  71. },
  72. {
  73. # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
  74. 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
  75. 'info_dict': {
  76. 'id': '2750934548001',
  77. 'ext': 'mp4',
  78. 'title': 'This Bracelet Acts as a Personal Thermostat',
  79. 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
  80. # 'uploader': 'Mashable',
  81. 'timestamp': 1382041798,
  82. 'upload_date': '20131017',
  83. 'uploader_id': '1130468786001',
  84. },
  85. },
  86. {
  87. # test that the default referer works
  88. # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
  89. 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
  90. 'info_dict': {
  91. 'id': '2878862109001',
  92. 'ext': 'mp4',
  93. 'title': 'Lost in Motion II',
  94. 'description': 'md5:363109c02998fee92ec02211bd8000df',
  95. 'uploader': 'National Ballet of Canada',
  96. },
  97. 'skip': 'Video gone',
  98. },
  99. {
  100. # test flv videos served by akamaihd.net
  101. # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
  102. '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',
  103. # The md5 checksum changes on each download
  104. 'info_dict': {
  105. 'id': '3750436379001',
  106. 'ext': 'flv',
  107. 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  108. 'uploader': 'RBTV Old (do not use)',
  109. 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
  110. 'timestamp': 1409122195,
  111. 'upload_date': '20140827',
  112. 'uploader_id': '710858724001',
  113. },
  114. 'skip': 'Video gone',
  115. },
  116. {
  117. # playlist with 'videoList'
  118. # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
  119. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
  120. 'info_dict': {
  121. 'title': 'Sealife',
  122. 'id': '3550319591001',
  123. },
  124. 'playlist_mincount': 7,
  125. 'skip': 'Unsupported URL',
  126. },
  127. {
  128. # playlist with 'playlistTab' (https://github.com/ytdl-org/youtube-dl/issues/9965)
  129. 'url': 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=AQ%7E%7E,AAABXlLMdok%7E,NJ4EoMlZ4rZdx9eU1rkMVd8EaYPBBUlg',
  130. 'info_dict': {
  131. 'id': '1522758701001',
  132. 'title': 'Lesson 08',
  133. },
  134. 'playlist_mincount': 10,
  135. 'skip': 'Unsupported URL',
  136. },
  137. {
  138. # playerID inferred from bcpid
  139. # from http://www.un.org/chinese/News/story.asp?NewsID=27724
  140. 'url': 'https://link.brightcove.com/services/player/bcpid1722935254001/?bctid=5360463607001&autoStart=false&secureConnections=true&width=650&height=350',
  141. 'only_matching': True, # Tested in GenericIE
  142. }
  143. ]
  144. @classmethod
  145. def _build_brightcove_url(cls, object_str):
  146. """
  147. Build a Brightcove url from a xml string containing
  148. <object class="BrightcoveExperience">{params}</object>
  149. """
  150. # Fix up some stupid HTML, see https://github.com/ytdl-org/youtube-dl/issues/1553
  151. object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
  152. lambda m: m.group(1) + '/>', object_str)
  153. # Fix up some stupid XML, see https://github.com/ytdl-org/youtube-dl/issues/1608
  154. object_str = object_str.replace('<--', '<!--')
  155. # remove namespace to simplify extraction
  156. object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
  157. object_str = fix_xml_ampersands(object_str)
  158. try:
  159. object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
  160. except compat_xml_parse_error:
  161. return
  162. fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
  163. if fv_el is not None:
  164. flashvars = dict(
  165. (k, v[0])
  166. for k, v in compat_parse_qs(fv_el.attrib['value']).items())
  167. else:
  168. flashvars = {}
  169. data_url = object_doc.attrib.get('data', '')
  170. data_url_params = compat_parse_qs(compat_urllib_parse_urlparse(data_url).query)
  171. def find_param(name):
  172. if name in flashvars:
  173. return flashvars[name]
  174. node = find_xpath_attr(object_doc, './param', 'name', name)
  175. if node is not None:
  176. return node.attrib['value']
  177. return data_url_params.get(name)
  178. params = {}
  179. playerID = find_param('playerID') or find_param('playerId')
  180. if playerID is None:
  181. raise ExtractorError('Cannot find player ID')
  182. params['playerID'] = playerID
  183. playerKey = find_param('playerKey')
  184. # Not all pages define this value
  185. if playerKey is not None:
  186. params['playerKey'] = playerKey
  187. # These fields hold the id of the video
  188. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
  189. if videoPlayer is not None:
  190. if isinstance(videoPlayer, list):
  191. videoPlayer = videoPlayer[0]
  192. videoPlayer = videoPlayer.strip()
  193. # UUID is also possible for videoPlayer (e.g.
  194. # http://www.popcornflix.com/hoodies-vs-hooligans/7f2d2b87-bbf2-4623-acfb-ea942b4f01dd
  195. # or http://www8.hp.com/cn/zh/home.html)
  196. if not (re.match(
  197. r'^(?:\d+|[\da-fA-F]{8}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{12})$',
  198. videoPlayer) or videoPlayer.startswith('ref:')):
  199. return None
  200. params['@videoPlayer'] = videoPlayer
  201. linkBase = find_param('linkBaseURL')
  202. if linkBase is not None:
  203. params['linkBaseURL'] = linkBase
  204. return cls._make_brightcove_url(params)
  205. @classmethod
  206. def _build_brightcove_url_from_js(cls, object_js):
  207. # The layout of JS is as follows:
  208. # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
  209. # // build Brightcove <object /> XML
  210. # }
  211. m = re.search(
  212. r'''(?x)customBC\.createVideo\(
  213. .*? # skipping width and height
  214. ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
  215. ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
  216. # in length, however it's appended to itself
  217. # in places, so truncate
  218. ["\'](?P<videoID>\d+)["\'] # @videoPlayer
  219. ''', object_js)
  220. if m:
  221. return cls._make_brightcove_url(m.groupdict())
  222. @classmethod
  223. def _make_brightcove_url(cls, params):
  224. return update_url_query(
  225. 'http://c.brightcove.com/services/viewer/htmlFederated', params)
  226. @classmethod
  227. def _extract_brightcove_url(cls, webpage):
  228. """Try to extract the brightcove url from the webpage, returns None
  229. if it can't be found
  230. """
  231. urls = cls._extract_brightcove_urls(webpage)
  232. return urls[0] if urls else None
  233. @classmethod
  234. def _extract_brightcove_urls(cls, webpage):
  235. """Return a list of all Brightcove URLs from the webpage """
  236. url_m = re.search(
  237. r'''(?x)
  238. <meta\s+
  239. (?:property|itemprop)=([\'"])(?:og:video|embedURL)\1[^>]+
  240. content=([\'"])(?P<url>https?://(?:secure|c)\.brightcove.com/(?:(?!\2).)+)\2
  241. ''', webpage)
  242. if url_m:
  243. url = unescapeHTML(url_m.group('url'))
  244. # Some sites don't add it, we can't download with this url, for example:
  245. # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
  246. if 'playerKey' in url or 'videoId' in url or 'idVideo' in url:
  247. return [url]
  248. matches = re.findall(
  249. r'''(?sx)<object
  250. (?:
  251. [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
  252. [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
  253. ).+?>\s*</object>''',
  254. webpage)
  255. if matches:
  256. return list(filter(None, [cls._build_brightcove_url(m) for m in matches]))
  257. matches = re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)
  258. if matches:
  259. return list(filter(None, [
  260. cls._build_brightcove_url_from_js(custom_bc)
  261. for custom_bc in matches]))
  262. return [src for _, src in re.findall(
  263. r'<iframe[^>]+src=([\'"])((?:https?:)?//link\.brightcove\.com/services/player/(?!\1).+)\1', webpage)]
  264. def _real_extract(self, url):
  265. url, smuggled_data = unsmuggle_url(url, {})
  266. # Change the 'videoId' and others field to '@videoPlayer'
  267. url = re.sub(r'(?<=[?&])(videoI(d|D)|idVideo|bctid)', '%40videoPlayer', url)
  268. # Change bckey (used by bcove.me urls) to playerKey
  269. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  270. mobj = re.match(self._VALID_URL, url)
  271. query_str = mobj.group('query')
  272. query = compat_urlparse.parse_qs(query_str)
  273. videoPlayer = query.get('@videoPlayer')
  274. if videoPlayer:
  275. # We set the original url as the default 'Referer' header
  276. referer = query.get('linkBaseURL', [None])[0] or smuggled_data.get('Referer', url)
  277. video_id = videoPlayer[0]
  278. if 'playerID' not in query:
  279. mobj = re.search(r'/bcpid(\d+)', url)
  280. if mobj is not None:
  281. query['playerID'] = [mobj.group(1)]
  282. publisher_id = query.get('publisherId')
  283. if publisher_id and publisher_id[0].isdigit():
  284. publisher_id = publisher_id[0]
  285. if not publisher_id:
  286. player_key = query.get('playerKey')
  287. if player_key and ',' in player_key[0]:
  288. player_key = player_key[0]
  289. else:
  290. player_id = query.get('playerID')
  291. if player_id and player_id[0].isdigit():
  292. headers = {}
  293. if referer:
  294. headers['Referer'] = referer
  295. player_page = self._download_webpage(
  296. 'http://link.brightcove.com/services/player/bcpid' + player_id[0],
  297. video_id, headers=headers, fatal=False)
  298. if player_page:
  299. player_key = self._search_regex(
  300. r'<param\s+name="playerKey"\s+value="([\w~,-]+)"',
  301. player_page, 'player key', fatal=False)
  302. if player_key:
  303. enc_pub_id = player_key.split(',')[1].replace('~', '=')
  304. publisher_id = struct.unpack('>Q', base64.urlsafe_b64decode(enc_pub_id))[0]
  305. if publisher_id:
  306. brightcove_new_url = 'http://players.brightcove.net/%s/default_default/index.html?videoId=%s' % (publisher_id, video_id)
  307. if referer:
  308. brightcove_new_url = smuggle_url(brightcove_new_url, {'referrer': referer})
  309. return self.url_result(brightcove_new_url, BrightcoveNewIE.ie_key(), video_id)
  310. # TODO: figure out if it's possible to extract playlistId from playerKey
  311. # elif 'playerKey' in query:
  312. # player_key = query['playerKey']
  313. # return self._get_playlist_info(player_key[0])
  314. raise UnsupportedError(url)
  315. class BrightcoveNewIE(AdobePassIE):
  316. IE_NAME = 'brightcove:new'
  317. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*(?P<content_type>video|playlist)Id=(?P<video_id>\d+|ref:[^&]+)'
  318. _TESTS = [{
  319. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  320. 'md5': 'c8100925723840d4b0d243f7025703be',
  321. 'info_dict': {
  322. 'id': '4463358922001',
  323. 'ext': 'mp4',
  324. 'title': 'Meet the man behind Popcorn Time',
  325. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  326. 'duration': 165.768,
  327. 'timestamp': 1441391203,
  328. 'upload_date': '20150904',
  329. 'uploader_id': '929656772001',
  330. 'formats': 'mincount:20',
  331. },
  332. }, {
  333. # with rtmp streams
  334. 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
  335. 'info_dict': {
  336. 'id': '4279049078001',
  337. 'ext': 'mp4',
  338. 'title': 'Titansgrave: Chapter 0',
  339. 'description': 'Titansgrave: Chapter 0',
  340. 'duration': 1242.058,
  341. 'timestamp': 1433556729,
  342. 'upload_date': '20150606',
  343. 'uploader_id': '4036320279001',
  344. 'formats': 'mincount:39',
  345. },
  346. 'params': {
  347. # m3u8 download
  348. 'skip_download': True,
  349. }
  350. }, {
  351. # playlist stream
  352. 'url': 'https://players.brightcove.net/1752604059001/S13cJdUBz_default/index.html?playlistId=5718313430001',
  353. 'info_dict': {
  354. 'id': '5718313430001',
  355. 'title': 'No Audio Playlist',
  356. },
  357. 'playlist_count': 7,
  358. 'params': {
  359. # m3u8 download
  360. 'skip_download': True,
  361. }
  362. }, {
  363. 'url': 'http://players.brightcove.net/5690807595001/HyZNerRl7_default/index.html?playlistId=5743160747001',
  364. 'only_matching': True,
  365. }, {
  366. # ref: prefixed video id
  367. 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
  368. 'only_matching': True,
  369. }, {
  370. # non numeric ref: prefixed video id
  371. 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
  372. 'only_matching': True,
  373. }, {
  374. # unavailable video without message but with error_code
  375. 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001',
  376. 'only_matching': True,
  377. }]
  378. @staticmethod
  379. def _extract_url(ie, webpage):
  380. urls = BrightcoveNewIE._extract_urls(ie, webpage)
  381. return urls[0] if urls else None
  382. @staticmethod
  383. def _extract_urls(ie, webpage):
  384. # Reference:
  385. # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
  386. # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#tag
  387. # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
  388. # 4. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/in-page-embed-player-implementation.html
  389. # 5. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
  390. entries = []
  391. # Look for iframe embeds [1]
  392. for _, url in re.findall(
  393. r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
  394. entries.append(url if url.startswith('http') else 'http:' + url)
  395. # Look for <video> tags [2] and embed_in_page embeds [3]
  396. # [2] looks like:
  397. for video, script_tag, account_id, player_id, embed in re.findall(
  398. r'''(?isx)
  399. (<video(?:-js)?\s+[^>]*\bdata-video-id\s*=\s*['"]?[^>]+>)
  400. (?:.*?
  401. (<script[^>]+
  402. src=["\'](?:https?:)?//players\.brightcove\.net/
  403. (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
  404. )
  405. )?
  406. ''', webpage):
  407. attrs = extract_attributes(video)
  408. # According to examples from [4] it's unclear whether video id
  409. # may be optional and what to do when it is
  410. video_id = attrs.get('data-video-id')
  411. if not video_id:
  412. continue
  413. account_id = account_id or attrs.get('data-account')
  414. if not account_id:
  415. continue
  416. player_id = player_id or attrs.get('data-player') or 'default'
  417. embed = embed or attrs.get('data-embed') or 'default'
  418. bc_url = 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s' % (
  419. account_id, player_id, embed, video_id)
  420. # Some brightcove videos may be embedded with video tag only and
  421. # without script tag or any mentioning of brightcove at all. Such
  422. # embeds are considered ambiguous since they are matched based only
  423. # on data-video-id and data-account attributes and in the wild may
  424. # not be brightcove embeds at all. Let's check reconstructed
  425. # brightcove URLs in case of such embeds and only process valid
  426. # ones. By this we ensure there is indeed a brightcove embed.
  427. if not script_tag and not ie._is_valid_url(
  428. bc_url, video_id, 'possible brightcove video'):
  429. continue
  430. entries.append(bc_url)
  431. return entries
  432. def _parse_brightcove_metadata(self, json_data, video_id, headers={}):
  433. title = json_data['name'].strip()
  434. num_drm_sources = 0
  435. formats = []
  436. sources = json_data.get('sources') or []
  437. for source in sources:
  438. container = source.get('container')
  439. ext = mimetype2ext(source.get('type'))
  440. src = source.get('src')
  441. # https://support.brightcove.com/playback-api-video-fields-reference#key_systems_object
  442. if container == 'WVM' or source.get('key_systems'):
  443. num_drm_sources += 1
  444. continue
  445. elif ext == 'ism':
  446. continue
  447. elif ext == 'm3u8' or container == 'M2TS':
  448. if not src:
  449. continue
  450. formats.extend(self._extract_m3u8_formats(
  451. src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
  452. elif ext == 'mpd':
  453. if not src:
  454. continue
  455. formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
  456. else:
  457. streaming_src = source.get('streaming_src')
  458. stream_name, app_name = source.get('stream_name'), source.get('app_name')
  459. if not src and not streaming_src and (not stream_name or not app_name):
  460. continue
  461. tbr = float_or_none(source.get('avg_bitrate'), 1000)
  462. height = int_or_none(source.get('height'))
  463. width = int_or_none(source.get('width'))
  464. f = {
  465. 'tbr': tbr,
  466. 'filesize': int_or_none(source.get('size')),
  467. 'container': container,
  468. 'ext': ext or container.lower(),
  469. }
  470. if width == 0 and height == 0:
  471. f.update({
  472. 'vcodec': 'none',
  473. })
  474. else:
  475. f.update({
  476. 'width': width,
  477. 'height': height,
  478. 'vcodec': source.get('codec'),
  479. })
  480. def build_format_id(kind):
  481. format_id = kind
  482. if tbr:
  483. format_id += '-%dk' % int(tbr)
  484. if height:
  485. format_id += '-%dp' % height
  486. return format_id
  487. if src or streaming_src:
  488. f.update({
  489. 'url': src or streaming_src,
  490. 'format_id': build_format_id('http' if src else 'http-streaming'),
  491. 'source_preference': 0 if src else -1,
  492. })
  493. else:
  494. f.update({
  495. 'url': app_name,
  496. 'play_path': stream_name,
  497. 'format_id': build_format_id('rtmp'),
  498. })
  499. formats.append(f)
  500. if not formats:
  501. errors = json_data.get('errors')
  502. if errors:
  503. error = errors[0]
  504. raise ExtractorError(
  505. error.get('message') or error.get('error_subcode') or error['error_code'], expected=True)
  506. if sources and num_drm_sources == len(sources):
  507. raise ExtractorError('This video is DRM protected.', expected=True)
  508. self._sort_formats(formats)
  509. for f in formats:
  510. f.setdefault('http_headers', {}).update(headers)
  511. subtitles = {}
  512. for text_track in json_data.get('text_tracks', []):
  513. if text_track.get('kind') != 'captions':
  514. continue
  515. text_track_url = url_or_none(text_track.get('src'))
  516. if not text_track_url:
  517. continue
  518. lang = (str_or_none(text_track.get('srclang'))
  519. or str_or_none(text_track.get('label')) or 'en').lower()
  520. subtitles.setdefault(lang, []).append({
  521. 'url': text_track_url,
  522. })
  523. is_live = False
  524. duration = float_or_none(json_data.get('duration'), 1000)
  525. if duration is not None and duration <= 0:
  526. is_live = True
  527. return {
  528. 'id': video_id,
  529. 'title': self._live_title(title) if is_live else title,
  530. 'description': clean_html(json_data.get('description')),
  531. 'thumbnail': json_data.get('thumbnail') or json_data.get('poster'),
  532. 'duration': duration,
  533. 'timestamp': parse_iso8601(json_data.get('published_at')),
  534. 'uploader_id': json_data.get('account_id'),
  535. 'formats': formats,
  536. 'subtitles': subtitles,
  537. 'tags': json_data.get('tags', []),
  538. 'is_live': is_live,
  539. }
  540. def _real_extract(self, url):
  541. url, smuggled_data = unsmuggle_url(url, {})
  542. self._initialize_geo_bypass({
  543. 'countries': smuggled_data.get('geo_countries'),
  544. 'ip_blocks': smuggled_data.get('geo_ip_blocks'),
  545. })
  546. account_id, player_id, embed, content_type, video_id = re.match(self._VALID_URL, url).groups()
  547. policy_key_id = '%s_%s' % (account_id, player_id)
  548. policy_key = self._downloader.cache.load('brightcove', policy_key_id)
  549. policy_key_extracted = False
  550. store_pk = lambda x: self._downloader.cache.store('brightcove', policy_key_id, x)
  551. def extract_policy_key():
  552. base_url = 'http://players.brightcove.net/%s/%s_%s/' % (account_id, player_id, embed)
  553. config = self._download_json(
  554. base_url + 'config.json', video_id, fatal=False) or {}
  555. policy_key = try_get(
  556. config, lambda x: x['video_cloud']['policy_key'])
  557. if not policy_key:
  558. webpage = self._download_webpage(
  559. base_url + 'index.min.js', video_id)
  560. catalog = self._search_regex(
  561. r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
  562. if catalog:
  563. catalog = self._parse_json(
  564. js_to_json(catalog), video_id, fatal=False)
  565. if catalog:
  566. policy_key = catalog.get('policyKey')
  567. if not policy_key:
  568. policy_key = self._search_regex(
  569. r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
  570. webpage, 'policy key', group='pk')
  571. store_pk(policy_key)
  572. return policy_key
  573. api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/%ss/%s' % (account_id, content_type, video_id)
  574. headers = {}
  575. referrer = smuggled_data.get('referrer')
  576. if referrer:
  577. headers.update({
  578. 'Referer': referrer,
  579. 'Origin': re.search(r'https?://[^/]+', referrer).group(0),
  580. })
  581. for _ in range(2):
  582. if not policy_key:
  583. policy_key = extract_policy_key()
  584. policy_key_extracted = True
  585. headers['Accept'] = 'application/json;pk=%s' % policy_key
  586. try:
  587. json_data = self._download_json(api_url, video_id, headers=headers)
  588. break
  589. except ExtractorError as e:
  590. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (401, 403):
  591. json_data = self._parse_json(e.cause.read().decode(), video_id)[0]
  592. message = json_data.get('message') or json_data['error_code']
  593. if json_data.get('error_subcode') == 'CLIENT_GEO':
  594. self.raise_geo_restricted(msg=message)
  595. elif json_data.get('error_code') == 'INVALID_POLICY_KEY' and not policy_key_extracted:
  596. policy_key = None
  597. store_pk(None)
  598. continue
  599. raise ExtractorError(message, expected=True)
  600. raise
  601. errors = json_data.get('errors')
  602. if errors and errors[0].get('error_subcode') == 'TVE_AUTH':
  603. custom_fields = json_data['custom_fields']
  604. tve_token = self._extract_mvpd_auth(
  605. smuggled_data['source_url'], video_id,
  606. custom_fields['bcadobepassrequestorid'],
  607. custom_fields['bcadobepassresourceid'])
  608. json_data = self._download_json(
  609. api_url, video_id, headers={
  610. 'Accept': 'application/json;pk=%s' % policy_key
  611. }, query={
  612. 'tveToken': tve_token,
  613. })
  614. if content_type == 'playlist':
  615. return self.playlist_result(
  616. [self._parse_brightcove_metadata(vid, vid.get('id'), headers)
  617. for vid in json_data.get('videos', []) if vid.get('id')],
  618. json_data.get('id'), json_data.get('name'),
  619. json_data.get('description'))
  620. return self._parse_brightcove_metadata(
  621. json_data, video_id, headers=headers)