Merge pull request #5328 from yan12125/fix_5226
[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 )
14
15
16 class NBCIE(InfoExtractor):
17     _VALID_URL = r'https?://www\.nbc\.com/(?:[^/]+/)+(?P<id>n?\d+)'
18
19     _TESTS = [
20         {
21             'url': 'http://www.nbc.com/the-tonight-show/segments/112966',
22             # md5 checksum is not stable
23             'info_dict': {
24                 'id': 'c9xnCo0YPOPH',
25                 'ext': 'flv',
26                 'title': 'Jimmy Fallon Surprises Fans at Ben & Jerry\'s',
27                 'description': 'Jimmy gives out free scoops of his new "Tonight Dough" ice cream flavor by surprising customers at the Ben & Jerry\'s scoop shop.',
28             },
29         },
30         {
31             'url': 'http://www.nbc.com/the-tonight-show/episodes/176',
32             'info_dict': {
33                 'id': 'XwU9KZkp98TH',
34                 'ext': 'flv',
35                 'title': 'Ricky Gervais, Steven Van Zandt, ILoveMakonnen',
36                 'description': 'A brand new episode of The Tonight Show welcomes Ricky Gervais, Steven Van Zandt and ILoveMakonnen.',
37             },
38             'skip': 'Only works from US',
39         },
40     ]
41
42     def _real_extract(self, url):
43         video_id = self._match_id(url)
44         webpage = self._download_webpage(url, video_id)
45         theplatform_url = self._search_regex(
46             '(?:class="video-player video-player-full" data-mpx-url|class="player" src)="(.*?)"',
47             webpage, 'theplatform url').replace('_no_endcard', '')
48         if theplatform_url.startswith('//'):
49             theplatform_url = 'http:' + theplatform_url
50         return self.url_result(theplatform_url)
51
52
53 class NBCSportsVPlayerIE(InfoExtractor):
54     _VALID_URL = r'https?://vplayer\.nbcsports\.com/(?:[^/]+/)+(?P<id>[0-9a-zA-Z_]+)'
55
56     _TESTS = [{
57         'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_share/select/9CsDKds0kvHI',
58         'info_dict': {
59             'id': '9CsDKds0kvHI',
60             'ext': 'flv',
61             'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
62             'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
63         }
64     }, {
65         'note': 'This video is already expired. It\'s for testing _VALID_URL',
66         'url': 'http://vplayer.nbcsports.com/p/BxmELC/nbc_embedshare/select/_hqLjQ95yx8Z',
67         'only_matching': True,
68     }]
69
70     @staticmethod
71     def _extract_url(webpage):
72         iframe_m = re.search(
73             r'<iframe[^>]+src="(?P<url>https?://vplayer\.nbcsports\.com/[^"]+)"', webpage)
74         if iframe_m:
75             return iframe_m.group('url')
76
77     def _real_extract(self, url):
78         video_id = self._match_id(url)
79         webpage = self._download_webpage(url, video_id)
80         theplatform_url = self._og_search_video_url(webpage)
81         return self.url_result(theplatform_url, 'ThePlatform')
82
83
84 class NBCSportsIE(InfoExtractor):
85     # Does not include https becuase its certificate is invalid
86     _VALID_URL = r'http://www\.nbcsports\.com//?(?:[^/]+/)+(?P<id>[0-9a-z-]+)'
87
88     _TEST = {
89         'url': 'http://www.nbcsports.com//college-basketball/ncaab/tom-izzo-michigan-st-has-so-much-respect-duke',
90         'info_dict': {
91             'id': 'PHJSaFWbrTY9',
92             'ext': 'flv',
93             'title': 'Tom Izzo, Michigan St. has \'so much respect\' for Duke',
94             'description': 'md5:ecb459c9d59e0766ac9c7d5d0eda8113',
95         }
96     }
97
98     def _real_extract(self, url):
99         video_id = self._match_id(url)
100         webpage = self._download_webpage(url, video_id)
101         return self.url_result(
102             NBCSportsVPlayerIE._extract_url(webpage), 'NBCSportsVPlayer')
103
104
105 class NBCNewsIE(InfoExtractor):
106     _VALID_URL = r'''(?x)https?://(?:www\.)?nbcnews\.com/
107         (?:video/.+?/(?P<id>\d+)|
108         (?:feature|nightly-news)/[^/]+/(?P<title>.+))
109         '''
110
111     _TESTS = [
112         {
113             'url': 'http://www.nbcnews.com/video/nbc-news/52753292',
114             'md5': '47abaac93c6eaf9ad37ee6c4463a5179',
115             'info_dict': {
116                 'id': '52753292',
117                 'ext': 'flv',
118                 'title': 'Crew emerges after four-month Mars food study',
119                 'description': 'md5:24e632ffac72b35f8b67a12d1b6ddfc1',
120             },
121         },
122         {
123             'url': 'http://www.nbcnews.com/feature/edward-snowden-interview/how-twitter-reacted-snowden-interview-n117236',
124             'md5': 'b2421750c9f260783721d898f4c42063',
125             'info_dict': {
126                 'id': 'I1wpAI_zmhsQ',
127                 'ext': 'mp4',
128                 'title': 'How Twitter Reacted To The Snowden Interview',
129                 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
130             },
131             'add_ie': ['ThePlatform'],
132         },
133         {
134             'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
135             'md5': 'fdbf39ab73a72df5896b6234ff98518a',
136             'info_dict': {
137                 'id': 'Wjf9EDR3A_60',
138                 'ext': 'mp4',
139                 'title': 'FULL EPISODE: Family Business',
140                 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
141             },
142         },
143         {
144             'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
145             'md5': 'b5dda8cddd8650baa0dcb616dd2cf60d',
146             'info_dict': {
147                 'id': 'sekXqyTVnmN3',
148                 'ext': 'mp4',
149                 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
150                 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
151             },
152         },
153     ]
154
155     def _real_extract(self, url):
156         mobj = re.match(self._VALID_URL, url)
157         video_id = mobj.group('id')
158         if video_id is not None:
159             all_info = self._download_xml('http://www.nbcnews.com/id/%s/displaymode/1219' % video_id, video_id)
160             info = all_info.find('video')
161
162             return {
163                 'id': video_id,
164                 'title': info.find('headline').text,
165                 'ext': 'flv',
166                 'url': find_xpath_attr(info, 'media', 'type', 'flashVideo').text,
167                 'description': compat_str(info.find('caption').text),
168                 'thumbnail': find_xpath_attr(info, 'media', 'type', 'thumbnail').text,
169             }
170         else:
171             # "feature" and "nightly-news" pages use theplatform.com
172             title = mobj.group('title')
173             webpage = self._download_webpage(url, title)
174             bootstrap_json = self._search_regex(
175                 r'var\s+(?:bootstrapJson|playlistData)\s*=\s*({.+});?\s*$',
176                 webpage, 'bootstrap json', flags=re.MULTILINE)
177             bootstrap = self._parse_json(bootstrap_json, video_id)
178             info = bootstrap['results'][0]['video']
179             mpxid = info['mpxId']
180
181             base_urls = [
182                 info['fallbackPlaylistUrl'],
183                 info['associatedPlaylistUrl'],
184             ]
185
186             for base_url in base_urls:
187                 if not base_url:
188                     continue
189                 playlist_url = base_url + '?form=MPXNBCNewsAPI'
190
191                 try:
192                     all_videos = self._download_json(playlist_url, title)
193                 except ExtractorError as ee:
194                     if isinstance(ee.cause, compat_HTTPError):
195                         continue
196                     raise
197
198                 if not all_videos or 'videos' not in all_videos:
199                     continue
200
201                 try:
202                     info = next(v for v in all_videos['videos'] if v['mpxId'] == mpxid)
203                     break
204                 except StopIteration:
205                     continue
206
207             if info is None:
208                 raise ExtractorError('Could not find video in playlists')
209
210             return {
211                 '_type': 'url',
212                 # We get the best quality video
213                 'url': info['videoAssets'][-1]['publicUrl'],
214                 'ie_key': 'ThePlatform',
215             }