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