[nbc] Smuggle referer (Closes #7791)
[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 ..compat import (
7     compat_str,
8     compat_HTTPError,
9 )
10 from ..utils import (
11     ExtractorError,
12     find_xpath_attr,
13     lowercase_escape,
14     smuggle_url,
15     unescapeHTML,
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             # md5 checksum is not stable
26             'info_dict': {
27                 'id': 'c9xnCo0YPOPH',
28                 'ext': 'flv',
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             },
32         },
33         {
34             'url': 'http://www.nbc.com/the-tonight-show/episodes/176',
35             'info_dict': {
36                 'id': 'XwU9KZkp98TH',
37                 'ext': 'flv',
38                 'title': 'Ricky Gervais, Steven Van Zandt, ILoveMakonnen',
39                 'description': 'A brand new episode of The Tonight Show welcomes Ricky Gervais, Steven Van Zandt and ILoveMakonnen.',
40             },
41             'skip': 'Only works from US',
42         },
43         {
44             'url': 'http://www.nbc.com/saturday-night-live/video/star-wars-teaser/2832821',
45             'info_dict': {
46                 'id': '8iUuyzWDdYUZ',
47                 'ext': 'flv',
48                 'title': 'Star Wars Teaser',
49                 'description': 'md5:0b40f9cbde5b671a7ff62fceccc4f442',
50             },
51             'skip': 'Only works from US',
52         },
53         {
54             # This video has expired but with an escaped embedURL
55             'url': 'http://www.nbc.com/parenthood/episode-guide/season-5/just-like-at-home/515',
56             'skip': 'Expired'
57         }
58     ]
59
60     def _real_extract(self, url):
61         video_id = self._match_id(url)
62         webpage = self._download_webpage(url, video_id)
63         theplatform_url = unescapeHTML(lowercase_escape(self._html_search_regex(
64             [
65                 r'(?:class="video-player video-player-full" data-mpx-url|class="player" src)="(.*?)"',
66                 r'"embedURL"\s*:\s*"([^"]+)"'
67             ],
68             webpage, 'theplatform url').replace('_no_endcard', '').replace('\\/', '/')))
69         if theplatform_url.startswith('//'):
70             theplatform_url = 'http:' + theplatform_url
71         return self.url_result(smuggle_url(theplatform_url, {'source_url': url}))
72
73
74 class NBCSportsVPlayerIE(InfoExtractor):
75     _VALID_URL = r'https?://vplayer\.nbcsports\.com/(?:[^/]+/)+(?P<id>[0-9a-zA-Z_]+)'
76
77     _TESTS = [{
78         'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_share/select/9CsDKds0kvHI',
79         'info_dict': {
80             'id': '9CsDKds0kvHI',
81             'ext': 'flv',
82             'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
83             'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
84         }
85     }, {
86         'url': 'http://vplayer.nbcsports.com/p/BxmELC/nbc_embedshare/select/_hqLjQ95yx8Z',
87         'only_matching': True,
88     }]
89
90     @staticmethod
91     def _extract_url(webpage):
92         iframe_m = re.search(
93             r'<iframe[^>]+src="(?P<url>https?://vplayer\.nbcsports\.com/[^"]+)"', webpage)
94         if iframe_m:
95             return iframe_m.group('url')
96
97     def _real_extract(self, url):
98         video_id = self._match_id(url)
99         webpage = self._download_webpage(url, video_id)
100         theplatform_url = self._og_search_video_url(webpage)
101         return self.url_result(theplatform_url, 'ThePlatform')
102
103
104 class NBCSportsIE(InfoExtractor):
105     # Does not include https becuase its certificate is invalid
106     _VALID_URL = r'http://www\.nbcsports\.com//?(?:[^/]+/)+(?P<id>[0-9a-z-]+)'
107
108     _TEST = {
109         'url': 'http://www.nbcsports.com//college-basketball/ncaab/tom-izzo-michigan-st-has-so-much-respect-duke',
110         'info_dict': {
111             'id': 'PHJSaFWbrTY9',
112             'ext': 'flv',
113             'title': 'Tom Izzo, Michigan St. has \'so much respect\' for Duke',
114             'description': 'md5:ecb459c9d59e0766ac9c7d5d0eda8113',
115         }
116     }
117
118     def _real_extract(self, url):
119         video_id = self._match_id(url)
120         webpage = self._download_webpage(url, video_id)
121         return self.url_result(
122             NBCSportsVPlayerIE._extract_url(webpage), 'NBCSportsVPlayer')
123
124
125 class NBCNewsIE(InfoExtractor):
126     _VALID_URL = r'''(?x)https?://(?:www\.)?nbcnews\.com/
127         (?:video/.+?/(?P<id>\d+)|
128         (?:watch|feature|nightly-news)/[^/]+/(?P<title>.+))
129         '''
130
131     _TESTS = [
132         {
133             'url': 'http://www.nbcnews.com/video/nbc-news/52753292',
134             'md5': '47abaac93c6eaf9ad37ee6c4463a5179',
135             'info_dict': {
136                 'id': '52753292',
137                 'ext': 'flv',
138                 'title': 'Crew emerges after four-month Mars food study',
139                 'description': 'md5:24e632ffac72b35f8b67a12d1b6ddfc1',
140             },
141         },
142         {
143             'url': 'http://www.nbcnews.com/feature/edward-snowden-interview/how-twitter-reacted-snowden-interview-n117236',
144             'md5': 'b2421750c9f260783721d898f4c42063',
145             'info_dict': {
146                 'id': 'I1wpAI_zmhsQ',
147                 'ext': 'mp4',
148                 'title': 'How Twitter Reacted To The Snowden Interview',
149                 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
150             },
151             'add_ie': ['ThePlatform'],
152         },
153         {
154             'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
155             'md5': 'fdbf39ab73a72df5896b6234ff98518a',
156             'info_dict': {
157                 'id': 'Wjf9EDR3A_60',
158                 'ext': 'mp4',
159                 'title': 'FULL EPISODE: Family Business',
160                 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
161             },
162         },
163         {
164             'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
165             'md5': 'b5dda8cddd8650baa0dcb616dd2cf60d',
166             'info_dict': {
167                 'id': 'sekXqyTVnmN3',
168                 'ext': 'mp4',
169                 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
170                 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
171             },
172         },
173         {
174             'url': 'http://www.nbcnews.com/watch/dateline/full-episode--deadly-betrayal-386250819952',
175             'only_matching': True,
176         },
177     ]
178
179     def _real_extract(self, url):
180         mobj = re.match(self._VALID_URL, url)
181         video_id = mobj.group('id')
182         if video_id is not None:
183             all_info = self._download_xml('http://www.nbcnews.com/id/%s/displaymode/1219' % video_id, video_id)
184             info = all_info.find('video')
185
186             return {
187                 'id': video_id,
188                 'title': info.find('headline').text,
189                 'ext': 'flv',
190                 'url': find_xpath_attr(info, 'media', 'type', 'flashVideo').text,
191                 'description': compat_str(info.find('caption').text),
192                 'thumbnail': find_xpath_attr(info, 'media', 'type', 'thumbnail').text,
193             }
194         else:
195             # "feature" and "nightly-news" pages use theplatform.com
196             title = mobj.group('title')
197             webpage = self._download_webpage(url, title)
198             bootstrap_json = self._search_regex(
199                 r'var\s+(?:bootstrapJson|playlistData)\s*=\s*({.+});?\s*$',
200                 webpage, 'bootstrap json', flags=re.MULTILINE)
201             bootstrap = self._parse_json(bootstrap_json, video_id)
202             info = bootstrap['results'][0]['video']
203             mpxid = info['mpxId']
204
205             base_urls = [
206                 info['fallbackPlaylistUrl'],
207                 info['associatedPlaylistUrl'],
208             ]
209
210             for base_url in base_urls:
211                 if not base_url:
212                     continue
213                 playlist_url = base_url + '?form=MPXNBCNewsAPI'
214
215                 try:
216                     all_videos = self._download_json(playlist_url, title)
217                 except ExtractorError as ee:
218                     if isinstance(ee.cause, compat_HTTPError):
219                         continue
220                     raise
221
222                 if not all_videos or 'videos' not in all_videos:
223                     continue
224
225                 try:
226                     info = next(v for v in all_videos['videos'] if v['mpxId'] == mpxid)
227                     break
228                 except StopIteration:
229                     continue
230
231             if info is None:
232                 raise ExtractorError('Could not find video in playlists')
233
234             return {
235                 '_type': 'url',
236                 # We get the best quality video
237                 'url': info['videoAssets'][-1]['publicUrl'],
238                 'ie_key': 'ThePlatform',
239             }
240
241
242 class MSNBCIE(InfoExtractor):
243     # https URLs redirect to corresponding http ones
244     _VALID_URL = r'http://www\.msnbc\.com/[^/]+/watch/(?P<id>[^/]+)'
245     _TEST = {
246         'url': 'http://www.msnbc.com/all-in-with-chris-hayes/watch/the-chaotic-gop-immigration-vote-314487875924',
247         'md5': '6d236bf4f3dddc226633ce6e2c3f814d',
248         'info_dict': {
249             'id': 'n_hayes_Aimm_140801_272214',
250             'ext': 'mp4',
251             'title': 'The chaotic GOP immigration vote',
252             '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.',
253             'thumbnail': 're:^https?://.*\.jpg$',
254             'timestamp': 1406937606,
255             'upload_date': '20140802',
256             'categories': ['MSNBC/Topics/Franchise/Best of last night', 'MSNBC/Topics/General/Congress'],
257         },
258     }
259
260     def _real_extract(self, url):
261         video_id = self._match_id(url)
262         webpage = self._download_webpage(url, video_id)
263         embed_url = self._html_search_meta('embedURL', webpage)
264         return self.url_result(embed_url)