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.

688 lines
29 KiB

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