[nbc] add support for stream.nbcsports.com(closes #13911)
[youtube-dl] / youtube_dl / 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 ..utils import (
11     find_xpath_attr,
12     smuggle_url,
13     try_get,
14     unescapeHTML,
15     update_url_query,
16     int_or_none,
17 )
18
19
20 class NBCIE(AdobePassIE):
21     _VALID_URL = r'https?(?P<permalink>://(?:www\.)?nbc\.com/(?:classic-tv/)?[^/]+/video/[^/]+/(?P<id>n?\d+))'
22
23     _TESTS = [
24         {
25             'url': 'http://www.nbc.com/the-tonight-show/video/jimmy-fallon-surprises-fans-at-ben-jerrys/2848237',
26             'info_dict': {
27                 'id': '2848237',
28                 'ext': 'mp4',
29                 'title': 'Jimmy Fallon Surprises Fans at Ben & Jerry\'s',
30                 'description': 'Jimmy gives out free scoops of his new "Tonight Dough" ice cream flavor by surprising customers at the Ben & Jerry\'s scoop shop.',
31                 'timestamp': 1424246400,
32                 'upload_date': '20150218',
33                 'uploader': 'NBCU-COM',
34             },
35             'params': {
36                 # m3u8 download
37                 'skip_download': True,
38             },
39         },
40         {
41             'url': 'http://www.nbc.com/saturday-night-live/video/star-wars-teaser/2832821',
42             'info_dict': {
43                 'id': '2832821',
44                 'ext': 'mp4',
45                 'title': 'Star Wars Teaser',
46                 'description': 'md5:0b40f9cbde5b671a7ff62fceccc4f442',
47                 'timestamp': 1417852800,
48                 'upload_date': '20141206',
49                 'uploader': 'NBCU-COM',
50             },
51             'params': {
52                 # m3u8 download
53                 'skip_download': True,
54             },
55             'skip': 'Only works from US',
56         },
57         {
58             # HLS streams requires the 'hdnea3' cookie
59             'url': 'http://www.nbc.com/Kings/video/goliath/n1806',
60             'info_dict': {
61                 'id': '101528f5a9e8127b107e98c5e6ce4638',
62                 'ext': 'mp4',
63                 'title': 'Goliath',
64                 '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.',
65                 'timestamp': 1237100400,
66                 'upload_date': '20090315',
67                 'uploader': 'NBCU-COM',
68             },
69             'params': {
70                 'skip_download': True,
71             },
72             'skip': 'Only works from US',
73         },
74         {
75             'url': 'https://www.nbc.com/classic-tv/charles-in-charge/video/charles-in-charge-pilot/n3310',
76             'only_matching': True,
77         },
78     ]
79
80     def _real_extract(self, url):
81         permalink, video_id = re.match(self._VALID_URL, url).groups()
82         permalink = 'http' + permalink
83         response = self._download_json(
84             'https://api.nbc.com/v3/videos', video_id, query={
85                 'filter[permalink]': permalink,
86                 'fields[videos]': 'description,entitlement,episodeNumber,guid,keywords,seasonNumber,title,vChipRating',
87                 'fields[shows]': 'shortTitle',
88                 'include': 'show.shortTitle',
89             })
90         video_data = response['data'][0]['attributes']
91         query = {
92             'mbr': 'true',
93             'manifest': 'm3u',
94         }
95         video_id = video_data['guid']
96         title = video_data['title']
97         if video_data.get('entitlement') == 'auth':
98             resource = self._get_mvpd_resource(
99                 'nbcentertainment', title, video_id,
100                 video_data.get('vChipRating'))
101             query['auth'] = self._extract_mvpd_auth(
102                 url, video_id, 'nbcentertainment', resource)
103         theplatform_url = smuggle_url(update_url_query(
104             'http://link.theplatform.com/s/NnzsPC/media/guid/2410887629/' + video_id,
105             query), {'force_smil_url': True})
106         return {
107             '_type': 'url_transparent',
108             'id': video_id,
109             'title': title,
110             'url': theplatform_url,
111             'description': video_data.get('description'),
112             'tags': video_data.get('keywords'),
113             'season_number': int_or_none(video_data.get('seasonNumber')),
114             'episode_number': int_or_none(video_data.get('episodeNumber')),
115             'episode': title,
116             'series': try_get(response, lambda x: x['included'][0]['attributes']['shortTitle']),
117             'ie_key': 'ThePlatform',
118         }
119
120
121 class NBCSportsVPlayerIE(InfoExtractor):
122     _VALID_URL = r'https?://vplayer\.nbcsports\.com/(?:[^/]+/)+(?P<id>[0-9a-zA-Z_]+)'
123
124     _TESTS = [{
125         'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_embed/select/9CsDKds0kvHI',
126         'info_dict': {
127             'id': '9CsDKds0kvHI',
128             'ext': 'mp4',
129             'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
130             'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
131             'timestamp': 1426270238,
132             'upload_date': '20150313',
133             'uploader': 'NBCU-SPORTS',
134         }
135     }, {
136         'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_embed/select/media/_hqLjQ95yx8Z',
137         'only_matching': True,
138     }]
139
140     @staticmethod
141     def _extract_url(webpage):
142         iframe_m = re.search(
143             r'<iframe[^>]+src="(?P<url>https?://vplayer\.nbcsports\.com/[^"]+)"', webpage)
144         if iframe_m:
145             return iframe_m.group('url')
146
147     def _real_extract(self, url):
148         video_id = self._match_id(url)
149         webpage = self._download_webpage(url, video_id)
150         theplatform_url = self._og_search_video_url(webpage).replace(
151             'vplayer.nbcsports.com', 'player.theplatform.com')
152         return self.url_result(theplatform_url, 'ThePlatform')
153
154
155 class NBCSportsIE(InfoExtractor):
156     # Does not include https because its certificate is invalid
157     _VALID_URL = r'https?://(?:www\.)?nbcsports\.com//?(?:[^/]+/)+(?P<id>[0-9a-z-]+)'
158
159     _TEST = {
160         'url': 'http://www.nbcsports.com//college-basketball/ncaab/tom-izzo-michigan-st-has-so-much-respect-duke',
161         'info_dict': {
162             'id': 'PHJSaFWbrTY9',
163             'ext': 'flv',
164             'title': 'Tom Izzo, Michigan St. has \'so much respect\' for Duke',
165             'description': 'md5:ecb459c9d59e0766ac9c7d5d0eda8113',
166             'uploader': 'NBCU-SPORTS',
167             'upload_date': '20150330',
168             'timestamp': 1427726529,
169         }
170     }
171
172     def _real_extract(self, url):
173         video_id = self._match_id(url)
174         webpage = self._download_webpage(url, video_id)
175         return self.url_result(
176             NBCSportsVPlayerIE._extract_url(webpage), 'NBCSportsVPlayer')
177
178
179 class NBCSportsStreamIE(AdobePassIE):
180     _VALID_URL = r'https?://stream\.nbcsports\.com/.+?\bpid=(?P<id>\d+)'
181     _TEST = {
182         'url': 'http://stream.nbcsports.com/nbcsn/generic?pid=206559',
183         'info_dict': {
184             'id': '206559',
185             'ext': 'mp4',
186             'title': 'Amgen Tour of California Women\'s Recap',
187             'description': 'md5:66520066b3b5281ada7698d0ea2aa894',
188         },
189         'params': {
190             # m3u8 download
191             'skip_download': True,
192         },
193         'skip': 'Requires Adobe Pass Authentication',
194     }
195
196     def _real_extract(self, url):
197         video_id = self._match_id(url)
198         live_source = self._download_json(
199             'http://stream.nbcsports.com/data/live_sources_%s.json' % video_id,
200             video_id)
201         video_source = live_source['videoSources'][0]
202         title = video_source['title']
203         source_url = None
204         for k in ('source', 'msl4source', 'iossource', 'hlsv4'):
205             sk = k + 'Url'
206             source_url = video_source.get(sk) or video_source.get(sk + 'Alt')
207             if source_url:
208                 break
209         else:
210             source_url = video_source['ottStreamUrl']
211         is_live = video_source.get('type') == 'live' or video_source.get('status') == 'Live'
212         resource = self._get_mvpd_resource('nbcsports', title, video_id, '')
213         token = self._extract_mvpd_auth(url, video_id, 'nbcsports', resource)
214         tokenized_url = self._download_json(
215             'https://token.playmakerservices.com/cdn',
216             video_id, data=json.dumps({
217                 'requestorId': 'nbcsports',
218                 'pid': video_id,
219                 'application': 'NBCSports',
220                 'version': 'v1',
221                 'platform': 'desktop',
222                 'cdn': 'akamai',
223                 'url': video_source['sourceUrl'],
224                 'token': base64.b64encode(token.encode()).decode(),
225                 'resourceId': base64.b64encode(resource.encode()).decode(),
226             }).encode())['tokenizedUrl']
227         formats = self._extract_m3u8_formats(tokenized_url, video_id, 'mp4')
228         self._sort_formats(formats)
229         return {
230             'id': video_id,
231             'title': self._live_title(title) if is_live else title,
232             'description': live_source.get('description'),
233             'formats': formats,
234             'is_live': is_live,
235         }
236
237
238 class CSNNEIE(InfoExtractor):
239     _VALID_URL = r'https?://(?:www\.)?csnne\.com/video/(?P<id>[0-9a-z-]+)'
240
241     _TEST = {
242         'url': 'http://www.csnne.com/video/snc-evening-update-wright-named-red-sox-no-5-starter',
243         'info_dict': {
244             'id': 'yvBLLUgQ8WU0',
245             'ext': 'mp4',
246             'title': 'SNC evening update: Wright named Red Sox\' No. 5 starter.',
247             'description': 'md5:1753cfee40d9352b19b4c9b3e589b9e3',
248             'timestamp': 1459369979,
249             'upload_date': '20160330',
250             'uploader': 'NBCU-SPORTS',
251         }
252     }
253
254     def _real_extract(self, url):
255         display_id = self._match_id(url)
256         webpage = self._download_webpage(url, display_id)
257         return {
258             '_type': 'url_transparent',
259             'ie_key': 'ThePlatform',
260             'url': self._html_search_meta('twitter:player:stream', webpage),
261             'display_id': display_id,
262         }
263
264
265 class NBCNewsIE(ThePlatformIE):
266     _VALID_URL = r'''(?x)https?://(?:www\.)?(?:nbcnews|today|msnbc)\.com/
267         (?:video/.+?/(?P<id>\d+)|
268         ([^/]+/)*(?:.*-)?(?P<mpx_id>[^/?]+))
269         '''
270
271     _TESTS = [
272         {
273             'url': 'http://www.nbcnews.com/video/nbc-news/52753292',
274             'md5': '47abaac93c6eaf9ad37ee6c4463a5179',
275             'info_dict': {
276                 'id': '52753292',
277                 'ext': 'flv',
278                 'title': 'Crew emerges after four-month Mars food study',
279                 'description': 'md5:24e632ffac72b35f8b67a12d1b6ddfc1',
280             },
281         },
282         {
283             'url': 'http://www.nbcnews.com/watch/nbcnews-com/how-twitter-reacted-to-the-snowden-interview-269389891880',
284             'md5': 'af1adfa51312291a017720403826bb64',
285             'info_dict': {
286                 'id': 'p_tweet_snow_140529',
287                 'ext': 'mp4',
288                 'title': 'How Twitter Reacted To The Snowden Interview',
289                 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
290                 'uploader': 'NBCU-NEWS',
291                 'timestamp': 1401363060,
292                 'upload_date': '20140529',
293             },
294         },
295         {
296             'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
297             'md5': 'fdbf39ab73a72df5896b6234ff98518a',
298             'info_dict': {
299                 'id': '529953347624',
300                 'ext': 'mp4',
301                 'title': 'FULL EPISODE: Family Business',
302                 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
303             },
304             'skip': 'This page is unavailable.',
305         },
306         {
307             'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
308             'md5': '73135a2e0ef819107bbb55a5a9b2a802',
309             'info_dict': {
310                 'id': 'nn_netcast_150204',
311                 'ext': 'mp4',
312                 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
313                 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
314                 'timestamp': 1423104900,
315                 'uploader': 'NBCU-NEWS',
316                 'upload_date': '20150205',
317             },
318         },
319         {
320             'url': 'http://www.nbcnews.com/business/autos/volkswagen-11-million-vehicles-could-have-suspect-software-emissions-scandal-n431456',
321             'md5': 'a49e173825e5fcd15c13fc297fced39d',
322             'info_dict': {
323                 'id': 'x_lon_vwhorn_150922',
324                 'ext': 'mp4',
325                 'title': 'Volkswagen U.S. Chief:\xa0 We Have Totally Screwed Up',
326                 'description': 'md5:c8be487b2d80ff0594c005add88d8351',
327                 'upload_date': '20150922',
328                 'timestamp': 1442917800,
329                 'uploader': 'NBCU-NEWS',
330             },
331         },
332         {
333             'url': 'http://www.today.com/video/see-the-aurora-borealis-from-space-in-stunning-new-nasa-video-669831235788',
334             'md5': '118d7ca3f0bea6534f119c68ef539f71',
335             'info_dict': {
336                 'id': 'tdy_al_space_160420',
337                 'ext': 'mp4',
338                 'title': 'See the aurora borealis from space in stunning new NASA video',
339                 'description': 'md5:74752b7358afb99939c5f8bb2d1d04b1',
340                 'upload_date': '20160420',
341                 'timestamp': 1461152093,
342                 'uploader': 'NBCU-NEWS',
343             },
344         },
345         {
346             'url': 'http://www.msnbc.com/all-in-with-chris-hayes/watch/the-chaotic-gop-immigration-vote-314487875924',
347             'md5': '6d236bf4f3dddc226633ce6e2c3f814d',
348             'info_dict': {
349                 'id': 'n_hayes_Aimm_140801_272214',
350                 'ext': 'mp4',
351                 'title': 'The chaotic GOP immigration vote',
352                 '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.',
353                 'thumbnail': r're:^https?://.*\.jpg$',
354                 'timestamp': 1406937606,
355                 'upload_date': '20140802',
356                 'uploader': 'NBCU-NEWS',
357             },
358         },
359         {
360             'url': 'http://www.nbcnews.com/watch/dateline/full-episode--deadly-betrayal-386250819952',
361             'only_matching': True,
362         },
363         {
364             # From http://www.vulture.com/2016/06/letterman-couldnt-care-less-about-late-night.html
365             'url': 'http://www.nbcnews.com/widget/video-embed/701714499682',
366             'only_matching': True,
367         },
368     ]
369
370     def _real_extract(self, url):
371         mobj = re.match(self._VALID_URL, url)
372         video_id = mobj.group('id')
373         if video_id is not None:
374             all_info = self._download_xml('http://www.nbcnews.com/id/%s/displaymode/1219' % video_id, video_id)
375             info = all_info.find('video')
376
377             return {
378                 'id': video_id,
379                 'title': info.find('headline').text,
380                 'ext': 'flv',
381                 'url': find_xpath_attr(info, 'media', 'type', 'flashVideo').text,
382                 'description': info.find('caption').text,
383                 'thumbnail': find_xpath_attr(info, 'media', 'type', 'thumbnail').text,
384             }
385         else:
386             # "feature" and "nightly-news" pages use theplatform.com
387             video_id = mobj.group('mpx_id')
388             webpage = self._download_webpage(url, video_id)
389
390             filter_param = 'byId'
391             bootstrap_json = self._search_regex(
392                 [r'(?m)(?:var\s+(?:bootstrapJson|playlistData)|NEWS\.videoObj)\s*=\s*({.+});?\s*$',
393                  r'videoObj\s*:\s*({.+})', r'data-video="([^"]+)"',
394                  r'jQuery\.extend\(Drupal\.settings\s*,\s*({.+?})\);'],
395                 webpage, 'bootstrap json', default=None)
396             if bootstrap_json:
397                 bootstrap = self._parse_json(
398                     bootstrap_json, video_id, transform_source=unescapeHTML)
399
400                 info = None
401                 if 'results' in bootstrap:
402                     info = bootstrap['results'][0]['video']
403                 elif 'video' in bootstrap:
404                     info = bootstrap['video']
405                 elif 'msnbcVideoInfo' in bootstrap:
406                     info = bootstrap['msnbcVideoInfo']['meta']
407                 elif 'msnbcThePlatform' in bootstrap:
408                     info = bootstrap['msnbcThePlatform']['videoPlayer']['video']
409                 else:
410                     info = bootstrap
411
412                 if 'guid' in info:
413                     video_id = info['guid']
414                     filter_param = 'byGuid'
415                 elif 'mpxId' in info:
416                     video_id = info['mpxId']
417
418             return {
419                 '_type': 'url_transparent',
420                 'id': video_id,
421                 # http://feed.theplatform.com/f/2E2eJC/nbcnews also works
422                 'url': update_url_query('http://feed.theplatform.com/f/2E2eJC/nnd_NBCNews', {filter_param: video_id}),
423                 'ie_key': 'ThePlatformFeed',
424             }
425
426
427 class NBCOlympicsIE(InfoExtractor):
428     IE_NAME = 'nbcolympics'
429     _VALID_URL = r'https?://www\.nbcolympics\.com/video/(?P<id>[a-z-]+)'
430
431     _TEST = {
432         # Geo-restricted to US
433         'url': 'http://www.nbcolympics.com/video/justin-roses-son-leo-was-tears-after-his-dad-won-gold',
434         'md5': '54fecf846d05429fbaa18af557ee523a',
435         'info_dict': {
436             'id': 'WjTBzDXx5AUq',
437             'display_id': 'justin-roses-son-leo-was-tears-after-his-dad-won-gold',
438             'ext': 'mp4',
439             'title': 'Rose\'s son Leo was in tears after his dad won gold',
440             'description': 'Olympic gold medalist Justin Rose gets emotional talking to the impact his win in men\'s golf has already had on his children.',
441             'timestamp': 1471274964,
442             'upload_date': '20160815',
443             'uploader': 'NBCU-SPORTS',
444         },
445     }
446
447     def _real_extract(self, url):
448         display_id = self._match_id(url)
449
450         webpage = self._download_webpage(url, display_id)
451
452         drupal_settings = self._parse_json(self._search_regex(
453             r'jQuery\.extend\(Drupal\.settings\s*,\s*({.+?})\);',
454             webpage, 'drupal settings'), display_id)
455
456         iframe_url = drupal_settings['vod']['iframe_url']
457         theplatform_url = iframe_url.replace(
458             'vplayer.nbcolympics.com', 'player.theplatform.com')
459
460         return {
461             '_type': 'url_transparent',
462             'url': theplatform_url,
463             'ie_key': ThePlatformIE.ie_key(),
464             'display_id': display_id,
465         }
466
467
468 class NBCOlympicsStreamIE(AdobePassIE):
469     IE_NAME = 'nbcolympics:stream'
470     _VALID_URL = r'https?://stream\.nbcolympics\.com/(?P<id>[0-9a-z-]+)'
471     _TEST = {
472         'url': 'http://stream.nbcolympics.com/2018-winter-olympics-nbcsn-evening-feb-8',
473         'info_dict': {
474             'id': '203493',
475             'ext': 'mp4',
476             'title': 're:Curling, Alpine, Luge [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
477         },
478         'params': {
479             # m3u8 download
480             'skip_download': True,
481         },
482     }
483     _DATA_URL_TEMPLATE = 'http://stream.nbcolympics.com/data/%s_%s.json'
484
485     def _real_extract(self, url):
486         display_id = self._match_id(url)
487         webpage = self._download_webpage(url, display_id)
488         pid = self._search_regex(r'pid\s*=\s*(\d+);', webpage, 'pid')
489         resource = self._search_regex(
490             r"resource\s*=\s*'(.+)';", webpage,
491             'resource').replace("' + pid + '", pid)
492         event_config = self._download_json(
493             self._DATA_URL_TEMPLATE % ('event_config', pid),
494             pid)['eventConfig']
495         title = self._live_title(event_config['eventTitle'])
496         source_url = self._download_json(
497             self._DATA_URL_TEMPLATE % ('live_sources', pid),
498             pid)['videoSources'][0]['sourceUrl']
499         media_token = self._extract_mvpd_auth(
500             url, pid, event_config.get('requestorId', 'NBCOlympics'), resource)
501         formats = self._extract_m3u8_formats(self._download_webpage(
502             'http://sp.auth.adobe.com/tvs/v1/sign', pid, query={
503                 'cdn': 'akamai',
504                 'mediaToken': base64.b64encode(media_token.encode()),
505                 'resource': base64.b64encode(resource.encode()),
506                 'url': source_url,
507             }), pid, 'mp4')
508         self._sort_formats(formats)
509
510         return {
511             'id': pid,
512             'display_id': display_id,
513             'title': title,
514             'formats': formats,
515             'is_live': True,
516         }