[nbcnews] Support embed widgets
[youtube-dl] / youtube_dl / extractor / nbc.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from .theplatform import ThePlatformIE
7 from ..utils import (
8     find_xpath_attr,
9     lowercase_escape,
10     smuggle_url,
11     unescapeHTML,
12     update_url_query,
13     int_or_none,
14     HEADRequest,
15     parse_iso8601,
16 )
17
18
19 class NBCIE(InfoExtractor):
20     _VALID_URL = r'https?://www\.nbc\.com/(?:[^/]+/)+(?P<id>n?\d+)'
21
22     _TESTS = [
23         {
24             'url': 'http://www.nbc.com/the-tonight-show/segments/112966',
25             'info_dict': {
26                 'id': '112966',
27                 'ext': 'mp4',
28                 'title': 'Jimmy Fallon Surprises Fans at Ben & Jerry\'s',
29                 'description': 'Jimmy gives out free scoops of his new "Tonight Dough" ice cream flavor by surprising customers at the Ben & Jerry\'s scoop shop.',
30                 'timestamp': 1424246400,
31                 'upload_date': '20150218',
32                 'uploader': 'NBCU-COM',
33             },
34             'params': {
35                 # m3u8 download
36                 'skip_download': True,
37             },
38         },
39         {
40             'url': 'http://www.nbc.com/the-tonight-show/episodes/176',
41             'info_dict': {
42                 'id': '176',
43                 'ext': 'flv',
44                 'title': 'Ricky Gervais, Steven Van Zandt, ILoveMakonnen',
45                 'description': 'A brand new episode of The Tonight Show welcomes Ricky Gervais, Steven Van Zandt and ILoveMakonnen.',
46             },
47             'skip': '404 Not Found',
48         },
49         {
50             'url': 'http://www.nbc.com/saturday-night-live/video/star-wars-teaser/2832821',
51             'info_dict': {
52                 'id': '2832821',
53                 'ext': 'mp4',
54                 'title': 'Star Wars Teaser',
55                 'description': 'md5:0b40f9cbde5b671a7ff62fceccc4f442',
56                 'timestamp': 1417852800,
57                 'upload_date': '20141206',
58                 'uploader': 'NBCU-COM',
59             },
60             'params': {
61                 # m3u8 download
62                 'skip_download': True,
63             },
64             'skip': 'Only works from US',
65         },
66         {
67             # This video has expired but with an escaped embedURL
68             'url': 'http://www.nbc.com/parenthood/episode-guide/season-5/just-like-at-home/515',
69             'only_matching': True,
70         },
71         {
72             # HLS streams requires the 'hdnea3' cookie
73             'url': 'http://www.nbc.com/Kings/video/goliath/n1806',
74             'info_dict': {
75                 'id': 'n1806',
76                 'ext': 'mp4',
77                 'title': 'Goliath',
78                 '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.',
79                 'timestamp': 1237100400,
80                 'upload_date': '20090315',
81                 'uploader': 'NBCU-COM',
82             },
83             'params': {
84                 'skip_download': True,
85             },
86             'skip': 'Only works from US',
87         }
88     ]
89
90     def _real_extract(self, url):
91         video_id = self._match_id(url)
92         webpage = self._download_webpage(url, video_id)
93         theplatform_url = unescapeHTML(lowercase_escape(self._html_search_regex(
94             [
95                 r'(?:class="video-player video-player-full" data-mpx-url|class="player" src)="(.*?)"',
96                 r'<iframe[^>]+src="((?:https?:)?//player\.theplatform\.com/[^"]+)"',
97                 r'"embedURL"\s*:\s*"([^"]+)"'
98             ],
99             webpage, 'theplatform url').replace('_no_endcard', '').replace('\\/', '/')))
100         if theplatform_url.startswith('//'):
101             theplatform_url = 'http:' + theplatform_url
102         return {
103             '_type': 'url_transparent',
104             'ie_key': 'ThePlatform',
105             'url': smuggle_url(theplatform_url, {'source_url': url}),
106             'id': video_id,
107         }
108
109
110 class NBCSportsVPlayerIE(InfoExtractor):
111     _VALID_URL = r'https?://vplayer\.nbcsports\.com/(?:[^/]+/)+(?P<id>[0-9a-zA-Z_]+)'
112
113     _TESTS = [{
114         'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_share/select/9CsDKds0kvHI',
115         'info_dict': {
116             'id': '9CsDKds0kvHI',
117             'ext': 'flv',
118             'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
119             'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
120             'timestamp': 1426270238,
121             'upload_date': '20150313',
122             'uploader': 'NBCU-SPORTS',
123         }
124     }, {
125         'url': 'http://vplayer.nbcsports.com/p/BxmELC/nbc_embedshare/select/_hqLjQ95yx8Z',
126         'only_matching': True,
127     }]
128
129     @staticmethod
130     def _extract_url(webpage):
131         iframe_m = re.search(
132             r'<iframe[^>]+src="(?P<url>https?://vplayer\.nbcsports\.com/[^"]+)"', webpage)
133         if iframe_m:
134             return iframe_m.group('url')
135
136     def _real_extract(self, url):
137         video_id = self._match_id(url)
138         webpage = self._download_webpage(url, video_id)
139         theplatform_url = self._og_search_video_url(webpage)
140         return self.url_result(theplatform_url, 'ThePlatform')
141
142
143 class NBCSportsIE(InfoExtractor):
144     # Does not include https because its certificate is invalid
145     _VALID_URL = r'https?://www\.nbcsports\.com//?(?:[^/]+/)+(?P<id>[0-9a-z-]+)'
146
147     _TEST = {
148         'url': 'http://www.nbcsports.com//college-basketball/ncaab/tom-izzo-michigan-st-has-so-much-respect-duke',
149         'info_dict': {
150             'id': 'PHJSaFWbrTY9',
151             'ext': 'flv',
152             'title': 'Tom Izzo, Michigan St. has \'so much respect\' for Duke',
153             'description': 'md5:ecb459c9d59e0766ac9c7d5d0eda8113',
154             'uploader': 'NBCU-SPORTS',
155             'upload_date': '20150330',
156             'timestamp': 1427726529,
157         }
158     }
159
160     def _real_extract(self, url):
161         video_id = self._match_id(url)
162         webpage = self._download_webpage(url, video_id)
163         return self.url_result(
164             NBCSportsVPlayerIE._extract_url(webpage), 'NBCSportsVPlayer')
165
166
167 class CSNNEIE(InfoExtractor):
168     _VALID_URL = r'https?://www\.csnne\.com/video/(?P<id>[0-9a-z-]+)'
169
170     _TEST = {
171         'url': 'http://www.csnne.com/video/snc-evening-update-wright-named-red-sox-no-5-starter',
172         'info_dict': {
173             'id': 'yvBLLUgQ8WU0',
174             'ext': 'mp4',
175             'title': 'SNC evening update: Wright named Red Sox\' No. 5 starter.',
176             'description': 'md5:1753cfee40d9352b19b4c9b3e589b9e3',
177             'timestamp': 1459369979,
178             'upload_date': '20160330',
179             'uploader': 'NBCU-SPORTS',
180         }
181     }
182
183     def _real_extract(self, url):
184         display_id = self._match_id(url)
185         webpage = self._download_webpage(url, display_id)
186         return {
187             '_type': 'url_transparent',
188             'ie_key': 'ThePlatform',
189             'url': self._html_search_meta('twitter:player:stream', webpage),
190             'display_id': display_id,
191         }
192
193
194 class NBCNewsIE(ThePlatformIE):
195     _VALID_URL = r'''(?x)https?://(?:www\.)?(?:nbcnews|today)\.com/
196         (?:video/.+?/(?P<id>\d+)|
197         ([^/]+/)*(?P<display_id>[^/?]+))
198         '''
199
200     _TESTS = [
201         {
202             'url': 'http://www.nbcnews.com/video/nbc-news/52753292',
203             'md5': '47abaac93c6eaf9ad37ee6c4463a5179',
204             'info_dict': {
205                 'id': '52753292',
206                 'ext': 'flv',
207                 'title': 'Crew emerges after four-month Mars food study',
208                 'description': 'md5:24e632ffac72b35f8b67a12d1b6ddfc1',
209             },
210         },
211         {
212             'url': 'http://www.nbcnews.com/watch/nbcnews-com/how-twitter-reacted-to-the-snowden-interview-269389891880',
213             'md5': 'af1adfa51312291a017720403826bb64',
214             'info_dict': {
215                 'id': '269389891880',
216                 'ext': 'mp4',
217                 'title': 'How Twitter Reacted To The Snowden Interview',
218                 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
219             },
220         },
221         {
222             'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
223             'md5': 'fdbf39ab73a72df5896b6234ff98518a',
224             'info_dict': {
225                 'id': 'Wjf9EDR3A_60',
226                 'ext': 'mp4',
227                 'title': 'FULL EPISODE: Family Business',
228                 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
229             },
230             'skip': 'This page is unavailable.',
231         },
232         {
233             'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
234             'md5': '73135a2e0ef819107bbb55a5a9b2a802',
235             'info_dict': {
236                 'id': '394064451844',
237                 'ext': 'mp4',
238                 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
239                 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
240             },
241         },
242         {
243             'url': 'http://www.nbcnews.com/business/autos/volkswagen-11-million-vehicles-could-have-suspect-software-emissions-scandal-n431456',
244             'md5': 'a49e173825e5fcd15c13fc297fced39d',
245             'info_dict': {
246                 'id': '529953347624',
247                 'ext': 'mp4',
248                 'title': 'Volkswagen U.S. Chief: We \'Totally Screwed Up\'',
249                 'description': 'md5:d22d1281a24f22ea0880741bb4dd6301',
250             },
251             'expected_warnings': ['http-6000 is not available']
252         },
253         {
254             'url': 'http://www.today.com/video/see-the-aurora-borealis-from-space-in-stunning-new-nasa-video-669831235788',
255             'md5': '118d7ca3f0bea6534f119c68ef539f71',
256             'info_dict': {
257                 'id': '669831235788',
258                 'ext': 'mp4',
259                 'title': 'See the aurora borealis from space in stunning new NASA video',
260                 'description': 'md5:74752b7358afb99939c5f8bb2d1d04b1',
261                 'upload_date': '20160420',
262                 'timestamp': 1461152093,
263             },
264         },
265         {
266             'url': 'http://www.nbcnews.com/watch/dateline/full-episode--deadly-betrayal-386250819952',
267             'only_matching': True,
268         },
269         {
270             # From http://www.vulture.com/2016/06/letterman-couldnt-care-less-about-late-night.html
271             'url': 'http://www.nbcnews.com/widget/video-embed/701714499682',
272             'only_matching': True,
273         },
274     ]
275
276     def _real_extract(self, url):
277         mobj = re.match(self._VALID_URL, url)
278         video_id = mobj.group('id')
279         if video_id is not None:
280             all_info = self._download_xml('http://www.nbcnews.com/id/%s/displaymode/1219' % video_id, video_id)
281             info = all_info.find('video')
282
283             return {
284                 'id': video_id,
285                 'title': info.find('headline').text,
286                 'ext': 'flv',
287                 'url': find_xpath_attr(info, 'media', 'type', 'flashVideo').text,
288                 'description': info.find('caption').text,
289                 'thumbnail': find_xpath_attr(info, 'media', 'type', 'thumbnail').text,
290             }
291         else:
292             # "feature" and "nightly-news" pages use theplatform.com
293             display_id = mobj.group('display_id')
294             webpage = self._download_webpage(url, display_id)
295             info = None
296             bootstrap_json = self._search_regex(
297                 [r'(?m)(?:var\s+(?:bootstrapJson|playlistData)|NEWS\.videoObj)\s*=\s*({.+});?\s*$',
298                  r'videoObj\s*:\s*({.+})', r'data-video="([^"]+)"'],
299                 webpage, 'bootstrap json', default=None)
300             bootstrap = self._parse_json(
301                 bootstrap_json, display_id, transform_source=unescapeHTML)
302             if 'results' in bootstrap:
303                 info = bootstrap['results'][0]['video']
304             elif 'video' in bootstrap:
305                 info = bootstrap['video']
306             else:
307                 info = bootstrap
308             video_id = info['mpxId']
309             title = info['title']
310
311             subtitles = {}
312             caption_links = info.get('captionLinks')
313             if caption_links:
314                 for (sub_key, sub_ext) in (('smpte-tt', 'ttml'), ('web-vtt', 'vtt'), ('srt', 'srt')):
315                     sub_url = caption_links.get(sub_key)
316                     if sub_url:
317                         subtitles.setdefault('en', []).append({
318                             'url': sub_url,
319                             'ext': sub_ext,
320                         })
321
322             formats = []
323             for video_asset in info['videoAssets']:
324                 video_url = video_asset.get('publicUrl')
325                 if not video_url:
326                     continue
327                 container = video_asset.get('format')
328                 asset_type = video_asset.get('assetType') or ''
329                 if container == 'ISM' or asset_type == 'FireTV-Once':
330                     continue
331                 elif asset_type == 'OnceURL':
332                     tp_formats, tp_subtitles = self._extract_theplatform_smil(
333                         video_url, video_id)
334                     formats.extend(tp_formats)
335                     subtitles = self._merge_subtitles(subtitles, tp_subtitles)
336                 else:
337                     tbr = int_or_none(video_asset.get('bitRate') or video_asset.get('bitrate'), 1000)
338                     format_id = 'http%s' % ('-%d' % tbr if tbr else '')
339                     video_url = update_url_query(
340                         video_url, {'format': 'redirect'})
341                     # resolve the url so that we can check availability and detect the correct extension
342                     head = self._request_webpage(
343                         HEADRequest(video_url), video_id,
344                         'Checking %s url' % format_id,
345                         '%s is not available' % format_id,
346                         fatal=False)
347                     if head:
348                         video_url = head.geturl()
349                         formats.append({
350                             'format_id': format_id,
351                             'url': video_url,
352                             'width': int_or_none(video_asset.get('width')),
353                             'height': int_or_none(video_asset.get('height')),
354                             'tbr': tbr,
355                             'container': video_asset.get('format'),
356                         })
357             self._sort_formats(formats)
358
359             return {
360                 'id': video_id,
361                 'title': title,
362                 'description': info.get('description'),
363                 'thumbnail': info.get('thumbnail'),
364                 'duration': int_or_none(info.get('duration')),
365                 'timestamp': parse_iso8601(info.get('pubDate') or info.get('pub_date')),
366                 'formats': formats,
367                 'subtitles': subtitles,
368             }
369
370
371 class MSNBCIE(InfoExtractor):
372     # https URLs redirect to corresponding http ones
373     _VALID_URL = r'https?://www\.msnbc\.com/[^/]+/watch/(?P<id>[^/]+)'
374     _TEST = {
375         'url': 'http://www.msnbc.com/all-in-with-chris-hayes/watch/the-chaotic-gop-immigration-vote-314487875924',
376         'md5': '6d236bf4f3dddc226633ce6e2c3f814d',
377         'info_dict': {
378             'id': 'n_hayes_Aimm_140801_272214',
379             'ext': 'mp4',
380             'title': 'The chaotic GOP immigration vote',
381             '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.',
382             'thumbnail': 're:^https?://.*\.jpg$',
383             'timestamp': 1406937606,
384             'upload_date': '20140802',
385             'uploader': 'NBCU-NEWS',
386             'categories': ['MSNBC/Topics/Franchise/Best of last night', 'MSNBC/Topics/General/Congress'],
387         },
388     }
389
390     def _real_extract(self, url):
391         video_id = self._match_id(url)
392         webpage = self._download_webpage(url, video_id)
393         embed_url = self._html_search_meta('embedURL', webpage)
394         return self.url_result(embed_url)