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.

731 lines
31 KiB

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