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