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.

651 lines
28 KiB

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