2 from __future__
import unicode_literals
7 from .common
import InfoExtractor
9 compat_etree_fromstring
,
12 compat_urllib_parse_urlparse
,
14 compat_xml_parse_error
,
34 class BrightcoveLegacyIE(InfoExtractor
):
35 IE_NAME
= 'brightcove:legacy'
36 _VALID_URL
= r
'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
37 _FEDERATED_URL
= 'http://c.brightcove.com/services/viewer/htmlFederated'
41 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
42 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
43 'md5': '5423e113865d26e40624dce2e4b45d95',
44 'note': 'Test Brightcove downloads and detection in GenericIE',
46 'id': '2371591881001',
48 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
50 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
51 'timestamp': 1368213670,
52 'upload_date': '20130510',
53 'uploader_id': '1589608506001',
57 # From http://medianetwork.oracle.com/video/player/1785452137001
58 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
60 'id': '1785452137001',
62 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
63 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
65 'timestamp': 1344975024,
66 'upload_date': '20120814',
67 'uploader_id': '1460825906',
71 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
72 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
74 'id': '2750934548001',
76 'title': 'This Bracelet Acts as a Personal Thermostat',
77 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
78 'uploader': 'Mashable',
79 'timestamp': 1382041798,
80 'upload_date': '20131017',
81 'uploader_id': '1130468786001',
85 # test that the default referer works
86 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
87 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
89 'id': '2878862109001',
91 'title': 'Lost in Motion II',
92 'description': 'md5:363109c02998fee92ec02211bd8000df',
93 'uploader': 'National Ballet of Canada',
98 # test flv videos served by akamaihd.net
99 # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
100 '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',
101 # The md5 checksum changes on each download
103 'id': '3750436379001',
105 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
106 'uploader': 'RBTV Old (do not use)',
107 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
108 'timestamp': 1409122195,
109 'upload_date': '20140827',
110 'uploader_id': '710858724001',
114 # playlist with 'videoList'
115 # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
116 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
119 'id': '3550319591001',
121 'playlist_mincount': 7,
124 # playlist with 'playlistTab' (https://github.com/rg3/youtube-dl/issues/9965)
125 'url': 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=AQ%7E%7E,AAABXlLMdok%7E,NJ4EoMlZ4rZdx9eU1rkMVd8EaYPBBUlg',
127 'id': '1522758701001',
128 'title': 'Lesson 08',
130 'playlist_mincount': 10,
141 def _build_brighcove_url(cls
, object_str
):
143 Build a Brightcove url from a xml string containing
144 <object class="BrightcoveExperience">{params}</object>
147 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
148 object_str
= re
.sub(r
'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
149 lambda m
: m
.group(1) + '/>', object_str
)
150 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
151 object_str
= object_str
.replace('<--', '<!--')
152 # remove namespace to simplify extraction
153 object_str
= re
.sub(r
'(<object[^>]*)(xmlns=".*?")', r
'\1', object_str
)
154 object_str
= fix_xml_ampersands(object_str
)
157 object_doc
= compat_etree_fromstring(object_str
.encode('utf-8'))
158 except compat_xml_parse_error
:
161 fv_el
= find_xpath_attr(object_doc
, './param', 'name', 'flashVars')
162 if fv_el
is not None:
165 for k
, v
in compat_parse_qs(fv_el
.attrib
['value']).items())
169 data_url
= object_doc
.attrib
.get('data', '')
170 data_url_params
= compat_parse_qs(compat_urllib_parse_urlparse(data_url
).query
)
172 def find_param(name
):
173 if name
in flashvars
:
174 return flashvars
[name
]
175 node
= find_xpath_attr(object_doc
, './param', 'name', name
)
177 return node
.attrib
['value']
178 return data_url_params
.get(name
)
182 playerID
= find_param('playerID') or find_param('playerId')
184 raise ExtractorError('Cannot find player ID')
185 params
['playerID'] = playerID
187 playerKey
= find_param('playerKey')
188 # Not all pages define this value
189 if playerKey
is not None:
190 params
['playerKey'] = playerKey
191 # These fields hold the id of the video
192 videoPlayer
= find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
193 if videoPlayer
is not None:
194 if isinstance(videoPlayer
, list):
195 videoPlayer
= videoPlayer
[0]
196 videoPlayer
= videoPlayer
.strip()
197 # UUID is also possible for videoPlayer (e.g.
198 # http://www.popcornflix.com/hoodies-vs-hooligans/7f2d2b87-bbf2-4623-acfb-ea942b4f01dd
199 # or http://www8.hp.com/cn/zh/home.html)
201 r
'^(?:\d+|[\da-fA-F]{8}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{12})$',
202 videoPlayer
) or videoPlayer
.startswith('ref:')):
204 params
['@videoPlayer'] = videoPlayer
205 linkBase
= find_param('linkBaseURL')
206 if linkBase
is not None:
207 params
['linkBaseURL'] = linkBase
208 return cls
._make
_brightcove
_url
(params
)
211 def _build_brighcove_url_from_js(cls
, object_js
):
212 # The layout of JS is as follows:
213 # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
214 # // build Brightcove <object /> XML
217 r
'''(?x)customBC\.createVideo\(
218 .*? # skipping width and height
219 ["\'](?P
<playerID
>\d
+)["\']\s*,\s* # playerID
220 ["\'](?P
<playerKey
>AQ
[^
"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
221 # in length, however it's appended to itself
222 # in places, so truncate
223 ["\'](?P
<videoID
>\d
+)["\'] # @videoPlayer
226 return cls._make_brightcove_url(m.groupdict())
229 def _make_brightcove_url(cls, params):
230 return update_url_query(cls._FEDERATED_URL, params)
233 def _extract_brightcove_url(cls, webpage):
234 """Try to extract the brightcove url from the webpage, returns None
237 urls = cls._extract_brightcove_urls(webpage)
238 return urls[0] if urls else None
241 def _extract_brightcove_urls(cls, webpage):
242 """Return a list of all Brightcove URLs from the webpage """
247 (?:property|itemprop)=([\'"])(?
:og
:video|embedURL
)\
1[^
>]+
248 content
=([\'"])(?P<url>https?://(?:secure|c)\.brightcove.com/(?:(?!\2).)+)\2
251 url = unescapeHTML(url_m.group('url'))
252 # Some sites don't add it, we can't download with this url, for example:
253 # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
254 if 'playerKey' in url or 'videoId' in url or 'idVideo' in url:
257 matches = re.findall(
260 [^>]+?class=[\'"][^
>]*?BrightcoveExperience
.*?
[\'"] |
261 [^>]*?>\s*<param\s+name="movie
"\s+value="https?
://[^
/]*brightcove\
.com
/
262 ).+?
>\s
*</object>''',
265 return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
267 return list(filter(None, [
268 cls._build_brighcove_url_from_js(custom_bc)
269 for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
271 def _real_extract(self, url):
272 url, smuggled_data = unsmuggle_url(url, {})
274 # Change the 'videoId' and others field to '@videoPlayer'
275 url = re.sub(r'(?<=[?&])(videoI(d|D)|idVideo|bctid)', '%40videoPlayer', url)
276 # Change bckey (used by bcove.me urls) to playerKey
277 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
278 mobj = re.match(self._VALID_URL, url)
279 query_str = mobj.group('query')
280 query = compat_urlparse.parse_qs(query_str)
282 videoPlayer = query.get('@videoPlayer')
284 # We set the original url as the default 'Referer' header
285 referer = smuggled_data.get('Referer', url)
286 return self._get_video_info(
287 videoPlayer[0], query, referer=referer)
288 elif 'playerKey' in query:
289 player_key = query['playerKey']
290 return self._get_playlist_info(player_key[0])
292 raise ExtractorError(
293 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
296 def _get_video_info(self, video_id, query, referer=None):
298 linkBase = query.get('linkBaseURL')
299 if linkBase is not None:
300 referer = linkBase[0]
301 if referer is not None:
302 headers['Referer'] = referer
303 webpage = self._download_webpage(self._FEDERATED_URL, video_id, headers=headers, query=query)
305 error_msg = self._html_search_regex(
306 r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
307 'error message', default=None)
308 if error_msg is not None:
309 raise ExtractorError(
310 'brightcove said: %s' % error_msg, expected=True)
312 self.report_extraction(video_id)
313 info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
314 info = json.loads(info)['data']
315 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
316 video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
318 return self._extract_video_info(video_info)
320 def _get_playlist_info(self, player_key):
321 info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
322 playlist_info = self._download_webpage(
323 info_url, player_key, 'Downloading playlist information')
325 json_data = json.loads(playlist_info)
326 if 'videoList' in json_data:
327 playlist_info = json_data['videoList']
328 playlist_dto = playlist_info['mediaCollectionDTO']
329 elif 'playlistTabs' in json_data:
330 playlist_info = json_data['playlistTabs']
331 playlist_dto = playlist_info['lineupListDTO']['playlistDTOs'][0]
333 raise ExtractorError('Empty playlist')
335 videos = [self._extract_video_info(video_info) for video_info in playlist_dto['videoDTOs']]
337 return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
338 playlist_title=playlist_dto['displayName'])
340 def _extract_video_info(self, video_info):
341 video_id = compat_str(video_info['id'])
342 publisher_id = video_info.get('publisherId')
345 'title': video_info['displayName'].strip(),
346 'description': video_info.get('shortDescription'),
347 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
348 'uploader': video_info.get('publisherName'),
349 'uploader_id': compat_str(publisher_id) if publisher_id else None,
350 'duration': float_or_none(video_info.get('length'), 1000),
351 'timestamp': int_or_none(video_info.get('creationDate'), 1000),
354 renditions = video_info.get('renditions', []) + video_info.get('IOSRenditions', [])
357 for rend in renditions:
358 url = rend['defaultURL']
363 url_comp = compat_urllib_parse_urlparse(url)
364 if url_comp.path.endswith('.m3u8'):
366 self._extract_m3u8_formats(
367 url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
369 elif 'akamaihd.net' in url_comp.netloc:
370 # This type of renditions are served through
371 # akamaihd.net, but they don't use f4m manifests
372 url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
375 ext = determine_ext(url)
376 tbr = int_or_none(rend.get('encodingRate'), 1000)
378 'format_id': 'http%s' % ('-%s' % tbr if tbr else ''),
381 'filesize': int_or_none(rend.get('size')) or None,
384 if rend.get('audioOnly'):
390 'height': int_or_none(rend.get('frameHeight')),
391 'width': int_or_none(rend.get('frameWidth')),
392 'vcodec': rend.get('videoCodec'),
395 # m3u8 manifests with remote == false are media playlists
396 # Not calling _extract_m3u8_formats here to save network traffic
399 'format_id': 'hls%s' % ('-%s' % tbr if tbr else ''),
401 'protocol': 'm3u8_native',
404 formats.append(a_format)
405 self._sort_formats(formats)
406 info['formats'] = formats
407 elif video_info.get('FLVFullLengthURL') is not None:
409 'url': video_info['FLVFullLengthURL'],
410 'vcodec': self.FLV_VCODECS.get(video_info.get('FLVFullCodec')),
411 'filesize': int_or_none(video_info.get('FLVFullSize')),
414 if self._downloader.params.get('include_ads', False):
415 adServerURL = video_info.get('_youtubedl_adServerURL')
424 'title': info['title'],
425 'entries': [ad_info, info],
430 if 'url' not in info and not info.get('formats'):
431 raise ExtractorError('Unable to extract video url for %s' % video_id)
435 class BrightcoveNewIE(InfoExtractor):
436 IE_NAME = 'brightcove:new'
437 _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
439 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
440 'md5': 'c8100925723840d4b0d243f7025703be',
442 'id': '4463358922001',
444 'title': 'Meet the man behind Popcorn Time',
445 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
447 'timestamp': 1441391203,
448 'upload_date': '20150904',
449 'uploader_id': '929656772001',
450 'formats': 'mincount:22',
454 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
456 'id': '4279049078001',
458 'title': 'Titansgrave: Chapter 0',
459 'description': 'Titansgrave: Chapter 0',
460 'duration': 1242.058,
461 'timestamp': 1433556729,
462 'upload_date': '20150606',
463 'uploader_id': '4036320279001',
464 'formats': 'mincount:41',
468 'skip_download': True,
471 # ref: prefixed video id
472 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
473 'only_matching': True,
475 # non numeric ref: prefixed video id
476 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
477 'only_matching': True,
479 # unavailable video without message but with error_code
480 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001',
481 'only_matching': True,
485 def _extract_url(webpage):
486 urls = BrightcoveNewIE._extract_urls(webpage)
487 return urls[0] if urls else None
490 def _extract_urls(webpage):
492 # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
493 # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
494 # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
495 # 4. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
499 # Look for iframe embeds [1]
500 for _, url in re.findall(
501 r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
502 entries.append(url if url.startswith('http') else 'http:' + url)
504 # Look for embed_in_page embeds [2]
505 for video_id, account_id, player_id, embed in re.findall(
506 # According to examples from [3] it's unclear whether video id
507 # may be optional and what to do when it is
508 # According to [4] data-video-id may be prefixed with ref:
511 data
-video
-id=["\'](\d+|ref:[^"\']+)["\'][^>]*>.*?
514 src=["\'](?
:https?
:)?
//players\
.brightcove\
.net
/
515 (\d
+)/([^
/]+)_([^
/]+)/index(?
:\
.min)?\
.js
518 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
519 % (account_id, player_id, embed, video_id))
523 def _real_extract(self, url):
524 url, smuggled_data = unsmuggle_url(url, {})
525 self._initialize_geo_bypass(smuggled_data.get('geo_countries'))
527 account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
529 webpage = self._download_webpage(
530 'http://players.brightcove.net/%s/%s_%s/index.min.js'
531 % (account_id, player_id, embed), video_id)
535 catalog = self._search_regex(
536 r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
538 catalog = self._parse_json(
539 js_to_json(catalog), video_id, fatal=False)
541 policy_key = catalog.get('policyKey')
544 policy_key = self._search_regex(
545 r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
546 webpage, 'policy key', group='pk')
548 api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
550 json_data = self._download_json(api_url, video_id, headers={
551 'Accept': 'application/json;pk=%s' % policy_key
553 except ExtractorError as e:
554 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
555 json_data = self._parse_json(e.cause.read().decode(), video_id)[0]
556 message = json_data.get('message') or json_data['error_code']
557 if json_data.get('error_subcode') == 'CLIENT_GEO':
558 self.raise_geo_restricted(msg=message)
559 raise ExtractorError(message, expected=True)
562 title = json_data['name'].strip()
565 for source in json_data.get('sources', []):
566 container = source.get('container')
567 ext = mimetype2ext(source.get('type'))
568 src = source.get('src')
569 if ext == 'ism' or container == 'WVM':
571 elif ext == 'm3u8' or container == 'M2TS':
574 formats.extend(self._extract_m3u8_formats(
575 src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
579 formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
581 streaming_src = source.get('streaming_src')
582 stream_name, app_name = source.get('stream_name'), source.get('app_name')
583 if not src and not streaming_src and (not stream_name or not app_name):
585 tbr = float_or_none(source.get('avg_bitrate'), 1000)
586 height = int_or_none(source.get('height'))
587 width = int_or_none(source.get('width'))
590 'filesize': int_or_none(source.get('size')),
591 'container': container,
592 'ext': ext or container.lower(),
594 if width == 0 and height == 0:
602 'vcodec': source.get('codec'),
605 def build_format_id(kind):
608 format_id += '-%dk' % int(tbr)
610 format_id += '-%dp' % height
613 if src or streaming_src:
615 'url': src or streaming_src,
616 'format_id': build_format_id('http' if src else 'http-streaming'),
617 'source_preference': 0 if src else -1,
622 'play_path': stream_name,
623 'format_id': build_format_id('rtmp'),
627 errors = json_data.get('errors')
628 if not formats and errors:
630 raise ExtractorError(
631 error.get('message') or error.get('error_subcode') or error['error_code'], expected=True)
633 self._sort_formats(formats)
636 for text_track in json_data.get('text_tracks', []):
637 if text_track.get('src'):
638 subtitles.setdefault(text_track.get('srclang'), []).append({
639 'url': text_track['src'],
643 duration = float_or_none(json_data.get('duration'), 1000)
644 if duration and duration < 0:
649 'title': self._live_title(title) if is_live else title,
650 'description': clean_html(json_data.get('description')),
651 'thumbnail': json_data.get('thumbnail') or json_data.get('poster'),
652 'duration': duration,
653 'timestamp': parse_iso8601(json_data.get('published_at')),
654 'uploader_id': account_id,
656 'subtitles': subtitles,
657 'tags': json_data.get('tags', []),