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