]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/nbc.py
365c2e60d58fe2b583b8922071e2751f4d2a5427
[yt-dlp.git] / yt_dlp / extractor / nbc.py
1 import base64
2 import json
3 import re
4
5 from .common import InfoExtractor
6 from .theplatform import ThePlatformIE
7 from .adobepass import AdobePassIE
8 from ..compat import compat_urllib_parse_unquote
9 from ..utils import (
10 int_or_none,
11 parse_age_limit,
12 parse_duration,
13 RegexNotFoundError,
14 smuggle_url,
15 try_get,
16 unified_timestamp,
17 update_url_query,
18 )
19
20
21 class NBCIE(ThePlatformIE):
22 _VALID_URL = r'https?(?P<permalink>://(?:www\.)?nbc\.com/(?:classic-tv/)?[^/]+/video/[^/]+/(?P<id>n?\d+))'
23
24 _TESTS = [
25 {
26 'url': 'http://www.nbc.com/the-tonight-show/video/jimmy-fallon-surprises-fans-at-ben-jerrys/2848237',
27 'info_dict': {
28 'id': '2848237',
29 'ext': 'mp4',
30 'title': 'Jimmy Fallon Surprises Fans at Ben & Jerry\'s',
31 'description': 'Jimmy gives out free scoops of his new "Tonight Dough" ice cream flavor by surprising customers at the Ben & Jerry\'s scoop shop.',
32 'timestamp': 1424246400,
33 'upload_date': '20150218',
34 'uploader': 'NBCU-COM',
35 },
36 'params': {
37 # m3u8 download
38 'skip_download': True,
39 },
40 },
41 {
42 'url': 'http://www.nbc.com/saturday-night-live/video/star-wars-teaser/2832821',
43 'info_dict': {
44 'id': '2832821',
45 'ext': 'mp4',
46 'title': 'Star Wars Teaser',
47 'description': 'md5:0b40f9cbde5b671a7ff62fceccc4f442',
48 'timestamp': 1417852800,
49 'upload_date': '20141206',
50 'uploader': 'NBCU-COM',
51 },
52 'params': {
53 # m3u8 download
54 'skip_download': True,
55 },
56 'skip': 'Only works from US',
57 },
58 {
59 # HLS streams requires the 'hdnea3' cookie
60 'url': 'http://www.nbc.com/Kings/video/goliath/n1806',
61 'info_dict': {
62 'id': '101528f5a9e8127b107e98c5e6ce4638',
63 'ext': 'mp4',
64 'title': 'Goliath',
65 'description': 'When an unknown soldier saves the life of the King\'s son in battle, he\'s thrust into the limelight and politics of the kingdom.',
66 'timestamp': 1237100400,
67 'upload_date': '20090315',
68 'uploader': 'NBCU-COM',
69 },
70 'params': {
71 'skip_download': True,
72 },
73 'skip': 'Only works from US',
74 },
75 {
76 'url': 'https://www.nbc.com/classic-tv/charles-in-charge/video/charles-in-charge-pilot/n3310',
77 'only_matching': True,
78 },
79 {
80 # Percent escaped url
81 'url': 'https://www.nbc.com/up-all-night/video/day-after-valentine%27s-day/n2189',
82 'only_matching': True,
83 }
84 ]
85
86 def _real_extract(self, url):
87 permalink, video_id = self._match_valid_url(url).groups()
88 permalink = 'http' + compat_urllib_parse_unquote(permalink)
89 video_data = self._download_json(
90 'https://friendship.nbc.co/v2/graphql', video_id, query={
91 'query': '''query bonanzaPage(
92 $app: NBCUBrands! = nbc
93 $name: String!
94 $oneApp: Boolean
95 $platform: SupportedPlatforms! = web
96 $type: EntityPageType! = VIDEO
97 $userId: String!
98 ) {
99 bonanzaPage(
100 app: $app
101 name: $name
102 oneApp: $oneApp
103 platform: $platform
104 type: $type
105 userId: $userId
106 ) {
107 metadata {
108 ... on VideoPageData {
109 description
110 episodeNumber
111 keywords
112 locked
113 mpxAccountId
114 mpxGuid
115 rating
116 resourceId
117 seasonNumber
118 secondaryTitle
119 seriesShortTitle
120 }
121 }
122 }
123 }''',
124 'variables': json.dumps({
125 'name': permalink,
126 'oneApp': True,
127 'userId': '0',
128 }),
129 })['data']['bonanzaPage']['metadata']
130 query = {
131 'mbr': 'true',
132 'manifest': 'm3u',
133 }
134 video_id = video_data['mpxGuid']
135 tp_path = 'NnzsPC/media/guid/%s/%s' % (video_data.get('mpxAccountId') or '2410887629', video_id)
136 tpm = self._download_theplatform_metadata(tp_path, video_id)
137 title = tpm.get('title') or video_data.get('secondaryTitle')
138 if video_data.get('locked'):
139 resource = self._get_mvpd_resource(
140 video_data.get('resourceId') or 'nbcentertainment',
141 title, video_id, video_data.get('rating'))
142 query['auth'] = self._extract_mvpd_auth(
143 url, video_id, 'nbcentertainment', resource)
144 theplatform_url = smuggle_url(update_url_query(
145 'http://link.theplatform.com/s/NnzsPC/media/guid/%s/%s' % (video_data.get('mpxAccountId') or '2410887629', video_id),
146 query), {'force_smil_url': True})
147
148 # Empty string or 0 can be valid values for these. So the check must be `is None`
149 description = video_data.get('description')
150 if description is None:
151 description = tpm.get('description')
152 episode_number = int_or_none(video_data.get('episodeNumber'))
153 if episode_number is None:
154 episode_number = int_or_none(tpm.get('nbcu$airOrder'))
155 rating = video_data.get('rating')
156 if rating is None:
157 try_get(tpm, lambda x: x['ratings'][0]['rating'])
158 season_number = int_or_none(video_data.get('seasonNumber'))
159 if season_number is None:
160 season_number = int_or_none(tpm.get('nbcu$seasonNumber'))
161 series = video_data.get('seriesShortTitle')
162 if series is None:
163 series = tpm.get('nbcu$seriesShortTitle')
164 tags = video_data.get('keywords')
165 if tags is None or len(tags) == 0:
166 tags = tpm.get('keywords')
167
168 return {
169 '_type': 'url_transparent',
170 'age_limit': parse_age_limit(rating),
171 'description': description,
172 'episode': title,
173 'episode_number': episode_number,
174 'id': video_id,
175 'ie_key': 'ThePlatform',
176 'season_number': season_number,
177 'series': series,
178 'tags': tags,
179 'title': title,
180 'url': theplatform_url,
181 }
182
183
184 class NBCSportsVPlayerIE(InfoExtractor):
185 _VALID_URL_BASE = r'https?://(?:vplayer\.nbcsports\.com|(?:www\.)?nbcsports\.com/vplayer)/'
186 _VALID_URL = _VALID_URL_BASE + r'(?:[^/]+/)+(?P<id>[0-9a-zA-Z_]+)'
187
188 _TESTS = [{
189 'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_embed/select/9CsDKds0kvHI',
190 'info_dict': {
191 'id': '9CsDKds0kvHI',
192 'ext': 'mp4',
193 'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
194 'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
195 'timestamp': 1426270238,
196 'upload_date': '20150313',
197 'uploader': 'NBCU-SPORTS',
198 'duration': 72.818,
199 'chapters': [],
200 'thumbnail': r're:^https?://.*\.jpg$'
201 }
202 }, {
203 'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_embed/select/media/PEgOtlNcC_y2',
204 'only_matching': True,
205 }, {
206 'url': 'https://www.nbcsports.com/vplayer/p/BxmELC/nbcsports/select/PHJSaFWbrTY9?form=html&autoPlay=true',
207 'only_matching': True,
208 }]
209
210 @staticmethod
211 def _extract_url(webpage):
212 video_urls = re.search(
213 r'(?:iframe[^>]+|var video|div[^>]+data-(?:mpx-)?)[sS]rc\s?=\s?"(?P<url>%s[^\"]+)' % NBCSportsVPlayerIE._VALID_URL_BASE, webpage)
214 if video_urls:
215 return video_urls.group('url')
216
217 def _real_extract(self, url):
218 video_id = self._match_id(url)
219 webpage = self._download_webpage(url, video_id)
220 theplatform_url = self._html_search_regex(r'tp:releaseUrl="(.+?)"', webpage, 'url')
221 return self.url_result(theplatform_url, 'ThePlatform')
222
223
224 class NBCSportsIE(InfoExtractor):
225 _VALID_URL = r'https?://(?:www\.)?nbcsports\.com//?(?!vplayer/)(?:[^/]+/)+(?P<id>[0-9a-z-]+)'
226
227 _TESTS = [{
228 # iframe src
229 'url': 'http://www.nbcsports.com//college-basketball/ncaab/tom-izzo-michigan-st-has-so-much-respect-duke',
230 'info_dict': {
231 'id': 'PHJSaFWbrTY9',
232 'ext': 'mp4',
233 'title': 'Tom Izzo, Michigan St. has \'so much respect\' for Duke',
234 'description': 'md5:ecb459c9d59e0766ac9c7d5d0eda8113',
235 'uploader': 'NBCU-SPORTS',
236 'upload_date': '20150330',
237 'timestamp': 1427726529,
238 'chapters': [],
239 'thumbnail': 'https://hdliveextra-a.akamaihd.net/HD/image_sports/NBCU_Sports_Group_-_nbcsports/253/303/izzodps.jpg',
240 'duration': 528.395,
241 }
242 }, {
243 # data-mpx-src
244 'url': 'https://www.nbcsports.com/philadelphia/philadelphia-phillies/bruce-bochy-hector-neris-hes-idiot',
245 'only_matching': True,
246 }, {
247 # data-src
248 'url': 'https://www.nbcsports.com/boston/video/report-card-pats-secondary-no-match-josh-allen',
249 'only_matching': True,
250 }]
251
252 def _real_extract(self, url):
253 video_id = self._match_id(url)
254 webpage = self._download_webpage(url, video_id)
255 return self.url_result(
256 NBCSportsVPlayerIE._extract_url(webpage), 'NBCSportsVPlayer')
257
258
259 class NBCSportsStreamIE(AdobePassIE):
260 _VALID_URL = r'https?://stream\.nbcsports\.com/.+?\bpid=(?P<id>\d+)'
261 _TEST = {
262 'url': 'http://stream.nbcsports.com/nbcsn/generic?pid=206559',
263 'info_dict': {
264 'id': '206559',
265 'ext': 'mp4',
266 'title': 'Amgen Tour of California Women\'s Recap',
267 'description': 'md5:66520066b3b5281ada7698d0ea2aa894',
268 },
269 'params': {
270 # m3u8 download
271 'skip_download': True,
272 },
273 'skip': 'Requires Adobe Pass Authentication',
274 }
275
276 def _real_extract(self, url):
277 video_id = self._match_id(url)
278 live_source = self._download_json(
279 'http://stream.nbcsports.com/data/live_sources_%s.json' % video_id,
280 video_id)
281 video_source = live_source['videoSources'][0]
282 title = video_source['title']
283 source_url = None
284 for k in ('source', 'msl4source', 'iossource', 'hlsv4'):
285 sk = k + 'Url'
286 source_url = video_source.get(sk) or video_source.get(sk + 'Alt')
287 if source_url:
288 break
289 else:
290 source_url = video_source['ottStreamUrl']
291 is_live = video_source.get('type') == 'live' or video_source.get('status') == 'Live'
292 resource = self._get_mvpd_resource('nbcsports', title, video_id, '')
293 token = self._extract_mvpd_auth(url, video_id, 'nbcsports', resource)
294 tokenized_url = self._download_json(
295 'https://token.playmakerservices.com/cdn',
296 video_id, data=json.dumps({
297 'requestorId': 'nbcsports',
298 'pid': video_id,
299 'application': 'NBCSports',
300 'version': 'v1',
301 'platform': 'desktop',
302 'cdn': 'akamai',
303 'url': video_source['sourceUrl'],
304 'token': base64.b64encode(token.encode()).decode(),
305 'resourceId': base64.b64encode(resource.encode()).decode(),
306 }).encode())['tokenizedUrl']
307 formats = self._extract_m3u8_formats(tokenized_url, video_id, 'mp4')
308 self._sort_formats(formats)
309 return {
310 'id': video_id,
311 'title': title,
312 'description': live_source.get('description'),
313 'formats': formats,
314 'is_live': is_live,
315 }
316
317
318 class NBCNewsIE(ThePlatformIE):
319 _VALID_URL = r'(?x)https?://(?:www\.)?(?:nbcnews|today|msnbc)\.com/([^/]+/)*(?:.*-)?(?P<id>[^/?]+)'
320
321 _TESTS = [
322 {
323 'url': 'http://www.nbcnews.com/watch/nbcnews-com/how-twitter-reacted-to-the-snowden-interview-269389891880',
324 'md5': 'cf4bc9e6ce0130f00f545d80ecedd4bf',
325 'info_dict': {
326 'id': '269389891880',
327 'ext': 'mp4',
328 'title': 'How Twitter Reacted To The Snowden Interview',
329 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
330 'timestamp': 1401363060,
331 'upload_date': '20140529',
332 },
333 },
334 {
335 'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
336 'md5': 'fdbf39ab73a72df5896b6234ff98518a',
337 'info_dict': {
338 'id': '529953347624',
339 'ext': 'mp4',
340 'title': 'FULL EPISODE: Family Business',
341 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
342 },
343 'skip': 'This page is unavailable.',
344 },
345 {
346 'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
347 'md5': '8eb831eca25bfa7d25ddd83e85946548',
348 'info_dict': {
349 'id': '394064451844',
350 'ext': 'mp4',
351 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
352 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
353 'timestamp': 1423104900,
354 'upload_date': '20150205',
355 },
356 },
357 {
358 'url': 'http://www.nbcnews.com/business/autos/volkswagen-11-million-vehicles-could-have-suspect-software-emissions-scandal-n431456',
359 'md5': '4a8c4cec9e1ded51060bdda36ff0a5c0',
360 'info_dict': {
361 'id': 'n431456',
362 'ext': 'mp4',
363 'title': "Volkswagen U.S. Chief: We 'Totally Screwed Up'",
364 'description': 'md5:d22d1281a24f22ea0880741bb4dd6301',
365 'upload_date': '20150922',
366 'timestamp': 1442917800,
367 },
368 },
369 {
370 'url': 'http://www.today.com/video/see-the-aurora-borealis-from-space-in-stunning-new-nasa-video-669831235788',
371 'md5': '118d7ca3f0bea6534f119c68ef539f71',
372 'info_dict': {
373 'id': '669831235788',
374 'ext': 'mp4',
375 'title': 'See the aurora borealis from space in stunning new NASA video',
376 'description': 'md5:74752b7358afb99939c5f8bb2d1d04b1',
377 'upload_date': '20160420',
378 'timestamp': 1461152093,
379 },
380 },
381 {
382 'url': 'http://www.msnbc.com/all-in-with-chris-hayes/watch/the-chaotic-gop-immigration-vote-314487875924',
383 'md5': '6d236bf4f3dddc226633ce6e2c3f814d',
384 'info_dict': {
385 'id': '314487875924',
386 'ext': 'mp4',
387 'title': 'The chaotic GOP immigration vote',
388 'description': 'The Republican House votes on a border bill that has no chance of getting through the Senate or signed by the President and is drawing criticism from all sides.',
389 'thumbnail': r're:^https?://.*\.jpg$',
390 'timestamp': 1406937606,
391 'upload_date': '20140802',
392 },
393 },
394 {
395 'url': 'http://www.nbcnews.com/watch/dateline/full-episode--deadly-betrayal-386250819952',
396 'only_matching': True,
397 },
398 {
399 # From http://www.vulture.com/2016/06/letterman-couldnt-care-less-about-late-night.html
400 'url': 'http://www.nbcnews.com/widget/video-embed/701714499682',
401 'only_matching': True,
402 },
403 ]
404
405 def _real_extract(self, url):
406 video_id = self._match_id(url)
407 webpage = self._download_webpage(url, video_id)
408
409 data = self._search_nextjs_data(webpage, video_id)['props']['initialState']
410 video_data = try_get(data, lambda x: x['video']['current'], dict)
411 if not video_data:
412 video_data = data['article']['content'][0]['primaryMedia']['video']
413 title = video_data['headline']['primary']
414
415 formats = []
416 for va in video_data.get('videoAssets', []):
417 public_url = va.get('publicUrl')
418 if not public_url:
419 continue
420 if '://link.theplatform.com/' in public_url:
421 public_url = update_url_query(public_url, {'format': 'redirect'})
422 format_id = va.get('format')
423 if format_id == 'M3U':
424 formats.extend(self._extract_m3u8_formats(
425 public_url, video_id, 'mp4', 'm3u8_native',
426 m3u8_id=format_id, fatal=False))
427 continue
428 tbr = int_or_none(va.get('bitrate'), 1000)
429 if tbr:
430 format_id += '-%d' % tbr
431 formats.append({
432 'format_id': format_id,
433 'url': public_url,
434 'width': int_or_none(va.get('width')),
435 'height': int_or_none(va.get('height')),
436 'tbr': tbr,
437 'ext': 'mp4',
438 })
439 self._sort_formats(formats)
440
441 subtitles = {}
442 closed_captioning = video_data.get('closedCaptioning')
443 if closed_captioning:
444 for cc_url in closed_captioning.values():
445 if not cc_url:
446 continue
447 subtitles.setdefault('en', []).append({
448 'url': cc_url,
449 })
450
451 return {
452 'id': video_id,
453 'title': title,
454 'description': try_get(video_data, lambda x: x['description']['primary']),
455 'thumbnail': try_get(video_data, lambda x: x['primaryImage']['url']['primary']),
456 'duration': parse_duration(video_data.get('duration')),
457 'timestamp': unified_timestamp(video_data.get('datePublished')),
458 'formats': formats,
459 'subtitles': subtitles,
460 }
461
462
463 class NBCOlympicsIE(InfoExtractor):
464 IE_NAME = 'nbcolympics'
465 _VALID_URL = r'https?://www\.nbcolympics\.com/videos?/(?P<id>[0-9a-z-]+)'
466
467 _TEST = {
468 # Geo-restricted to US
469 'url': 'http://www.nbcolympics.com/video/justin-roses-son-leo-was-tears-after-his-dad-won-gold',
470 'md5': '54fecf846d05429fbaa18af557ee523a',
471 'info_dict': {
472 'id': 'WjTBzDXx5AUq',
473 'display_id': 'justin-roses-son-leo-was-tears-after-his-dad-won-gold',
474 'ext': 'mp4',
475 'title': 'Rose\'s son Leo was in tears after his dad won gold',
476 'description': 'Olympic gold medalist Justin Rose gets emotional talking to the impact his win in men\'s golf has already had on his children.',
477 'timestamp': 1471274964,
478 'upload_date': '20160815',
479 'uploader': 'NBCU-SPORTS',
480 },
481 }
482
483 def _real_extract(self, url):
484 display_id = self._match_id(url)
485
486 webpage = self._download_webpage(url, display_id)
487
488 try:
489 drupal_settings = self._parse_json(self._search_regex(
490 r'jQuery\.extend\(Drupal\.settings\s*,\s*({.+?})\);',
491 webpage, 'drupal settings'), display_id)
492
493 iframe_url = drupal_settings['vod']['iframe_url']
494 theplatform_url = iframe_url.replace(
495 'vplayer.nbcolympics.com', 'player.theplatform.com')
496 except RegexNotFoundError:
497 theplatform_url = self._search_regex(
498 r"([\"'])embedUrl\1: *([\"'])(?P<embedUrl>.+)\2",
499 webpage, 'embedding URL', group="embedUrl")
500
501 return {
502 '_type': 'url_transparent',
503 'url': theplatform_url,
504 'ie_key': ThePlatformIE.ie_key(),
505 'display_id': display_id,
506 }
507
508
509 class NBCOlympicsStreamIE(AdobePassIE):
510 IE_NAME = 'nbcolympics:stream'
511 _VALID_URL = r'https?://stream\.nbcolympics\.com/(?P<id>[0-9a-z-]+)'
512 _TESTS = [
513 {
514 'note': 'Tokenized m3u8 source URL',
515 'url': 'https://stream.nbcolympics.com/womens-soccer-group-round-11',
516 'info_dict': {
517 'id': '2019740',
518 'ext': 'mp4',
519 'title': r"re:Women's Group Stage - Netherlands vs\. Brazil [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$",
520 },
521 'params': {
522 'skip_download': 'm3u8',
523 },
524 }, {
525 'note': 'Plain m3u8 source URL',
526 'url': 'https://stream.nbcolympics.com/gymnastics-event-finals-mens-floor-pommel-horse-womens-vault-bars',
527 'info_dict': {
528 'id': '2021729',
529 'ext': 'mp4',
530 'title': r're:Event Finals: M Floor, W Vault, M Pommel, W Uneven Bars [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
531 },
532 'params': {
533 'skip_download': 'm3u8',
534 },
535 },
536 ]
537
538 def _real_extract(self, url):
539 display_id = self._match_id(url)
540 webpage = self._download_webpage(url, display_id)
541 pid = self._search_regex(r'pid\s*=\s*(\d+);', webpage, 'pid')
542
543 event_config = self._download_json(
544 f'http://stream.nbcolympics.com/data/event_config_{pid}.json',
545 pid, 'Downloading event config')['eventConfig']
546
547 title = event_config['eventTitle']
548 is_live = {'live': True, 'replay': False}.get(event_config.get('eventStatus'))
549
550 source_url = self._download_json(
551 f'https://api-leap.nbcsports.com/feeds/assets/{pid}?application=NBCOlympics&platform=desktop&format=nbc-player&env=staging',
552 pid, 'Downloading leap config'
553 )['videoSources'][0]['cdnSources']['primary'][0]['sourceUrl']
554
555 if event_config.get('cdnToken'):
556 ap_resource = self._get_mvpd_resource(
557 event_config.get('resourceId', 'NBCOlympics'),
558 re.sub(r'[^\w\d ]+', '', event_config['eventTitle']), pid,
559 event_config.get('ratingId', 'NO VALUE'))
560 media_token = self._extract_mvpd_auth(url, pid, event_config.get('requestorId', 'NBCOlympics'), ap_resource)
561
562 source_url = self._download_json(
563 'https://tokens.playmakerservices.com/', pid, 'Retrieving tokenized URL',
564 data=json.dumps({
565 'application': 'NBCSports',
566 'authentication-type': 'adobe-pass',
567 'cdn': 'akamai',
568 'pid': pid,
569 'platform': 'desktop',
570 'requestorId': 'NBCOlympics',
571 'resourceId': base64.b64encode(ap_resource.encode()).decode(),
572 'token': base64.b64encode(media_token.encode()).decode(),
573 'url': source_url,
574 'version': 'v1',
575 }).encode(),
576 )['akamai'][0]['tokenizedUrl']
577
578 formats = self._extract_m3u8_formats(source_url, pid, 'mp4', live=is_live)
579 for f in formats:
580 # -http_seekable requires ffmpeg 4.3+ but it doesnt seem possible to
581 # download with ffmpeg without this option
582 f['downloader_options'] = {'ffmpeg_args': ['-seekable', '0', '-http_seekable', '0', '-icy', '0']}
583 self._sort_formats(formats)
584
585 return {
586 'id': pid,
587 'display_id': display_id,
588 'title': title,
589 'formats': formats,
590 'is_live': is_live,
591 }