]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/brightcove.py
[cleanup] Add more ruff rules (#10149)
[yt-dlp.git] / yt_dlp / extractor / brightcove.py
CommitLineData
160c2773 1import base64
160c2773
RA
2import re
3import struct
add96eb9 4import urllib.parse
f9934b96 5import xml.etree.ElementTree
fbaaad49 6
5996d21a 7from .adobepass import AdobePassIE
c8b232cc 8from .common import InfoExtractor
add96eb9 9from ..compat import compat_etree_fromstring
3d2623a8 10from ..networking.exceptions import HTTPError
1cc79574 11from ..utils import (
e897bd82
SS
12 ExtractorError,
13 UnsupportedError,
c8b232cc 14 clean_html,
487c5b33 15 dict_get,
40158f55 16 extract_attributes,
1cc79574
PH
17 find_xpath_attr,
18 fix_xml_ampersands,
a6624898 19 float_or_none,
ed126900 20 int_or_none,
c8b232cc
S
21 js_to_json,
22 mimetype2ext,
ed126900 23 parse_iso8601,
4dfbf869 24 parse_qs,
f455a934 25 smuggle_url,
b4eb0bc7 26 str_or_none,
29f7c58a 27 try_get,
fd91257c
S
28 unescapeHTML,
29 unsmuggle_url,
48254c3f 30 update_url_query,
b4eb0bc7 31 url_or_none,
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>.*)'
592882aa
JMF
38
39 _TESTS = [
40 {
4de1994b 41 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
400e5810 42 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
400e5810
PH
43 'md5': '5423e113865d26e40624dce2e4b45d95',
44 'note': 'Test Brightcove downloads and detection in GenericIE',
45 'info_dict': {
96bef88f
JMF
46 'id': '2371591881001',
47 'ext': 'mp4',
400e5810
PH
48 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
49 'uploader': '8TV',
50 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
41f5492f 51 'timestamp': 1368213670,
52 'upload_date': '20130510',
4d4cd35f 53 'uploader_id': '1589608506001',
f455a934
RA
54 },
55 'skip': 'The player has been deactivated by the content owner',
592882aa
JMF
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 69 },
f455a934 70 'skip': 'video not playable',
592882aa 71 },
fc4a0c2a
JMF
72 {
73 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
400e5810
PH
74 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
75 'info_dict': {
76 'id': '2750934548001',
77 'ext': 'mp4',
78 'title': 'This Bracelet Acts as a Personal Thermostat',
79 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
f455a934 80 # 'uploader': 'Mashable',
41f5492f 81 'timestamp': 1382041798,
82 'upload_date': '20131017',
4d4cd35f 83 'uploader_id': '1130468786001',
fc4a0c2a
JMF
84 },
85 },
77526143
JMF
86 {
87 # test that the default referer works
88 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
400e5810
PH
89 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
90 'info_dict': {
91 'id': '2878862109001',
92 'ext': 'mp4',
93 'title': 'Lost in Motion II',
94 'description': 'md5:363109c02998fee92ec02211bd8000df',
95 'uploader': 'National Ballet of Canada',
77526143 96 },
c65aa4e9 97 'skip': 'Video gone',
5524b242
JMF
98 },
99 {
100 # test flv videos served by akamaihd.net
101 # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
41f5492f 102 '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
103 # The md5 checksum changes on each download
104 'info_dict': {
41f5492f 105 'id': '3750436379001',
5524b242
JMF
106 'ext': 'flv',
107 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
41f5492f 108 'uploader': 'RBTV Old (do not use)',
5524b242 109 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
41f5492f 110 'timestamp': 1409122195,
111 'upload_date': '20140827',
4d4cd35f 112 'uploader_id': '710858724001',
5524b242 113 },
40158f55 114 'skip': 'Video gone',
5524b242 115 },
bd4e40df 116 {
c65aa4e9 117 # playlist with 'videoList'
bd4e40df
JMF
118 # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
119 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
120 'info_dict': {
121 'title': 'Sealife',
d47c26e1 122 'id': '3550319591001',
bd4e40df
JMF
123 },
124 'playlist_mincount': 7,
f455a934 125 'skip': 'Unsupported URL',
bd4e40df 126 },
c65aa4e9 127 {
067aa17e 128 # playlist with 'playlistTab' (https://github.com/ytdl-org/youtube-dl/issues/9965)
c65aa4e9
YCH
129 'url': 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=AQ%7E%7E,AAABXlLMdok%7E,NJ4EoMlZ4rZdx9eU1rkMVd8EaYPBBUlg',
130 'info_dict': {
131 'id': '1522758701001',
132 'title': 'Lesson 08',
133 },
134 'playlist_mincount': 10,
f455a934 135 'skip': 'Unsupported URL',
c65aa4e9 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
add96eb9 142 },
592882aa 143 ]
cfe50f04 144
f5a9e9df 145 _WEBPAGE_TESTS = [{
146 # embedded brightcove video
147 # it also tests brightcove videos that need to set the 'Referer'
148 # in the http requests
149 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
150 'info_dict': {
151 'id': '2765128793001',
152 'ext': 'mp4',
153 'title': 'Le cours de bourse : l’analyse technique',
154 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
155 'uploader': 'BFM BUSINESS',
156 },
157 'params': {
158 'skip_download': True,
159 },
160 'skip': '404 Not Found',
161 }, {
162 # embedded with itemprop embedURL and video id spelled as `idVideo`
163 'url': 'http://bfmbusiness.bfmtv.com/mediaplayer/chroniques/olivier-delamarche/',
164 'info_dict': {
165 'id': '5255628253001',
166 'ext': 'mp4',
167 'title': 'md5:37c519b1128915607601e75a87995fc0',
168 'description': 'md5:37f7f888b434bb8f8cc8dbd4f7a4cf26',
169 'uploader': 'BFM BUSINESS',
170 'uploader_id': '876450612001',
171 'timestamp': 1482255315,
172 'upload_date': '20161220',
173 },
174 'params': {
175 'skip_download': True,
176 },
177 'skip': 'Redirects, page gone',
178 }, {
179 # https://github.com/ytdl-org/youtube-dl/issues/2253
180 'url': 'http://bcove.me/i6nfkrc3',
181 'md5': '0ba9446db037002366bab3b3eb30c88c',
182 'info_dict': {
183 'id': '3101154703001',
184 'ext': 'mp4',
185 'title': 'Still no power',
186 'uploader': 'thestar.com',
187 'description': 'Mississauga resident David Farmer is still out of power as a result of the ice storm a month ago. To keep the house warm, Farmer cuts wood from his property for a wood burning stove downstairs.',
188 },
189 'skip': 'video gone',
190 }, {
191 # https://github.com/ytdl-org/youtube-dl/issues/3541
192 'url': 'http://www.kijk.nl/sbs6/leermijvrouwenkennen/videos/jqMiXKAYan2S/aflevering-1',
193 'info_dict': {
194 'id': '3866516442001',
195 'ext': 'mp4',
196 'title': 'Leer mij vrouwen kennen: Aflevering 1',
197 'description': 'Leer mij vrouwen kennen: Aflevering 1',
198 'uploader': 'SBS Broadcasting',
199 },
200 'skip': 'Restricted to Netherlands, 404 Not Found',
201 'params': {
202 'skip_download': True, # m3u8 download
203 },
204 }, {
205 # Brightcove video in <iframe>
206 'url': 'http://www.un.org/chinese/News/story.asp?NewsID=27724',
207 'md5': '36d74ef5e37c8b4a2ce92880d208b968',
208 'info_dict': {
209 'id': '5360463607001',
210 'ext': 'mp4',
211 'title': '叙利亚失明儿童在废墟上演唱《心跳》 呼吁获得正常童年生活',
212 'description': '联合国儿童基金会中东和北非区域大使、作曲家扎德·迪拉尼(Zade Dirani)在3月15日叙利亚冲突爆发7周年纪念日之际发布了为叙利亚谱写的歌曲《心跳》(HEARTBEAT),为受到六年冲突影响的叙利亚儿童发出强烈呐喊,呼吁世界做出共同努力,使叙利亚儿童重新获得享有正常童年生活的权利。',
213 'uploader': 'United Nations',
214 'uploader_id': '1362235914001',
215 'timestamp': 1489593889,
216 'upload_date': '20170315',
217 },
218 'skip': '404 Not Found',
219 }, {
220 # Brightcove with UUID in videoPlayer
221 'url': 'http://www8.hp.com/cn/zh/home.html',
222 'info_dict': {
223 'id': '5255815316001',
224 'ext': 'mp4',
225 'title': 'Sprocket Video - China',
226 'description': 'Sprocket Video - China',
227 'uploader': 'HP-Video Gallery',
228 'timestamp': 1482263210,
229 'upload_date': '20161220',
230 'uploader_id': '1107601872001',
231 },
232 'params': {
233 'skip_download': True, # m3u8 download
234 },
235 'skip': 'video rotates...weekly?',
236 }, {
237 # Multiple brightcove videos
238 # https://github.com/ytdl-org/youtube-dl/issues/2283
239 'url': 'http://www.newyorker.com/online/blogs/newsdesk/2014/01/always-never-nuclear-command-and-control.html',
240 'info_dict': {
241 'id': 'always-never',
242 'title': 'Always / Never - The New Yorker',
243 },
244 'playlist_count': 3,
245 'params': {
246 'extract_flat': False,
247 'skip_download': True,
248 },
249 'skip': 'Redirects, page gone',
250 }, {
251 # BrightcoveInPageEmbed embed
252 'url': 'http://www.geekandsundry.com/tabletop-bonus-wils-final-thoughts-on-dread/',
253 'info_dict': {
254 'id': '4238694884001',
255 'ext': 'flv',
256 'title': 'Tabletop: Dread, Last Thoughts',
257 'description': 'Tabletop: Dread, Last Thoughts',
258 'duration': 51690,
259 },
260 'skip': 'Redirects, page gone',
261 }, {
262 # Brightcove embed, with no valid 'renditions' but valid 'IOSRenditions'
263 # This video can't be played in browsers if Flash disabled and UA set to iPhone, which is actually a false alarm
264 'url': 'https://dl.dropboxusercontent.com/u/29092637/interview.html',
265 'info_dict': {
266 'id': '4785848093001',
267 'ext': 'mp4',
268 'title': 'The Cardinal Pell Interview',
269 'description': 'Sky News Contributor Andrew Bolt interviews George Pell in Rome, following the Cardinal\'s evidence before the Royal Commission into Child Abuse. ',
270 'uploader': 'GlobeCast Australia - GlobeStream',
271 'uploader_id': '2733773828001',
272 'upload_date': '20160304',
273 'timestamp': 1457083087,
274 },
275 'params': {
276 # m3u8 downloads
277 'skip_download': True,
278 },
279 'skip': '404 Not Found',
280 }, {
281 # Brightcove embed with whitespace around attribute names
282 'url': 'http://www.stack.com/video/3167554373001/learn-to-hit-open-three-pointers-with-damian-lillard-s-baseline-drift-drill',
283 'info_dict': {
284 'id': '3167554373001',
285 'ext': 'mp4',
286 'title': "Learn to Hit Open Three-Pointers With Damian Lillard's Baseline Drift Drill",
287 'description': 'md5:57bacb0e0f29349de4972bfda3191713',
288 'uploader_id': '1079349493',
289 'upload_date': '20140207',
290 'timestamp': 1391810548,
291 },
292 'params': {
293 'skip_download': True,
294 },
295 'skip': '410 Gone',
296 }]
297
cfe50f04 298 @classmethod
a0566bbf 299 def _build_brightcove_url(cls, object_str):
cfe50f04
JMF
300 """
301 Build a Brightcove url from a xml string containing
302 <object class="BrightcoveExperience">{params}</object>
303 """
46e28a84 304
067aa17e 305 # Fix up some stupid HTML, see https://github.com/ytdl-org/youtube-dl/issues/1553
c1147c05 306 object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
46e28a84 307 lambda m: m.group(1) + '/>', object_str)
067aa17e 308 # Fix up some stupid XML, see https://github.com/ytdl-org/youtube-dl/issues/1608
400e5810 309 object_str = object_str.replace('<--', '<!--')
d6f714f3
JMF
310 # remove namespace to simplify extraction
311 object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
7b0817e8 312 object_str = fix_xml_ampersands(object_str)
46e28a84 313
94c12557 314 try:
add96eb9 315 object_doc = compat_etree_fromstring(object_str.encode())
f9934b96 316 except xml.etree.ElementTree.ParseError:
94c12557 317 return
7b0817e8
PH
318
319 fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
47917f24
JMF
320 if fv_el is not None:
321 flashvars = dict(
322 (k, v[0])
add96eb9 323 for k, v in urllib.parse.parse_qs(fv_el.attrib['value']).items())
47917f24
JMF
324 else:
325 flashvars = {}
7b0817e8 326
5964b598 327 data_url = object_doc.attrib.get('data', '')
4dfbf869 328 data_url_params = parse_qs(data_url)
5964b598 329
36de0a0e 330 def find_param(name):
7b0817e8
PH
331 if name in flashvars:
332 return flashvars[name]
d214fdb8
JMF
333 node = find_xpath_attr(object_doc, './param', 'name', name)
334 if node is not None:
335 return node.attrib['value']
5964b598 336 return data_url_params.get(name)
7b0817e8
PH
337
338 params = {}
339
add96eb9 340 player_id = find_param('playerID') or find_param('playerId')
341 if player_id is None:
7b0817e8 342 raise ExtractorError('Cannot find player ID')
add96eb9 343 params['playerID'] = player_id
7b0817e8 344
add96eb9 345 player_key = find_param('playerKey')
cfe50f04 346 # Not all pages define this value
add96eb9 347 if player_key is not None:
348 params['playerKey'] = player_key
48254c3f 349 # These fields hold the id of the video
add96eb9 350 video_player = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
351 if video_player is not None:
352 if isinstance(video_player, list):
353 video_player = video_player[0]
354 video_player = video_player.strip()
2e76bdc8
S
355 # UUID is also possible for videoPlayer (e.g.
356 # http://www.popcornflix.com/hoodies-vs-hooligans/7f2d2b87-bbf2-4623-acfb-ea942b4f01dd
357 # or http://www8.hp.com/cn/zh/home.html)
358 if not (re.match(
359 r'^(?:\d+|[\da-fA-F]{8}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{12})$',
add96eb9 360 video_player) or video_player.startswith('ref:')):
049a0f4d 361 return None
add96eb9 362 params['@videoPlayer'] = video_player
363 link_base = find_param('linkBaseURL')
364 if link_base is not None:
365 params['linkBaseURL'] = link_base
af9cdee9
S
366 return cls._make_brightcove_url(params)
367
368 @classmethod
a0566bbf 369 def _build_brightcove_url_from_js(cls, object_js):
af9cdee9
S
370 # The layout of JS is as follows:
371 # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
372 # // build Brightcove <object /> XML
373 # }
374 m = re.search(
4f66c16f 375 r'''(?x)customBC\.createVideo\(
af9cdee9
S
376 .*? # skipping width and height
377 ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
378 ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
379 # in length, however it's appended to itself
380 # in places, so truncate
381 ["\'](?P<videoID>\d+)["\'] # @videoPlayer
382 ''', object_js)
383 if m:
384 return cls._make_brightcove_url(m.groupdict())
385
386 @classmethod
387 def _make_brightcove_url(cls, params):
f455a934
RA
388 return update_url_query(
389 'http://c.brightcove.com/services/viewer/htmlFederated', params)
fbaaad49 390
eeb165e6
JMF
391 @classmethod
392 def _extract_brightcove_url(cls, webpage):
99877772 393 """Try to extract the brightcove url from the webpage, returns None
eeb165e6
JMF
394 if it can't be found
395 """
99877772
PH
396 urls = cls._extract_brightcove_urls(webpage)
397 return urls[0] if urls else None
398
399 @classmethod
400 def _extract_brightcove_urls(cls, webpage):
401 """Return a list of all Brightcove URLs from the webpage """
117bec93 402
e1ab5000 403 url_m = re.search(
53a664ed
S
404 r'''(?x)
405 <meta\s+
406 (?:property|itemprop)=([\'"])(?:og:video|embedURL)\1[^>]+
407 content=([\'"])(?P<url>https?://(?:secure|c)\.brightcove.com/(?:(?!\2).)+)\2
408 ''', webpage)
117bec93 409 if url_m:
53a664ed 410 url = unescapeHTML(url_m.group('url'))
381640e3
JMF
411 # Some sites don't add it, we can't download with this url, for example:
412 # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
53a664ed 413 if 'playerKey' in url or 'videoId' in url or 'idVideo' in url:
381640e3 414 return [url]
117bec93 415
99877772 416 matches = re.findall(
7b0817e8
PH
417 r'''(?sx)<object
418 (?:
99877772 419 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
7b0817e8 420 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
476e1095 421 ).+?>\s*</object>''',
7b0817e8 422 webpage)
b4e1576a 423 if matches:
a0566bbf 424 return list(filter(None, [cls._build_brightcove_url(m) for m in matches]))
b4e1576a 425
06d0ad9a
YCH
426 matches = re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)
427 if matches:
428 return list(filter(None, [
a0566bbf 429 cls._build_brightcove_url_from_js(custom_bc)
06d0ad9a 430 for custom_bc in matches]))
481ef51e 431 return [src for _, src in re.findall(
06d0ad9a 432 r'<iframe[^>]+src=([\'"])((?:https?:)?//link\.brightcove\.com/services/player/(?!\1).+)\1', webpage)]
eeb165e6 433
f5a9e9df 434 def _extract_from_webpage(self, url, webpage):
435 bc_urls = self._extract_brightcove_urls(webpage)
436 for bc_url in bc_urls:
437 yield self.url_result(smuggle_url(bc_url, {'Referer': url}), BrightcoveLegacyIE)
438
fbaaad49 439 def _real_extract(self, url):
79f82953
PH
440 url, smuggled_data = unsmuggle_url(url, {})
441
51040b72 442 # Change the 'videoId' and others field to '@videoPlayer'
53a664ed 443 url = re.sub(r'(?<=[?&])(videoI(d|D)|idVideo|bctid)', '%40videoPlayer', url)
51040b72
JMF
444 # Change bckey (used by bcove.me urls) to playerKey
445 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
5ad28e7f 446 mobj = self._match_valid_url(url)
6543f0dc 447 query_str = mobj.group('query')
add96eb9 448 query = urllib.parse.parse_qs(query_str)
fbaaad49 449
add96eb9 450 video_player = query.get('@videoPlayer')
451 if video_player:
79f82953 452 # We set the original url as the default 'Referer' header
f455a934 453 referer = query.get('linkBaseURL', [None])[0] or smuggled_data.get('Referer', url)
add96eb9 454 video_id = video_player[0]
06d0ad9a
YCH
455 if 'playerID' not in query:
456 mobj = re.search(r'/bcpid(\d+)', url)
457 if mobj is not None:
458 query['playerID'] = [mobj.group(1)]
160c2773
RA
459 publisher_id = query.get('publisherId')
460 if publisher_id and publisher_id[0].isdigit():
461 publisher_id = publisher_id[0]
462 if not publisher_id:
160c2773
RA
463 player_key = query.get('playerKey')
464 if player_key and ',' in player_key[0]:
465 player_key = player_key[0]
466 else:
467 player_id = query.get('playerID')
468 if player_id and player_id[0].isdigit():
f455a934
RA
469 headers = {}
470 if referer:
471 headers['Referer'] = referer
160c2773
RA
472 player_page = self._download_webpage(
473 'http://link.brightcove.com/services/player/bcpid' + player_id[0],
474 video_id, headers=headers, fatal=False)
475 if player_page:
476 player_key = self._search_regex(
477 r'<param\s+name="playerKey"\s+value="([\w~,-]+)"',
478 player_page, 'player key', fatal=False)
479 if player_key:
480 enc_pub_id = player_key.split(',')[1].replace('~', '=')
481 publisher_id = struct.unpack('>Q', base64.urlsafe_b64decode(enc_pub_id))[0]
f455a934 482 if publisher_id:
add96eb9 483 brightcove_new_url = f'http://players.brightcove.net/{publisher_id}/default_default/index.html?videoId={video_id}'
f455a934
RA
484 if referer:
485 brightcove_new_url = smuggle_url(brightcove_new_url, {'referrer': referer})
486 return self.url_result(brightcove_new_url, BrightcoveNewIE.ie_key(), video_id)
487 # TODO: figure out if it's possible to extract playlistId from playerKey
488 # elif 'playerKey' in query:
489 # player_key = query['playerKey']
490 # return self._get_playlist_info(player_key[0])
491 raise UnsupportedError(url)
ed126900 492
493
f5a9e9df 494class BrightcoveNewBaseIE(AdobePassIE):
495 def _parse_brightcove_metadata(self, json_data, video_id, headers={}):
496 title = json_data['name'].strip()
497
498 formats, subtitles = [], {}
499 sources = json_data.get('sources') or []
500 for source in sources:
501 container = source.get('container')
502 ext = mimetype2ext(source.get('type'))
503 src = source.get('src')
504 if ext == 'm3u8' or container == 'M2TS':
505 if not src:
506 continue
507 fmts, subs = self._extract_m3u8_formats_and_subtitles(
508 src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)
509 subtitles = self._merge_subtitles(subtitles, subs)
510 elif ext == 'mpd':
511 if not src:
512 continue
513 fmts, subs = self._extract_mpd_formats_and_subtitles(src, video_id, 'dash', fatal=False)
514 subtitles = self._merge_subtitles(subtitles, subs)
515 else:
516 streaming_src = source.get('streaming_src')
517 stream_name, app_name = source.get('stream_name'), source.get('app_name')
518 if not src and not streaming_src and (not stream_name or not app_name):
519 continue
520 tbr = float_or_none(source.get('avg_bitrate'), 1000)
521 height = int_or_none(source.get('height'))
522 width = int_or_none(source.get('width'))
523 f = {
524 'tbr': tbr,
525 'filesize': int_or_none(source.get('size')),
526 'container': container,
527 'ext': ext or container.lower(),
528 }
529 if width == 0 and height == 0:
530 f.update({
531 'vcodec': 'none',
532 })
533 else:
534 f.update({
535 'width': width,
536 'height': height,
537 'vcodec': source.get('codec'),
538 })
539
540 def build_format_id(kind):
541 format_id = kind
542 if tbr:
add96eb9 543 format_id += f'-{int(tbr)}k'
f5a9e9df 544 if height:
add96eb9 545 format_id += f'-{height}p'
f5a9e9df 546 return format_id
547
548 if src or streaming_src:
549 f.update({
550 'url': src or streaming_src,
551 'format_id': build_format_id('http' if src else 'http-streaming'),
552 'source_preference': 0 if src else -1,
553 })
554 else:
555 f.update({
556 'url': app_name,
557 'play_path': stream_name,
558 'format_id': build_format_id('rtmp'),
559 })
560 fmts = [f]
561
562 # https://support.brightcove.com/playback-api-video-fields-reference#key_systems_object
563 if container == 'WVM' or source.get('key_systems') or ext == 'ism':
564 for f in fmts:
565 f['has_drm'] = True
566 formats.extend(fmts)
567
568 if not formats:
569 errors = json_data.get('errors')
570 if errors:
571 error = errors[0]
572 self.raise_no_formats(
573 error.get('message') or error.get('error_subcode') or error['error_code'], expected=True)
574
44369c9a 575 headers.pop('Authorization', None) # or else http formats will give error 400
f5a9e9df 576 for f in formats:
577 f.setdefault('http_headers', {}).update(headers)
578
579 for text_track in json_data.get('text_tracks', []):
580 if text_track.get('kind') != 'captions':
581 continue
582 text_track_url = url_or_none(text_track.get('src'))
583 if not text_track_url:
584 continue
585 lang = (str_or_none(text_track.get('srclang'))
586 or str_or_none(text_track.get('label')) or 'en').lower()
587 subtitles.setdefault(lang, []).append({
588 'url': text_track_url,
589 })
590
591 is_live = False
592 duration = float_or_none(json_data.get('duration'), 1000)
593 if duration is not None and duration <= 0:
594 is_live = True
595
596 common_res = [(160, 90), (320, 180), (480, 720), (640, 360), (768, 432), (1024, 576), (1280, 720), (1366, 768), (1920, 1080)]
597 thumb_base_url = dict_get(json_data, ('poster', 'thumbnail'))
598 thumbnails = [{
599 'url': re.sub(r'\d+x\d+', f'{w}x{h}', thumb_base_url),
600 'width': w,
601 'height': h,
602 } for w, h in common_res] if thumb_base_url else None
603
604 return {
605 'id': video_id,
606 'title': title,
607 'description': clean_html(json_data.get('description')),
608 'thumbnails': thumbnails,
609 'duration': duration,
610 'timestamp': parse_iso8601(json_data.get('published_at')),
611 'uploader_id': json_data.get('account_id'),
612 'formats': formats,
613 'subtitles': subtitles,
614 'tags': json_data.get('tags', []),
615 'is_live': is_live,
616 }
617
618
619class BrightcoveNewIE(BrightcoveNewBaseIE):
e721d857 620 IE_NAME = 'brightcove:new'
3031b7c4 621 _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 622 _TESTS = [{
ed126900 623 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
c01e1a96 624 'md5': 'c8100925723840d4b0d243f7025703be',
ed126900 625 'info_dict': {
626 'id': '4463358922001',
c01e1a96 627 'ext': 'mp4',
ed126900 628 'title': 'Meet the man behind Popcorn Time',
c01e1a96 629 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
cb33d389 630 'duration': 165.768,
c01e1a96 631 'timestamp': 1441391203,
632 'upload_date': '20150904',
c01e1a96 633 'uploader_id': '929656772001',
4b7dd170 634 'formats': 'mincount:20',
cb33d389 635 },
f5a9e9df 636 'skip': '404 Not Found',
cb33d389
S
637 }, {
638 # with rtmp streams
639 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
640 'info_dict': {
641 'id': '4279049078001',
642 'ext': 'mp4',
643 'title': 'Titansgrave: Chapter 0',
644 'description': 'Titansgrave: Chapter 0',
645 'duration': 1242.058,
646 'timestamp': 1433556729,
647 'upload_date': '20150606',
648 'uploader_id': '4036320279001',
4b7dd170 649 'formats': 'mincount:39',
cb33d389
S
650 },
651 'params': {
08136dc1 652 # m3u8 download
cb33d389 653 'skip_download': True,
add96eb9 654 },
3031b7c4
K
655 }, {
656 # playlist stream
657 'url': 'https://players.brightcove.net/1752604059001/S13cJdUBz_default/index.html?playlistId=5718313430001',
658 'info_dict': {
659 'id': '5718313430001',
660 'title': 'No Audio Playlist',
661 },
662 'playlist_count': 7,
663 'params': {
664 # m3u8 download
665 'skip_download': True,
add96eb9 666 },
3031b7c4
K
667 }, {
668 'url': 'http://players.brightcove.net/5690807595001/HyZNerRl7_default/index.html?playlistId=5743160747001',
669 'only_matching': True,
4f29fa99
S
670 }, {
671 # ref: prefixed video id
672 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
673 'only_matching': True,
8ac73bdb 674 }, {
675 # non numeric ref: prefixed video id
676 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
677 'only_matching': True,
b219f5e5
S
678 }, {
679 # unavailable video without message but with error_code
680 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001',
681 'only_matching': True,
cb33d389 682 }]
ed126900 683
f5a9e9df 684 _WEBPAGE_TESTS = [{
685 # brightcove player url embed
686 'url': 'https://nbc-2.com/weather/forecast/2022/11/16/forecast-warmest-day-of-the-week/',
687 'md5': '2934d5372b354d27083ccf8575dbfee2',
688 'info_dict': {
689 'id': '6315650313112',
690 'title': 'First Alert Forecast: November 15, 2022',
691 'ext': 'mp4',
692 'tags': ['nbc2', 'forecast'],
693 'uploader_id': '6146886170001',
694 'thumbnail': r're:^https?://.*\.jpg$',
695 'timestamp': 1668574571,
696 'duration': 233.375,
697 'upload_date': '20221116',
698 },
699 }, {
700 # embedded with video tag only
701 'url': 'https://www.gooddishtv.com/tiktok-rapping-chef-mr-pyrex',
702 'info_dict': {
703 'id': 'tiktok-rapping-chef-mr-pyrex',
704 'title': 'TikTok\'s Rapping Chef Makes Jambalaya for the Hosts',
705 'thumbnail': r're:^https?://.*\.jpg$',
706 'age_limit': 0,
707 'description': 'Just in time for Mardi Gras',
708 },
709 'playlist': [{
710 'info_dict': {
711 'id': '6299189544001',
712 'ext': 'mp4',
713 'title': 'TGD_01-032_5',
714 'thumbnail': r're:^https?://.*\.jpg$',
715 'tags': [],
716 'timestamp': 1646078943,
717 'uploader_id': '1569565978001',
718 'upload_date': '20220228',
719 'duration': 217.195,
720 },
721 }, {
722 'info_dict': {
723 'id': '6305565995112',
724 'ext': 'mp4',
725 'title': 'TGD 01-087 (Airs 05.25.22)_Segment 5',
726 'thumbnail': r're:^https?://.*\.jpg$',
727 'tags': [],
728 'timestamp': 1651604591,
729 'uploader_id': '1569565978001',
730 'upload_date': '20220503',
731 'duration': 310.421,
732 },
733 }],
734 }, {
735 # Brightcove:new type [2].
736 'url': 'http://www.delawaresportszone.com/video-st-thomas-more-earns-first-trip-to-basketball-semis',
737 'md5': '2b35148fcf48da41c9fb4591650784f3',
738 'info_dict': {
739 'id': '5348741021001',
740 'ext': 'mp4',
741 'upload_date': '20170306',
742 'uploader_id': '4191638492001',
743 'timestamp': 1488769918,
744 'title': 'VIDEO: St. Thomas More earns first trip to basketball semis',
745 },
746 'skip': '404 Not Found',
747 }, {
748 # Alternative brightcove <video> attributes
749 'url': 'http://www.programme-tv.net/videos/extraits/81095-guillaume-canet-evoque-les-rumeurs-d-infidelite-de-marion-cotillard-avec-brad-pitt-dans-vivement-dimanche/',
750 'info_dict': {
751 'id': '81095-guillaume-canet-evoque-les-rumeurs-d-infidelite-de-marion-cotillard-avec-brad-pitt-dans-vivement-dimanche',
752 'title': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche, Extraits : toutes les vidéos avec Télé-Loisirs",
753 },
754 'playlist': [{
755 'md5': '732d22ba3d33f2f3fc253c39f8f36523',
756 'info_dict': {
757 'id': '5311302538001',
758 'ext': 'mp4',
759 'title': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche",
760 'description': "Guillaume Canet évoque les rumeurs d'infidélité de Marion Cotillard avec Brad Pitt dans Vivement Dimanche (France 2, 5 février 2017)",
761 'timestamp': 1486321708,
762 'upload_date': '20170205',
763 'uploader_id': '800000640001',
764 },
765 'only_matching': True,
766 }],
767 'skip': '404 Not Found',
768 }, {
769 # Brightcove URL in single quotes
770 'url': 'http://www.sportsnet.ca/baseball/mlb/sn-presents-russell-martin-world-citizen/',
771 'md5': '4ae374f1f8b91c889c4b9203c8c752af',
772 'info_dict': {
773 'id': '4255764656001',
774 'ext': 'mp4',
775 'title': 'SN Presents: Russell Martin, World Citizen',
776 'description': 'To understand why he was the Toronto Blue Jays’ top off-season priority is to appreciate his background and upbringing in Montreal, where he first developed his baseball skills. Written and narrated by Stephen Brunt.',
777 'uploader': 'Rogers Sportsnet',
778 'uploader_id': '1704050871',
779 'upload_date': '20150525',
780 'timestamp': 1432570283,
781 },
782 'skip': 'Page no longer has URL, now has javascript',
783 }]
784
7234d1d9 785 @staticmethod
f631b557 786 def _extract_url(ie, webpage):
8f97a15d 787 urls = BrightcoveNewIE._extract_brightcove_urls(ie, webpage)
7234d1d9
S
788 return urls[0] if urls else None
789
24af8529 790 @staticmethod
8f97a15d 791 def _extract_brightcove_urls(ie, webpage):
536f819e
S
792 # Reference:
793 # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
40158f55
JH
794 # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#tag
795 # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
796 # 4. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/in-page-embed-player-implementation.html
797 # 5. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
536f819e
S
798
799 entries = []
800
801 # Look for iframe embeds [1]
802 for _, url in re.findall(
354dbbd8 803 r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
804 entries.append(url if url.startswith('http') else 'http:' + url)
d8a1caf0 805
40158f55
JH
806 # Look for <video> tags [2] and embed_in_page embeds [3]
807 # [2] looks like:
40158f55 808 for video, script_tag, account_id, player_id, embed in re.findall(
0254f93b 809 r'''(?isx)
2391941f 810 (<video(?:-js)?\s+[^>]*\bdata-video-id\s*=\s*['"]?[^>]+>)
0254f93b
S
811 (?:.*?
812 (<script[^>]+
813 src=["\'](?:https?:)?//players\.brightcove\.net/
814 (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
815 )
816 )?
817 ''', webpage):
40158f55
JH
818 attrs = extract_attributes(video)
819
820 # According to examples from [4] it's unclear whether video id
821 # may be optional and what to do when it is
822 video_id = attrs.get('data-video-id')
0254f93b
S
823 if not video_id:
824 continue
40158f55 825
0254f93b 826 account_id = account_id or attrs.get('data-account')
40158f55 827 if not account_id:
0254f93b
S
828 continue
829
830 player_id = player_id or attrs.get('data-player') or 'default'
831 embed = embed or attrs.get('data-embed') or 'default'
832
add96eb9 833 bc_url = f'http://players.brightcove.net/{account_id}/{player_id}_{embed}/index.html?videoId={video_id}'
0254f93b
S
834
835 # Some brightcove videos may be embedded with video tag only and
836 # without script tag or any mentioning of brightcove at all. Such
837 # embeds are considered ambiguous since they are matched based only
838 # on data-video-id and data-account attributes and in the wild may
839 # not be brightcove embeds at all. Let's check reconstructed
840 # brightcove URLs in case of such embeds and only process valid
841 # ones. By this we ensure there is indeed a brightcove embed.
842 if not script_tag and not ie._is_valid_url(
843 bc_url, video_id, 'possible brightcove video'):
844 continue
845
846 entries.append(bc_url)
d8a1caf0 847
536f819e 848 return entries
ed126900 849
f5a9e9df 850 def _extract_from_webpage(self, url, webpage):
851 bc_urls = self._extract_brightcove_urls(self, webpage)
852 for bc_url in bc_urls:
853 yield self.url_result(smuggle_url(bc_url, {'referrer': url}), BrightcoveNewIE)
4b7dd170
RA
854
855 def _real_extract(self, url):
856 url, smuggled_data = unsmuggle_url(url, {})
5f95927a
S
857 self._initialize_geo_bypass({
858 'countries': smuggled_data.get('geo_countries'),
859 'ip_blocks': smuggled_data.get('geo_ip_blocks'),
860 })
4b7dd170 861
5ad28e7f 862 account_id, player_id, embed, content_type, video_id = self._match_valid_url(url).groups()
4b7dd170 863
add96eb9 864 policy_key_id = f'{account_id}_{player_id}'
9809740b 865 policy_key = self.cache.load('brightcove', policy_key_id)
06068087 866 policy_key_extracted = False
9809740b 867 store_pk = lambda x: self.cache.store('brightcove', policy_key_id, x)
06068087
RA
868
869 def extract_policy_key():
add96eb9 870 base_url = f'http://players.brightcove.net/{account_id}/{player_id}_{embed}/'
29f7c58a 871 config = self._download_json(
872 base_url + 'config.json', video_id, fatal=False) or {}
873 policy_key = try_get(
874 config, lambda x: x['video_cloud']['policy_key'])
875 if not policy_key:
876 webpage = self._download_webpage(
877 base_url + 'index.min.js', video_id)
06068087 878
29f7c58a 879 catalog = self._search_regex(
880 r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
75ef77c1 881 if catalog:
29f7c58a 882 catalog = self._parse_json(
883 js_to_json(catalog), video_id, fatal=False)
884 if catalog:
885 policy_key = catalog.get('policyKey')
886
887 if not policy_key:
888 policy_key = self._search_regex(
889 r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
890 webpage, 'policy key', group='pk')
06068087 891
2d30b92e 892 store_pk(policy_key)
06068087 893 return policy_key
4b7dd170 894
44369c9a 895 token = smuggled_data.get('token')
896 api_url = f'https://{"edge-auth" if token else "edge"}.api.brightcove.com/playback/v1/accounts/{account_id}/{content_type}s/{video_id}'
897 headers = {'Authorization': f'Bearer {token}'} if token else {}
f5a9e9df 898 referrer = smuggled_data.get('referrer') # XXX: notice the spelling/case of the key
5399ab3f
S
899 if referrer:
900 headers.update({
901 'Referer': referrer,
902 'Origin': re.search(r'https?://[^/]+', referrer).group(0),
4b7dd170 903 })
06068087
RA
904
905 for _ in range(2):
906 if not policy_key:
907 policy_key = extract_policy_key()
908 policy_key_extracted = True
add96eb9 909 headers['Accept'] = f'application/json;pk={policy_key}'
06068087
RA
910 try:
911 json_data = self._download_json(api_url, video_id, headers=headers)
912 break
913 except ExtractorError as e:
3d2623a8 914 if isinstance(e.cause, HTTPError) and e.cause.status in (401, 403):
915 json_data = self._parse_json(e.cause.response.read().decode(), video_id)[0]
06068087
RA
916 message = json_data.get('message') or json_data['error_code']
917 if json_data.get('error_subcode') == 'CLIENT_GEO':
918 self.raise_geo_restricted(msg=message)
919 elif json_data.get('error_code') == 'INVALID_POLICY_KEY' and not policy_key_extracted:
920 policy_key = None
2d30b92e 921 store_pk(None)
06068087
RA
922 continue
923 raise ExtractorError(message, expected=True)
924 raise
4b7dd170
RA
925
926 errors = json_data.get('errors')
927 if errors and errors[0].get('error_subcode') == 'TVE_AUTH':
928 custom_fields = json_data['custom_fields']
929 tve_token = self._extract_mvpd_auth(
930 smuggled_data['source_url'], video_id,
931 custom_fields['bcadobepassrequestorid'],
932 custom_fields['bcadobepassresourceid'])
933 json_data = self._download_json(
934 api_url, video_id, headers={
add96eb9 935 'Accept': f'application/json;pk={policy_key}',
4b7dd170
RA
936 }, query={
937 'tveToken': tve_token,
938 })
939
3031b7c4
K
940 if content_type == 'playlist':
941 return self.playlist_result(
942 [self._parse_brightcove_metadata(vid, vid.get('id'), headers)
943 for vid in json_data.get('videos', []) if vid.get('id')],
944 json_data.get('id'), json_data.get('name'),
945 json_data.get('description'))
946
18d7aa6e
S
947 return self._parse_brightcove_metadata(
948 json_data, video_id, headers=headers)