[nbcnews] Simplify
[youtube-dl] / youtube_dl / extractor / nbc.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_str,
9     compat_HTTPError,
10 )
11 from ..utils import (
12     ExtractorError,
13     find_xpath_attr,
14 )
15
16
17 class NBCIE(InfoExtractor):
18     _VALID_URL = r'http://www\.nbc\.com/(?:[^/]+/)+(?P<id>n?\d+)'
19
20     _TESTS = [
21         {
22             'url': 'http://www.nbc.com/chicago-fire/video/i-am-a-firefighter/2734188',
23             # md5 checksum is not stable
24             'info_dict': {
25                 'id': 'bTmnLCvIbaaH',
26                 'ext': 'flv',
27                 'title': 'I Am a Firefighter',
28                 'description': 'An emergency puts Dawson\'sf irefighter skills to the ultimate test in this four-part digital series.',
29             },
30         },
31         {
32             'url': 'http://www.nbc.com/the-tonight-show/episodes/176',
33             'info_dict': {
34                 'id': 'XwU9KZkp98TH',
35                 'ext': 'flv',
36                 'title': 'Ricky Gervais, Steven Van Zandt, ILoveMakonnen',
37                 'description': 'A brand new episode of The Tonight Show welcomes Ricky Gervais, Steven Van Zandt and ILoveMakonnen.',
38             },
39             'skip': 'Only works from US',
40         },
41     ]
42
43     def _real_extract(self, url):
44         video_id = self._match_id(url)
45         webpage = self._download_webpage(url, video_id)
46         theplatform_url = self._search_regex(
47             '(?:class="video-player video-player-full" data-mpx-url|class="player" src)="(.*?)"',
48             webpage, 'theplatform url').replace('_no_endcard', '')
49         if theplatform_url.startswith('//'):
50             theplatform_url = 'http:' + theplatform_url
51         return self.url_result(theplatform_url)
52
53
54 class NBCNewsIE(InfoExtractor):
55     _VALID_URL = r'''(?x)https?://(?:www\.)?nbcnews\.com/
56         (?:video/.+?/(?P<id>\d+)|
57         (?:feature|nightly-news)/[^/]+/(?P<title>.+))
58         '''
59
60     _TESTS = [
61         {
62             'url': 'http://www.nbcnews.com/video/nbc-news/52753292',
63             'md5': '47abaac93c6eaf9ad37ee6c4463a5179',
64             'info_dict': {
65                 'id': '52753292',
66                 'ext': 'flv',
67                 'title': 'Crew emerges after four-month Mars food study',
68                 'description': 'md5:24e632ffac72b35f8b67a12d1b6ddfc1',
69             },
70         },
71         {
72             'url': 'http://www.nbcnews.com/feature/edward-snowden-interview/how-twitter-reacted-snowden-interview-n117236',
73             'md5': 'b2421750c9f260783721d898f4c42063',
74             'info_dict': {
75                 'id': 'I1wpAI_zmhsQ',
76                 'ext': 'mp4',
77                 'title': 'How Twitter Reacted To The Snowden Interview',
78                 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
79             },
80             'add_ie': ['ThePlatform'],
81         },
82         {
83             'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
84             'md5': 'fdbf39ab73a72df5896b6234ff98518a',
85             'info_dict': {
86                 'id': 'Wjf9EDR3A_60',
87                 'ext': 'mp4',
88                 'title': 'FULL EPISODE: Family Business',
89                 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
90             },
91         },
92         {
93             'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
94             'md5': 'b5dda8cddd8650baa0dcb616dd2cf60d',
95             'info_dict': {
96                 'id': 'sekXqyTVnmN3',
97                 'ext': 'mp4',
98                 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
99                 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
100             },
101         },
102     ]
103
104     def _real_extract(self, url):
105         mobj = re.match(self._VALID_URL, url)
106         video_id = mobj.group('id')
107         if video_id is not None:
108             all_info = self._download_xml('http://www.nbcnews.com/id/%s/displaymode/1219' % video_id, video_id)
109             info = all_info.find('video')
110
111             return {
112                 'id': video_id,
113                 'title': info.find('headline').text,
114                 'ext': 'flv',
115                 'url': find_xpath_attr(info, 'media', 'type', 'flashVideo').text,
116                 'description': compat_str(info.find('caption').text),
117                 'thumbnail': find_xpath_attr(info, 'media', 'type', 'thumbnail').text,
118             }
119         else:
120             # "feature" and "nightly-news" pages use theplatform.com
121             title = mobj.group('title')
122             webpage = self._download_webpage(url, title)
123             bootstrap_json = self._search_regex(
124                 r'var\s+(?:bootstrapJson|playlistData)\s*=\s*({.+});?\s*$',
125                 webpage, 'bootstrap json', flags=re.MULTILINE)
126             bootstrap = self._parse_json(bootstrap_json, video_id)
127             info = bootstrap['results'][0]['video']
128             mpxid = info['mpxId']
129
130             base_urls = [
131                 info['fallbackPlaylistUrl'],
132                 info['associatedPlaylistUrl'],
133             ]
134
135             for base_url in base_urls:
136                 if not base_url:
137                     continue
138                 playlist_url = base_url + '?form=MPXNBCNewsAPI'
139
140                 try:
141                     all_videos = self._download_json(playlist_url, title)
142                 except ExtractorError as ee:
143                     if isinstance(ee.cause, compat_HTTPError):
144                         continue
145                     raise
146
147                 if not all_videos or 'videos' not in all_videos:
148                     continue
149
150                 try:
151                     info = next(v for v in all_videos['videos'] if v['mpxId'] == mpxid)
152                     break
153                 except StopIteration:
154                     continue
155
156             if info is None:
157                 raise ExtractorError('Could not find video in playlists')
158
159             return {
160                 '_type': 'url',
161                 # We get the best quality video
162                 'url': info['videoAssets'][-1]['publicUrl'],
163                 'ie_key': 'ThePlatform',
164             }