Merge branch 'akamai_pv' of https://github.com/remitamine/youtube-dl into remitamine...
[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
73     def _real_extract(self, url):
74         video_id = self._match_id(url)
75         webpage = self._download_webpage(url, video_id)
76         theplatform_url = unescapeHTML(lowercase_escape(self._html_search_regex(
77             [
78                 r'(?:class="video-player video-player-full" data-mpx-url|class="player" src)="(.*?)"',
79                 r'<iframe[^>]+src="((?:https?:)?//player\.theplatform\.com/[^"]+)"',
80                 r'"embedURL"\s*:\s*"([^"]+)"'
81             ],
82             webpage, 'theplatform url').replace('_no_endcard', '').replace('\\/', '/')))
83         if theplatform_url.startswith('//'):
84             theplatform_url = 'http:' + theplatform_url
85         return {
86             '_type': 'url_transparent',
87             'ie_key': 'ThePlatform',
88             'url': smuggle_url(theplatform_url, {'source_url': url}),
89             'id': video_id,
90         }
91
92
93 class NBCSportsVPlayerIE(InfoExtractor):
94     _VALID_URL = r'https?://vplayer\.nbcsports\.com/(?:[^/]+/)+(?P<id>[0-9a-zA-Z_]+)'
95
96     _TESTS = [{
97         'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_share/select/9CsDKds0kvHI',
98         'info_dict': {
99             'id': '9CsDKds0kvHI',
100             'ext': 'flv',
101             'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
102             'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
103             'timestamp': 1426270238,
104             'upload_date': '20150313',
105             'uploader': 'NBCU-SPORTS',
106         }
107     }, {
108         'url': 'http://vplayer.nbcsports.com/p/BxmELC/nbc_embedshare/select/_hqLjQ95yx8Z',
109         'only_matching': True,
110     }]
111
112     @staticmethod
113     def _extract_url(webpage):
114         iframe_m = re.search(
115             r'<iframe[^>]+src="(?P<url>https?://vplayer\.nbcsports\.com/[^"]+)"', webpage)
116         if iframe_m:
117             return iframe_m.group('url')
118
119     def _real_extract(self, url):
120         video_id = self._match_id(url)
121         webpage = self._download_webpage(url, video_id)
122         theplatform_url = self._og_search_video_url(webpage)
123         return self.url_result(theplatform_url, 'ThePlatform')
124
125
126 class NBCSportsIE(InfoExtractor):
127     # Does not include https because its certificate is invalid
128     _VALID_URL = r'https?://www\.nbcsports\.com//?(?:[^/]+/)+(?P<id>[0-9a-z-]+)'
129
130     _TEST = {
131         'url': 'http://www.nbcsports.com//college-basketball/ncaab/tom-izzo-michigan-st-has-so-much-respect-duke',
132         'info_dict': {
133             'id': 'PHJSaFWbrTY9',
134             'ext': 'flv',
135             'title': 'Tom Izzo, Michigan St. has \'so much respect\' for Duke',
136             'description': 'md5:ecb459c9d59e0766ac9c7d5d0eda8113',
137             'uploader': 'NBCU-SPORTS',
138             'upload_date': '20150330',
139             'timestamp': 1427726529,
140         }
141     }
142
143     def _real_extract(self, url):
144         video_id = self._match_id(url)
145         webpage = self._download_webpage(url, video_id)
146         return self.url_result(
147             NBCSportsVPlayerIE._extract_url(webpage), 'NBCSportsVPlayer')
148
149
150 class CSNNEIE(InfoExtractor):
151     _VALID_URL = r'https?://www\.csnne\.com/video/(?P<id>[0-9a-z-]+)'
152
153     _TEST = {
154         'url': 'http://www.csnne.com/video/snc-evening-update-wright-named-red-sox-no-5-starter',
155         'info_dict': {
156             'id': 'yvBLLUgQ8WU0',
157             'ext': 'mp4',
158             'title': 'SNC evening update: Wright named Red Sox\' No. 5 starter.',
159             'description': 'md5:1753cfee40d9352b19b4c9b3e589b9e3',
160             'timestamp': 1459369979,
161             'upload_date': '20160330',
162             'uploader': 'NBCU-SPORTS',
163         }
164     }
165
166     def _real_extract(self, url):
167         display_id = self._match_id(url)
168         webpage = self._download_webpage(url, display_id)
169         return {
170             '_type': 'url_transparent',
171             'ie_key': 'ThePlatform',
172             'url': self._html_search_meta('twitter:player:stream', webpage),
173             'display_id': display_id,
174         }
175
176
177 class NBCNewsIE(ThePlatformIE):
178     _VALID_URL = r'''(?x)https?://(?:www\.)?(?:nbcnews|today)\.com/
179         (?:video/.+?/(?P<id>\d+)|
180         ([^/]+/)*(?P<display_id>[^/?]+))
181         '''
182
183     _TESTS = [
184         {
185             'url': 'http://www.nbcnews.com/video/nbc-news/52753292',
186             'md5': '47abaac93c6eaf9ad37ee6c4463a5179',
187             'info_dict': {
188                 'id': '52753292',
189                 'ext': 'flv',
190                 'title': 'Crew emerges after four-month Mars food study',
191                 'description': 'md5:24e632ffac72b35f8b67a12d1b6ddfc1',
192             },
193         },
194         {
195             'url': 'http://www.nbcnews.com/watch/nbcnews-com/how-twitter-reacted-to-the-snowden-interview-269389891880',
196             'md5': 'af1adfa51312291a017720403826bb64',
197             'info_dict': {
198                 'id': '269389891880',
199                 'ext': 'mp4',
200                 'title': 'How Twitter Reacted To The Snowden Interview',
201                 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
202             },
203         },
204         {
205             'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
206             'md5': 'fdbf39ab73a72df5896b6234ff98518a',
207             'info_dict': {
208                 'id': 'Wjf9EDR3A_60',
209                 'ext': 'mp4',
210                 'title': 'FULL EPISODE: Family Business',
211                 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
212             },
213             'skip': 'This page is unavailable.',
214         },
215         {
216             'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
217             'md5': '73135a2e0ef819107bbb55a5a9b2a802',
218             'info_dict': {
219                 'id': '394064451844',
220                 'ext': 'mp4',
221                 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
222                 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
223             },
224         },
225         {
226             'url': 'http://www.nbcnews.com/business/autos/volkswagen-11-million-vehicles-could-have-suspect-software-emissions-scandal-n431456',
227             'md5': 'a49e173825e5fcd15c13fc297fced39d',
228             'info_dict': {
229                 'id': '529953347624',
230                 'ext': 'mp4',
231                 'title': 'Volkswagen U.S. Chief: We \'Totally Screwed Up\'',
232                 'description': 'md5:d22d1281a24f22ea0880741bb4dd6301',
233             },
234             'expected_warnings': ['http-6000 is not available']
235         },
236         {
237             'url': 'http://www.today.com/video/see-the-aurora-borealis-from-space-in-stunning-new-nasa-video-669831235788',
238             'md5': '118d7ca3f0bea6534f119c68ef539f71',
239             'info_dict': {
240                 'id': '669831235788',
241                 'ext': 'mp4',
242                 'title': 'See the aurora borealis from space in stunning new NASA video',
243                 'description': 'md5:74752b7358afb99939c5f8bb2d1d04b1',
244                 'upload_date': '20160420',
245                 'timestamp': 1461152093,
246             },
247         },
248         {
249             'url': 'http://www.nbcnews.com/watch/dateline/full-episode--deadly-betrayal-386250819952',
250             'only_matching': True,
251         },
252     ]
253
254     def _real_extract(self, url):
255         mobj = re.match(self._VALID_URL, url)
256         video_id = mobj.group('id')
257         if video_id is not None:
258             all_info = self._download_xml('http://www.nbcnews.com/id/%s/displaymode/1219' % video_id, video_id)
259             info = all_info.find('video')
260
261             return {
262                 'id': video_id,
263                 'title': info.find('headline').text,
264                 'ext': 'flv',
265                 'url': find_xpath_attr(info, 'media', 'type', 'flashVideo').text,
266                 'description': info.find('caption').text,
267                 'thumbnail': find_xpath_attr(info, 'media', 'type', 'thumbnail').text,
268             }
269         else:
270             # "feature" and "nightly-news" pages use theplatform.com
271             display_id = mobj.group('display_id')
272             webpage = self._download_webpage(url, display_id)
273             info = None
274             bootstrap_json = self._search_regex(
275                 r'(?m)var\s+(?:bootstrapJson|playlistData)\s*=\s*({.+});?\s*$',
276                 webpage, 'bootstrap json', default=None)
277             if bootstrap_json:
278                 bootstrap = self._parse_json(bootstrap_json, display_id)
279                 info = bootstrap['results'][0]['video']
280             else:
281                 player_instance_json = self._search_regex(
282                     r'videoObj\s*:\s*({.+})', webpage, 'player instance', default=None)
283                 if not player_instance_json:
284                     player_instance_json = self._html_search_regex(
285                         r'data-video="([^"]+)"', webpage, 'video json')
286                 info = self._parse_json(player_instance_json, display_id)
287             video_id = info['mpxId']
288             title = info['title']
289
290             subtitles = {}
291             caption_links = info.get('captionLinks')
292             if caption_links:
293                 for (sub_key, sub_ext) in (('smpte-tt', 'ttml'), ('web-vtt', 'vtt'), ('srt', 'srt')):
294                     sub_url = caption_links.get(sub_key)
295                     if sub_url:
296                         subtitles.setdefault('en', []).append({
297                             'url': sub_url,
298                             'ext': sub_ext,
299                         })
300
301             formats = []
302             for video_asset in info['videoAssets']:
303                 video_url = video_asset.get('publicUrl')
304                 if not video_url:
305                     continue
306                 container = video_asset.get('format')
307                 asset_type = video_asset.get('assetType') or ''
308                 if container == 'ISM' or asset_type == 'FireTV-Once':
309                     continue
310                 elif asset_type == 'OnceURL':
311                     tp_formats, tp_subtitles = self._extract_theplatform_smil(
312                         video_url, video_id)
313                     formats.extend(tp_formats)
314                     subtitles = self._merge_subtitles(subtitles, tp_subtitles)
315                 else:
316                     tbr = int_or_none(video_asset.get('bitRate') or video_asset.get('bitrate'), 1000)
317                     format_id = 'http%s' % ('-%d' % tbr if tbr else '')
318                     video_url = update_url_query(
319                         video_url, {'format': 'redirect'})
320                     # resolve the url so that we can check availability and detect the correct extension
321                     head = self._request_webpage(
322                         HEADRequest(video_url), video_id,
323                         'Checking %s url' % format_id,
324                         '%s is not available' % format_id,
325                         fatal=False)
326                     if head:
327                         video_url = head.geturl()
328                         formats.append({
329                             'format_id': format_id,
330                             'url': video_url,
331                             'width': int_or_none(video_asset.get('width')),
332                             'height': int_or_none(video_asset.get('height')),
333                             'tbr': tbr,
334                             'container': video_asset.get('format'),
335                         })
336             self._sort_formats(formats)
337
338             return {
339                 'id': video_id,
340                 'title': title,
341                 'description': info.get('description'),
342                 'thumbnail': info.get('thumbnail'),
343                 'duration': int_or_none(info.get('duration')),
344                 'timestamp': parse_iso8601(info.get('pubDate') or info.get('pub_date')),
345                 'formats': formats,
346                 'subtitles': subtitles,
347             }
348
349
350 class MSNBCIE(InfoExtractor):
351     # https URLs redirect to corresponding http ones
352     _VALID_URL = r'https?://www\.msnbc\.com/[^/]+/watch/(?P<id>[^/]+)'
353     _TEST = {
354         'url': 'http://www.msnbc.com/all-in-with-chris-hayes/watch/the-chaotic-gop-immigration-vote-314487875924',
355         'md5': '6d236bf4f3dddc226633ce6e2c3f814d',
356         'info_dict': {
357             'id': 'n_hayes_Aimm_140801_272214',
358             'ext': 'mp4',
359             'title': 'The chaotic GOP immigration vote',
360             '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.',
361             'thumbnail': 're:^https?://.*\.jpg$',
362             'timestamp': 1406937606,
363             'upload_date': '20140802',
364             'uploader': 'NBCU-NEWS',
365             'categories': ['MSNBC/Topics/Franchise/Best of last night', 'MSNBC/Topics/General/Congress'],
366         },
367     }
368
369     def _real_extract(self, url):
370         video_id = self._match_id(url)
371         webpage = self._download_webpage(url, video_id)
372         embed_url = self._html_search_meta('embedURL', webpage)
373         return self.url_result(embed_url)