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