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