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.

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