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