Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

776 lines
34KB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. import json
  5. import re
  6. import struct
  7. from .common import InfoExtractor
  8. from .adobepass import AdobePassIE
  9. from ..compat import (
  10. compat_etree_fromstring,
  11. compat_parse_qs,
  12. compat_str,
  13. compat_urllib_parse_urlparse,
  14. compat_urlparse,
  15. compat_xml_parse_error,
  16. compat_HTTPError,
  17. )
  18. from ..utils import (
  19. determine_ext,
  20. ExtractorError,
  21. extract_attributes,
  22. find_xpath_attr,
  23. fix_xml_ampersands,
  24. float_or_none,
  25. js_to_json,
  26. int_or_none,
  27. parse_iso8601,
  28. unescapeHTML,
  29. unsmuggle_url,
  30. update_url_query,
  31. clean_html,
  32. mimetype2ext,
  33. )
  34. class BrightcoveLegacyIE(InfoExtractor):
  35. IE_NAME = 'brightcove:legacy'
  36. _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
  37. _FEDERATED_URL = 'http://c.brightcove.com/services/viewer/htmlFederated'
  38. _TESTS = [
  39. {
  40. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  41. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  42. 'md5': '5423e113865d26e40624dce2e4b45d95',
  43. 'note': 'Test Brightcove downloads and detection in GenericIE',
  44. 'info_dict': {
  45. 'id': '2371591881001',
  46. 'ext': 'mp4',
  47. 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  48. 'uploader': '8TV',
  49. 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
  50. 'timestamp': 1368213670,
  51. 'upload_date': '20130510',
  52. 'uploader_id': '1589608506001',
  53. }
  54. },
  55. {
  56. # From http://medianetwork.oracle.com/video/player/1785452137001
  57. 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  58. 'info_dict': {
  59. 'id': '1785452137001',
  60. 'ext': 'flv',
  61. 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  62. 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  63. 'uploader': 'Oracle',
  64. 'timestamp': 1344975024,
  65. 'upload_date': '20120814',
  66. 'uploader_id': '1460825906',
  67. },
  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. },
  123. {
  124. # playlist with 'playlistTab' (https://github.com/ytdl-org/youtube-dl/issues/9965)
  125. 'url': 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=AQ%7E%7E,AAABXlLMdok%7E,NJ4EoMlZ4rZdx9eU1rkMVd8EaYPBBUlg',
  126. 'info_dict': {
  127. 'id': '1522758701001',
  128. 'title': 'Lesson 08',
  129. },
  130. 'playlist_mincount': 10,
  131. },
  132. {
  133. # playerID inferred from bcpid
  134. # from http://www.un.org/chinese/News/story.asp?NewsID=27724
  135. 'url': 'https://link.brightcove.com/services/player/bcpid1722935254001/?bctid=5360463607001&autoStart=false&secureConnections=true&width=650&height=350',
  136. 'only_matching': True, # Tested in GenericIE
  137. }
  138. ]
  139. FLV_VCODECS = {
  140. 1: 'SORENSON',
  141. 2: 'ON2',
  142. 3: 'H264',
  143. 4: 'VP8',
  144. }
  145. @classmethod
  146. def _build_brighcove_url(cls, object_str):
  147. """
  148. Build a Brightcove url from a xml string containing
  149. <object class="BrightcoveExperience">{params}</object>
  150. """
  151. # Fix up some stupid HTML, see https://github.com/ytdl-org/youtube-dl/issues/1553
  152. object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
  153. lambda m: m.group(1) + '/>', object_str)
  154. # Fix up some stupid XML, see https://github.com/ytdl-org/youtube-dl/issues/1608
  155. object_str = object_str.replace('<--', '<!--')
  156. # remove namespace to simplify extraction
  157. object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
  158. object_str = fix_xml_ampersands(object_str)
  159. try:
  160. object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
  161. except compat_xml_parse_error:
  162. return
  163. fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
  164. if fv_el is not None:
  165. flashvars = dict(
  166. (k, v[0])
  167. for k, v in compat_parse_qs(fv_el.attrib['value']).items())
  168. else:
  169. flashvars = {}
  170. data_url = object_doc.attrib.get('data', '')
  171. data_url_params = compat_parse_qs(compat_urllib_parse_urlparse(data_url).query)
  172. def find_param(name):
  173. if name in flashvars:
  174. return flashvars[name]
  175. node = find_xpath_attr(object_doc, './param', 'name', name)
  176. if node is not None:
  177. return node.attrib['value']
  178. return data_url_params.get(name)
  179. params = {}
  180. playerID = find_param('playerID') or find_param('playerId')
  181. if playerID is None:
  182. raise ExtractorError('Cannot find player ID')
  183. params['playerID'] = playerID
  184. playerKey = find_param('playerKey')
  185. # Not all pages define this value
  186. if playerKey is not None:
  187. params['playerKey'] = playerKey
  188. # These fields hold the id of the video
  189. videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
  190. if videoPlayer is not None:
  191. if isinstance(videoPlayer, list):
  192. videoPlayer = videoPlayer[0]
  193. videoPlayer = videoPlayer.strip()
  194. # UUID is also possible for videoPlayer (e.g.
  195. # http://www.popcornflix.com/hoodies-vs-hooligans/7f2d2b87-bbf2-4623-acfb-ea942b4f01dd
  196. # or http://www8.hp.com/cn/zh/home.html)
  197. if not (re.match(
  198. r'^(?:\d+|[\da-fA-F]{8}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{12})$',
  199. videoPlayer) or videoPlayer.startswith('ref:')):
  200. return None
  201. params['@videoPlayer'] = videoPlayer
  202. linkBase = find_param('linkBaseURL')
  203. if linkBase is not None:
  204. params['linkBaseURL'] = linkBase
  205. return cls._make_brightcove_url(params)
  206. @classmethod
  207. def _build_brighcove_url_from_js(cls, object_js):
  208. # The layout of JS is as follows:
  209. # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
  210. # // build Brightcove <object /> XML
  211. # }
  212. m = re.search(
  213. r'''(?x)customBC\.createVideo\(
  214. .*? # skipping width and height
  215. ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
  216. ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
  217. # in length, however it's appended to itself
  218. # in places, so truncate
  219. ["\'](?P<videoID>\d+)["\'] # @videoPlayer
  220. ''', object_js)
  221. if m:
  222. return cls._make_brightcove_url(m.groupdict())
  223. @classmethod
  224. def _make_brightcove_url(cls, params):
  225. return update_url_query(cls._FEDERATED_URL, 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_brighcove_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_brighcove_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 = smuggled_data.get('Referer', url)
  277. if 'playerID' not in query:
  278. mobj = re.search(r'/bcpid(\d+)', url)
  279. if mobj is not None:
  280. query['playerID'] = [mobj.group(1)]
  281. return self._get_video_info(
  282. videoPlayer[0], query, referer=referer)
  283. elif 'playerKey' in query:
  284. player_key = query['playerKey']
  285. return self._get_playlist_info(player_key[0])
  286. else:
  287. raise ExtractorError(
  288. 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
  289. expected=True)
  290. def _brightcove_new_url_result(self, publisher_id, video_id):
  291. brightcove_new_url = 'http://players.brightcove.net/%s/default_default/index.html?videoId=%s' % (publisher_id, video_id)
  292. return self.url_result(brightcove_new_url, BrightcoveNewIE.ie_key(), video_id)
  293. def _get_video_info(self, video_id, query, referer=None):
  294. headers = {}
  295. linkBase = query.get('linkBaseURL')
  296. if linkBase is not None:
  297. referer = linkBase[0]
  298. if referer is not None:
  299. headers['Referer'] = referer
  300. webpage = self._download_webpage(self._FEDERATED_URL, video_id, headers=headers, query=query)
  301. error_msg = self._html_search_regex(
  302. r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
  303. 'error message', default=None)
  304. if error_msg is not None:
  305. publisher_id = query.get('publisherId')
  306. if publisher_id and publisher_id[0].isdigit():
  307. publisher_id = publisher_id[0]
  308. if not publisher_id:
  309. player_key = query.get('playerKey')
  310. if player_key and ',' in player_key[0]:
  311. player_key = player_key[0]
  312. else:
  313. player_id = query.get('playerID')
  314. if player_id and player_id[0].isdigit():
  315. player_page = self._download_webpage(
  316. 'http://link.brightcove.com/services/player/bcpid' + player_id[0],
  317. video_id, headers=headers, fatal=False)
  318. if player_page:
  319. player_key = self._search_regex(
  320. r'<param\s+name="playerKey"\s+value="([\w~,-]+)"',
  321. player_page, 'player key', fatal=False)
  322. if player_key:
  323. enc_pub_id = player_key.split(',')[1].replace('~', '=')
  324. publisher_id = struct.unpack('>Q', base64.urlsafe_b64decode(enc_pub_id))[0]
  325. if publisher_id:
  326. return self._brightcove_new_url_result(publisher_id, video_id)
  327. raise ExtractorError(
  328. 'brightcove said: %s' % error_msg, expected=True)
  329. self.report_extraction(video_id)
  330. info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
  331. info = json.loads(info)['data']
  332. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  333. video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
  334. return self._extract_video_info(video_info)
  335. def _get_playlist_info(self, player_key):
  336. info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
  337. playlist_info = self._download_webpage(
  338. info_url, player_key, 'Downloading playlist information')
  339. json_data = json.loads(playlist_info)
  340. if 'videoList' in json_data:
  341. playlist_info = json_data['videoList']
  342. playlist_dto = playlist_info['mediaCollectionDTO']
  343. elif 'playlistTabs' in json_data:
  344. playlist_info = json_data['playlistTabs']
  345. playlist_dto = playlist_info['lineupListDTO']['playlistDTOs'][0]
  346. else:
  347. raise ExtractorError('Empty playlist')
  348. videos = [self._extract_video_info(video_info) for video_info in playlist_dto['videoDTOs']]
  349. return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
  350. playlist_title=playlist_dto['displayName'])
  351. def _extract_video_info(self, video_info):
  352. video_id = compat_str(video_info['id'])
  353. publisher_id = video_info.get('publisherId')
  354. info = {
  355. 'id': video_id,
  356. 'title': video_info['displayName'].strip(),
  357. 'description': video_info.get('shortDescription'),
  358. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  359. 'uploader': video_info.get('publisherName'),
  360. 'uploader_id': compat_str(publisher_id) if publisher_id else None,
  361. 'duration': float_or_none(video_info.get('length'), 1000),
  362. 'timestamp': int_or_none(video_info.get('creationDate'), 1000),
  363. }
  364. renditions = video_info.get('renditions', []) + video_info.get('IOSRenditions', [])
  365. if renditions:
  366. formats = []
  367. for rend in renditions:
  368. url = rend['defaultURL']
  369. if not url:
  370. continue
  371. ext = None
  372. if rend['remote']:
  373. url_comp = compat_urllib_parse_urlparse(url)
  374. if url_comp.path.endswith('.m3u8'):
  375. formats.extend(
  376. self._extract_m3u8_formats(
  377. url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
  378. continue
  379. elif 'akamaihd.net' in url_comp.netloc:
  380. # This type of renditions are served through
  381. # akamaihd.net, but they don't use f4m manifests
  382. url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
  383. ext = 'flv'
  384. if ext is None:
  385. ext = determine_ext(url)
  386. tbr = int_or_none(rend.get('encodingRate'), 1000)
  387. a_format = {
  388. 'format_id': 'http%s' % ('-%s' % tbr if tbr else ''),
  389. 'url': url,
  390. 'ext': ext,
  391. 'filesize': int_or_none(rend.get('size')) or None,
  392. 'tbr': tbr,
  393. }
  394. if rend.get('audioOnly'):
  395. a_format.update({
  396. 'vcodec': 'none',
  397. })
  398. else:
  399. a_format.update({
  400. 'height': int_or_none(rend.get('frameHeight')),
  401. 'width': int_or_none(rend.get('frameWidth')),
  402. 'vcodec': rend.get('videoCodec'),
  403. })
  404. # m3u8 manifests with remote == false are media playlists
  405. # Not calling _extract_m3u8_formats here to save network traffic
  406. if ext == 'm3u8':
  407. a_format.update({
  408. 'format_id': 'hls%s' % ('-%s' % tbr if tbr else ''),
  409. 'ext': 'mp4',
  410. 'protocol': 'm3u8_native',
  411. })
  412. formats.append(a_format)
  413. self._sort_formats(formats)
  414. info['formats'] = formats
  415. elif video_info.get('FLVFullLengthURL') is not None:
  416. info.update({
  417. 'url': video_info['FLVFullLengthURL'],
  418. 'vcodec': self.FLV_VCODECS.get(video_info.get('FLVFullCodec')),
  419. 'filesize': int_or_none(video_info.get('FLVFullSize')),
  420. })
  421. if self._downloader.params.get('include_ads', False):
  422. adServerURL = video_info.get('_youtubedl_adServerURL')
  423. if adServerURL:
  424. ad_info = {
  425. '_type': 'url',
  426. 'url': adServerURL,
  427. }
  428. if 'url' in info:
  429. return {
  430. '_type': 'playlist',
  431. 'title': info['title'],
  432. 'entries': [ad_info, info],
  433. }
  434. else:
  435. return ad_info
  436. if not info.get('url') and not info.get('formats'):
  437. uploader_id = info.get('uploader_id')
  438. if uploader_id:
  439. info.update(self._brightcove_new_url_result(uploader_id, video_id))
  440. else:
  441. raise ExtractorError('Unable to extract video url for %s' % video_id)
  442. return info
  443. class BrightcoveNewIE(AdobePassIE):
  444. IE_NAME = 'brightcove:new'
  445. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
  446. _TESTS = [{
  447. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  448. 'md5': 'c8100925723840d4b0d243f7025703be',
  449. 'info_dict': {
  450. 'id': '4463358922001',
  451. 'ext': 'mp4',
  452. 'title': 'Meet the man behind Popcorn Time',
  453. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  454. 'duration': 165.768,
  455. 'timestamp': 1441391203,
  456. 'upload_date': '20150904',
  457. 'uploader_id': '929656772001',
  458. 'formats': 'mincount:20',
  459. },
  460. }, {
  461. # with rtmp streams
  462. 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
  463. 'info_dict': {
  464. 'id': '4279049078001',
  465. 'ext': 'mp4',
  466. 'title': 'Titansgrave: Chapter 0',
  467. 'description': 'Titansgrave: Chapter 0',
  468. 'duration': 1242.058,
  469. 'timestamp': 1433556729,
  470. 'upload_date': '20150606',
  471. 'uploader_id': '4036320279001',
  472. 'formats': 'mincount:39',
  473. },
  474. 'params': {
  475. # m3u8 download
  476. 'skip_download': True,
  477. }
  478. }, {
  479. # ref: prefixed video id
  480. 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
  481. 'only_matching': True,
  482. }, {
  483. # non numeric ref: prefixed video id
  484. 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
  485. 'only_matching': True,
  486. }, {
  487. # unavailable video without message but with error_code
  488. 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001',
  489. 'only_matching': True,
  490. }]
  491. @staticmethod
  492. def _extract_url(ie, webpage):
  493. urls = BrightcoveNewIE._extract_urls(ie, webpage)
  494. return urls[0] if urls else None
  495. @staticmethod
  496. def _extract_urls(ie, webpage):
  497. # Reference:
  498. # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
  499. # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#tag
  500. # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
  501. # 4. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/in-page-embed-player-implementation.html
  502. # 5. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
  503. entries = []
  504. # Look for iframe embeds [1]
  505. for _, url in re.findall(
  506. r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
  507. entries.append(url if url.startswith('http') else 'http:' + url)
  508. # Look for <video> tags [2] and embed_in_page embeds [3]
  509. # [2] looks like:
  510. for video, script_tag, account_id, player_id, embed in re.findall(
  511. r'''(?isx)
  512. (<video\s+[^>]*\bdata-video-id\s*=\s*['"]?[^>]+>)
  513. (?:.*?
  514. (<script[^>]+
  515. src=["\'](?:https?:)?//players\.brightcove\.net/
  516. (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
  517. )
  518. )?
  519. ''', webpage):
  520. attrs = extract_attributes(video)
  521. # According to examples from [4] it's unclear whether video id
  522. # may be optional and what to do when it is
  523. video_id = attrs.get('data-video-id')
  524. if not video_id:
  525. continue
  526. account_id = account_id or attrs.get('data-account')
  527. if not account_id:
  528. continue
  529. player_id = player_id or attrs.get('data-player') or 'default'
  530. embed = embed or attrs.get('data-embed') or 'default'
  531. bc_url = 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s' % (
  532. account_id, player_id, embed, video_id)
  533. # Some brightcove videos may be embedded with video tag only and
  534. # without script tag or any mentioning of brightcove at all. Such
  535. # embeds are considered ambiguous since they are matched based only
  536. # on data-video-id and data-account attributes and in the wild may
  537. # not be brightcove embeds at all. Let's check reconstructed
  538. # brightcove URLs in case of such embeds and only process valid
  539. # ones. By this we ensure there is indeed a brightcove embed.
  540. if not script_tag and not ie._is_valid_url(
  541. bc_url, video_id, 'possible brightcove video'):
  542. continue
  543. entries.append(bc_url)
  544. return entries
  545. def _parse_brightcove_metadata(self, json_data, video_id, headers={}):
  546. title = json_data['name'].strip()
  547. formats = []
  548. for source in json_data.get('sources', []):
  549. container = source.get('container')
  550. ext = mimetype2ext(source.get('type'))
  551. src = source.get('src')
  552. # https://support.brightcove.com/playback-api-video-fields-reference#key_systems_object
  553. if ext == 'ism' or container == 'WVM' or source.get('key_systems'):
  554. continue
  555. elif ext == 'm3u8' or container == 'M2TS':
  556. if not src:
  557. continue
  558. formats.extend(self._extract_m3u8_formats(
  559. src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
  560. elif ext == 'mpd':
  561. if not src:
  562. continue
  563. formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
  564. else:
  565. streaming_src = source.get('streaming_src')
  566. stream_name, app_name = source.get('stream_name'), source.get('app_name')
  567. if not src and not streaming_src and (not stream_name or not app_name):
  568. continue
  569. tbr = float_or_none(source.get('avg_bitrate'), 1000)
  570. height = int_or_none(source.get('height'))
  571. width = int_or_none(source.get('width'))
  572. f = {
  573. 'tbr': tbr,
  574. 'filesize': int_or_none(source.get('size')),
  575. 'container': container,
  576. 'ext': ext or container.lower(),
  577. }
  578. if width == 0 and height == 0:
  579. f.update({
  580. 'vcodec': 'none',
  581. })
  582. else:
  583. f.update({
  584. 'width': width,
  585. 'height': height,
  586. 'vcodec': source.get('codec'),
  587. })
  588. def build_format_id(kind):
  589. format_id = kind
  590. if tbr:
  591. format_id += '-%dk' % int(tbr)
  592. if height:
  593. format_id += '-%dp' % height
  594. return format_id
  595. if src or streaming_src:
  596. f.update({
  597. 'url': src or streaming_src,
  598. 'format_id': build_format_id('http' if src else 'http-streaming'),
  599. 'source_preference': 0 if src else -1,
  600. })
  601. else:
  602. f.update({
  603. 'url': app_name,
  604. 'play_path': stream_name,
  605. 'format_id': build_format_id('rtmp'),
  606. })
  607. formats.append(f)
  608. if not formats:
  609. # for sonyliv.com DRM protected videos
  610. s3_source_url = json_data.get('custom_fields', {}).get('s3sourceurl')
  611. if s3_source_url:
  612. formats.append({
  613. 'url': s3_source_url,
  614. 'format_id': 'source',
  615. })
  616. errors = json_data.get('errors')
  617. if not formats and errors:
  618. error = errors[0]
  619. raise ExtractorError(
  620. error.get('message') or error.get('error_subcode') or error['error_code'], expected=True)
  621. self._sort_formats(formats)
  622. for f in formats:
  623. f.setdefault('http_headers', {}).update(headers)
  624. subtitles = {}
  625. for text_track in json_data.get('text_tracks', []):
  626. if text_track.get('src'):
  627. subtitles.setdefault(text_track.get('srclang'), []).append({
  628. 'url': text_track['src'],
  629. })
  630. is_live = False
  631. duration = float_or_none(json_data.get('duration'), 1000)
  632. if duration is not None and duration <= 0:
  633. is_live = True
  634. return {
  635. 'id': video_id,
  636. 'title': self._live_title(title) if is_live else title,
  637. 'description': clean_html(json_data.get('description')),
  638. 'thumbnail': json_data.get('thumbnail') or json_data.get('poster'),
  639. 'duration': duration,
  640. 'timestamp': parse_iso8601(json_data.get('published_at')),
  641. 'uploader_id': json_data.get('account_id'),
  642. 'formats': formats,
  643. 'subtitles': subtitles,
  644. 'tags': json_data.get('tags', []),
  645. 'is_live': is_live,
  646. }
  647. def _real_extract(self, url):
  648. url, smuggled_data = unsmuggle_url(url, {})
  649. self._initialize_geo_bypass({
  650. 'countries': smuggled_data.get('geo_countries'),
  651. 'ip_blocks': smuggled_data.get('geo_ip_blocks'),
  652. })
  653. account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
  654. webpage = self._download_webpage(
  655. 'http://players.brightcove.net/%s/%s_%s/index.min.js'
  656. % (account_id, player_id, embed), video_id)
  657. policy_key = None
  658. catalog = self._search_regex(
  659. r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
  660. if catalog:
  661. catalog = self._parse_json(
  662. js_to_json(catalog), video_id, fatal=False)
  663. if catalog:
  664. policy_key = catalog.get('policyKey')
  665. if not policy_key:
  666. policy_key = self._search_regex(
  667. r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
  668. webpage, 'policy key', group='pk')
  669. api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
  670. headers = {
  671. 'Accept': 'application/json;pk=%s' % policy_key,
  672. }
  673. referrer = smuggled_data.get('referrer')
  674. if referrer:
  675. headers.update({
  676. 'Referer': referrer,
  677. 'Origin': re.search(r'https?://[^/]+', referrer).group(0),
  678. })
  679. try:
  680. json_data = self._download_json(api_url, video_id, headers=headers)
  681. except ExtractorError as e:
  682. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  683. json_data = self._parse_json(e.cause.read().decode(), video_id)[0]
  684. message = json_data.get('message') or json_data['error_code']
  685. if json_data.get('error_subcode') == 'CLIENT_GEO':
  686. self.raise_geo_restricted(msg=message)
  687. raise ExtractorError(message, expected=True)
  688. raise
  689. errors = json_data.get('errors')
  690. if errors and errors[0].get('error_subcode') == 'TVE_AUTH':
  691. custom_fields = json_data['custom_fields']
  692. tve_token = self._extract_mvpd_auth(
  693. smuggled_data['source_url'], video_id,
  694. custom_fields['bcadobepassrequestorid'],
  695. custom_fields['bcadobepassresourceid'])
  696. json_data = self._download_json(
  697. api_url, video_id, headers={
  698. 'Accept': 'application/json;pk=%s' % policy_key
  699. }, query={
  700. 'tveToken': tve_token,
  701. })
  702. return self._parse_brightcove_metadata(
  703. json_data, video_id, headers=headers)