2 from __future__ import unicode_literals
7 from .common import InfoExtractor
9 compat_etree_fromstring,
13 compat_urllib_parse_urlparse,
14 compat_urllib_request,
16 compat_xml_parse_error,
33 class BrightcoveLegacyIE(InfoExtractor):
34 IE_NAME = 'brightcove:legacy'
35 _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
36 _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
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',
45 'id': '2371591881001',
47 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
49 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
53 # From http://medianetwork.oracle.com/video/player/1785452137001
54 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
56 'id': '1785452137001',
58 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
59 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
64 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
65 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
67 'id': '2750934548001',
69 'title': 'This Bracelet Acts as a Personal Thermostat',
70 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
71 'uploader': 'Mashable',
75 # test that the default referer works
76 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
77 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
79 'id': '2878862109001',
81 'title': 'Lost in Motion II',
82 'description': 'md5:363109c02998fee92ec02211bd8000df',
83 'uploader': 'National Ballet of Canada',
87 # test flv videos served by akamaihd.net
88 # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
89 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?%40videoPlayer=ref%3ABC2996102916001&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',
90 # The md5 checksum changes on each download
92 'id': '2996102916001',
94 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
95 'uploader': 'Red Bull TV',
96 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
101 # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
102 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
105 'id': '3550319591001',
107 'playlist_mincount': 7,
112 def _build_brighcove_url(cls, object_str):
114 Build a Brightcove url from a xml string containing
115 <object class="BrightcoveExperience">{params}</object>
118 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
119 object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
120 lambda m: m.group(1) + '/>', object_str)
121 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
122 object_str = object_str.replace('<--', '<!--')
123 # remove namespace to simplify extraction
124 object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
125 object_str = fix_xml_ampersands(object_str)
128 object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
129 except compat_xml_parse_error:
132 fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
133 if fv_el is not None:
136 for k, v in compat_parse_qs(fv_el.attrib['value']).items())
140 def find_param(name):
141 if name in flashvars:
142 return flashvars[name]
143 node = find_xpath_attr(object_doc, './param', 'name', name)
145 return node.attrib['value']
150 playerID = find_param('playerID')
152 raise ExtractorError('Cannot find player ID')
153 params['playerID'] = playerID
155 playerKey = find_param('playerKey')
156 # Not all pages define this value
157 if playerKey is not None:
158 params['playerKey'] = playerKey
159 # The three fields hold the id of the video
160 videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
161 if videoPlayer is not None:
162 params['@videoPlayer'] = videoPlayer
163 linkBase = find_param('linkBaseURL')
164 if linkBase is not None:
165 params['linkBaseURL'] = linkBase
166 return cls._make_brightcove_url(params)
169 def _build_brighcove_url_from_js(cls, object_js):
170 # The layout of JS is as follows:
171 # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
172 # // build Brightcove <object /> XML
175 r'''(?x)customBC.\createVideo\(
176 .*? # skipping width and height
177 ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
178 ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
179 # in length, however it's appended to itself
180 # in places, so truncate
181 ["\'](?P<videoID>\d+)["\'] # @videoPlayer
184 return cls._make_brightcove_url(m.groupdict())
187 def _make_brightcove_url(cls, params):
188 data = compat_urllib_parse.urlencode(params)
189 return cls._FEDERATED_URL_TEMPLATE % data
192 def _extract_brightcove_url(cls, webpage):
193 """Try to extract the brightcove url from the webpage, returns None
196 urls = cls._extract_brightcove_urls(webpage)
197 return urls[0] if urls else None
200 def _extract_brightcove_urls(cls, webpage):
201 """Return a list of all Brightcove URLs from the webpage """
204 r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
207 url = unescapeHTML(url_m.group(1))
208 # Some sites don't add it, we can't download with this url, for example:
209 # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
210 if 'playerKey' in url or 'videoId' in url:
213 matches = re.findall(
216 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
217 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
218 ).+?>\s*</object>''',
221 return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
223 return list(filter(None, [
224 cls._build_brighcove_url_from_js(custom_bc)
225 for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
227 def _real_extract(self, url):
228 url, smuggled_data = unsmuggle_url(url, {})
230 # Change the 'videoId' and others field to '@videoPlayer'
231 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
232 # Change bckey (used by bcove.me urls) to playerKey
233 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
234 mobj = re.match(self._VALID_URL, url)
235 query_str = mobj.group('query')
236 query = compat_urlparse.parse_qs(query_str)
238 videoPlayer = query.get('@videoPlayer')
240 # We set the original url as the default 'Referer' header
241 referer = smuggled_data.get('Referer', url)
242 return self._get_video_info(
243 videoPlayer[0], query_str, query, referer=referer)
244 elif 'playerKey' in query:
245 player_key = query['playerKey']
246 return self._get_playlist_info(player_key[0])
248 raise ExtractorError(
249 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
252 def _get_video_info(self, video_id, query_str, query, referer=None):
253 request_url = self._FEDERATED_URL_TEMPLATE % query_str
254 req = compat_urllib_request.Request(request_url)
255 linkBase = query.get('linkBaseURL')
256 if linkBase is not None:
257 referer = linkBase[0]
258 if referer is not None:
259 req.add_header('Referer', referer)
260 webpage = self._download_webpage(req, video_id)
262 error_msg = self._html_search_regex(
263 r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
264 'error message', default=None)
265 if error_msg is not None:
266 raise ExtractorError(
267 'brightcove said: %s' % error_msg, expected=True)
269 self.report_extraction(video_id)
270 info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
271 info = json.loads(info)['data']
272 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
273 video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
275 return self._extract_video_info(video_info)
277 def _get_playlist_info(self, player_key):
278 info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
279 playlist_info = self._download_webpage(
280 info_url, player_key, 'Downloading playlist information')
282 json_data = json.loads(playlist_info)
283 if 'videoList' not in json_data:
284 raise ExtractorError('Empty playlist')
285 playlist_info = json_data['videoList']
286 videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
288 return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
289 playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
291 def _extract_video_info(self, video_info):
293 'id': compat_str(video_info['id']),
294 'title': video_info['displayName'].strip(),
295 'description': video_info.get('shortDescription'),
296 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
297 'uploader': video_info.get('publisherName'),
300 renditions = video_info.get('renditions')
303 for rend in renditions:
304 url = rend['defaultURL']
309 url_comp = compat_urllib_parse_urlparse(url)
310 if url_comp.path.endswith('.m3u8'):
312 self._extract_m3u8_formats(url, info['id'], 'mp4'))
314 elif 'akamaihd.net' in url_comp.netloc:
315 # This type of renditions are served through
316 # akamaihd.net, but they don't use f4m manifests
317 url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
320 ext = determine_ext(url)
321 size = rend.get('size')
325 'height': rend.get('frameHeight'),
326 'width': rend.get('frameWidth'),
327 'filesize': size if size != 0 else None,
329 self._sort_formats(formats)
330 info['formats'] = formats
331 elif video_info.get('FLVFullLengthURL') is not None:
333 'url': video_info['FLVFullLengthURL'],
336 if self._downloader.params.get('include_ads', False):
337 adServerURL = video_info.get('_youtubedl_adServerURL')
346 'title': info['title'],
347 'entries': [ad_info, info],
352 if 'url' not in info and not info.get('formats'):
353 raise ExtractorError('Unable to extract video url for %s' % info['id'])
357 class BrightcoveNewIE(InfoExtractor):
358 IE_NAME = 'brightcove:new'
359 _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+)'
361 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
362 'md5': 'c8100925723840d4b0d243f7025703be',
364 'id': '4463358922001',
366 'title': 'Meet the man behind Popcorn Time',
367 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
368 'timestamp': 1441391203,
369 'upload_date': '20150904',
371 'uploader_id': '929656772001',
375 def _extract_urls(self, webpage):
377 # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
378 # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript)
379 # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
383 # Look for iframe embeds [1]
384 for _, url in re.findall(
385 r'<iframe[^>]+src=(["\'])((?:https?:)//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
386 entries.append(self.url_result(self._proto_relative_url(url)))
387 # Look for embed_in_page embeds [2]
388 # According to examples from [3] it's unclear whether video id may be optional
389 # and what to do when it is
390 for video_id, account_id, player_id, embed in re.findall(
393 data-video-id=["\'](\d+)["\'][^>]*>.*?
396 src=["\'](?:https?:)?//players\.brightcove\.net/
397 (\d+)/([\da-f-]+)_([^/]+)/index\.min\.js
399 entries.append(self.url_result(
400 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
401 % (account_id, player_id, embed, video_id)))
404 def _real_extract(self, url):
405 account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
407 webpage = self._download_webpage(
408 'http://players.brightcove.net/%s/%s_%s/index.min.js'
409 % (account_id, player_id, embed), video_id)
413 catalog = self._search_regex(
414 r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
416 catalog = self._parse_json(
417 js_to_json(catalog), video_id, fatal=False)
419 policy_key = catalog.get('policyKey')
422 policy_key = self._search_regex(
423 r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
424 webpage, 'policy key', group='pk')
426 req = compat_urllib_request.Request(
427 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s'
428 % (account_id, video_id),
429 headers={'Accept': 'application/json;pk=%s' % policy_key})
430 json_data = self._download_json(req, video_id)
432 title = json_data['name']
435 for source in json_data.get('sources', []):
436 source_type = source.get('type')
437 src = source.get('src')
438 if source_type == 'application/x-mpegURL':
441 m3u8_formats = self._extract_m3u8_formats(
442 src, video_id, 'mp4', entry_protocol='m3u8_native',
443 m3u8_id='hls', fatal=False)
445 formats.extend(m3u8_formats)
447 streaming_src = source.get('streaming_src')
448 stream_name, app_name = source.get('stream_name'), source.get('app_name')
449 if not src and not streaming_src and (not stream_name or not app_name):
451 tbr = float_or_none(source.get('avg_bitrate'), 1000)
452 height = int_or_none(source.get('height'))
455 'width': int_or_none(source.get('width')),
457 'filesize': int_or_none(source.get('size')),
458 'container': source.get('container'),
459 'vcodec': source.get('codec'),
460 'ext': source.get('container').lower(),
463 def build_format_id(kind):
466 format_id += '-%dk' % int(tbr)
468 format_id += '-%dp' % height
471 if src or streaming_src:
473 'url': src or streaming_src,
474 'format_id': build_format_id('http' if src else 'http-streaming'),
475 'preference': 2 if src else 1,
480 'play_path': stream_name,
481 'format_id': build_format_id('rtmp'),
484 self._sort_formats(formats)
486 description = json_data.get('description')
487 thumbnail = json_data.get('thumbnail')
488 timestamp = parse_iso8601(json_data.get('published_at'))
489 duration = float_or_none(json_data.get('duration'), 1000)
490 tags = json_data.get('tags', [])
495 'description': description,
496 'thumbnail': thumbnail,
497 'duration': duration,
498 'timestamp': timestamp,
499 'uploader_id': account_id,