2 from __future__ import unicode_literals
6 import xml.etree.ElementTree
8 from .common import InfoExtractor
15 compat_urllib_request,
25 class BrightcoveIE(InfoExtractor):
26 _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*?\?(?P<query>.*)'
27 _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
31 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
32 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
33 'md5': '5423e113865d26e40624dce2e4b45d95',
34 'note': 'Test Brightcove downloads and detection in GenericIE',
36 'id': '2371591881001',
38 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
40 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
44 # From http://medianetwork.oracle.com/video/player/1785452137001
45 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
47 'id': '1785452137001',
49 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
50 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
55 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
56 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
58 'id': '2750934548001',
60 'title': 'This Bracelet Acts as a Personal Thermostat',
61 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
62 'uploader': 'Mashable',
66 # test that the default referer works
67 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
68 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
70 'id': '2878862109001',
72 'title': 'Lost in Motion II',
73 'description': 'md5:363109c02998fee92ec02211bd8000df',
74 'uploader': 'National Ballet of Canada',
78 # test flv videos served by akamaihd.net
79 # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
80 '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',
81 # The md5 checksum changes on each download
83 'id': '2996102916001',
85 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
86 'uploader': 'Red Bull TV',
87 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
92 # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
93 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
97 'playlist_mincount': 7,
102 def _build_brighcove_url(cls, object_str):
104 Build a Brightcove url from a xml string containing
105 <object class="BrightcoveExperience">{params}</object>
108 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
109 object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
110 lambda m: m.group(1) + '/>', object_str)
111 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
112 object_str = object_str.replace('<--', '<!--')
113 object_str = fix_xml_ampersands(object_str)
115 object_doc = xml.etree.ElementTree.fromstring(object_str.encode('utf-8'))
117 fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
118 if fv_el is not None:
121 for k, v in compat_parse_qs(fv_el.attrib['value']).items())
125 def find_param(name):
126 if name in flashvars:
127 return flashvars[name]
128 node = find_xpath_attr(object_doc, './param', 'name', name)
130 return node.attrib['value']
135 playerID = find_param('playerID')
137 raise ExtractorError('Cannot find player ID')
138 params['playerID'] = playerID
140 playerKey = find_param('playerKey')
141 # Not all pages define this value
142 if playerKey is not None:
143 params['playerKey'] = playerKey
144 # The three fields hold the id of the video
145 videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
146 if videoPlayer is not None:
147 params['@videoPlayer'] = videoPlayer
148 linkBase = find_param('linkBaseURL')
149 if linkBase is not None:
150 params['linkBaseURL'] = linkBase
151 data = compat_urllib_parse.urlencode(params)
152 return cls._FEDERATED_URL_TEMPLATE % data
155 def _extract_brightcove_url(cls, webpage):
156 """Try to extract the brightcove url from the webpage, returns None
159 urls = cls._extract_brightcove_urls(webpage)
160 return urls[0] if urls else None
163 def _extract_brightcove_urls(cls, webpage):
164 """Return a list of all Brightcove URLs from the webpage """
167 r'<meta\s+property="og:video"\s+content="(https?://(?:secure|c)\.brightcove.com/[^"]+)"',
170 url = unescapeHTML(url_m.group(1))
171 # Some sites don't add it, we can't download with this url, for example:
172 # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
173 if 'playerKey' in url or 'videoId' in url:
176 matches = re.findall(
179 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
180 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
183 return [cls._build_brighcove_url(m) for m in matches]
185 def _real_extract(self, url):
186 url, smuggled_data = unsmuggle_url(url, {})
188 # Change the 'videoId' and others field to '@videoPlayer'
189 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
190 # Change bckey (used by bcove.me urls) to playerKey
191 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
192 mobj = re.match(self._VALID_URL, url)
193 query_str = mobj.group('query')
194 query = compat_urlparse.parse_qs(query_str)
196 videoPlayer = query.get('@videoPlayer')
198 # We set the original url as the default 'Referer' header
199 referer = smuggled_data.get('Referer', url)
200 return self._get_video_info(
201 videoPlayer[0], query_str, query, referer=referer)
202 elif 'playerKey' in query:
203 player_key = query['playerKey']
204 return self._get_playlist_info(player_key[0])
206 raise ExtractorError(
207 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
210 def _get_video_info(self, video_id, query_str, query, referer=None):
211 request_url = self._FEDERATED_URL_TEMPLATE % query_str
212 req = compat_urllib_request.Request(request_url)
213 linkBase = query.get('linkBaseURL')
214 if linkBase is not None:
215 referer = linkBase[0]
216 if referer is not None:
217 req.add_header('Referer', referer)
218 webpage = self._download_webpage(req, video_id)
220 error_msg = self._html_search_regex(
221 r"<h1>We're sorry.</h1>\s*<p>(.*?)</p>", webpage,
222 'error message', default=None)
223 if error_msg is not None:
224 raise ExtractorError(
225 'brightcove said: %s' % error_msg, expected=True)
227 self.report_extraction(video_id)
228 info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
229 info = json.loads(info)['data']
230 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
231 video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
233 return self._extract_video_info(video_info)
235 def _get_playlist_info(self, player_key):
236 info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
237 playlist_info = self._download_webpage(
238 info_url, player_key, 'Downloading playlist information')
240 json_data = json.loads(playlist_info)
241 if 'videoList' not in json_data:
242 raise ExtractorError('Empty playlist')
243 playlist_info = json_data['videoList']
244 videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
246 return self.playlist_result(videos, playlist_id=playlist_info['id'],
247 playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
249 def _extract_video_info(self, video_info):
251 'id': compat_str(video_info['id']),
252 'title': video_info['displayName'].strip(),
253 'description': video_info.get('shortDescription'),
254 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
255 'uploader': video_info.get('publisherName'),
258 renditions = video_info.get('renditions')
261 for rend in renditions:
262 url = rend['defaultURL']
266 # This type of renditions are served through akamaihd.net,
267 # but they don't use f4m manifests
268 url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
271 ext = determine_ext(url)
272 size = rend.get('size')
276 'height': rend.get('frameHeight'),
277 'width': rend.get('frameWidth'),
278 'filesize': size if size != 0 else None,
280 self._sort_formats(formats)
281 info['formats'] = formats
282 elif video_info.get('FLVFullLengthURL') is not None:
284 'url': video_info['FLVFullLengthURL'],
287 if self._downloader.params.get('include_ads', False):
288 adServerURL = video_info.get('_youtubedl_adServerURL')
297 'title': info['title'],
298 'entries': [ad_info, info],
303 if 'url' not in info and not info.get('formats'):
304 raise ExtractorError('Unable to extract video url for %s' % info['id'])