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