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