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