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