[bliptv] remove extractor and add support for site replacement(makertv)
[youtube-dl] / youtube_dl / extractor / pbs.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     ExtractorError,
9     determine_ext,
10     int_or_none,
11     unified_strdate,
12     US_RATINGS,
13 )
14
15
16 class PBSIE(InfoExtractor):
17     _VALID_URL = r'''(?x)https?://
18         (?:
19            # Direct video URL
20            video\.pbs\.org/(?:viralplayer|video)/(?P<id>[0-9]+)/? |
21            # Article with embedded player (or direct video)
22            (?:www\.)?pbs\.org/(?:[^/]+/){2,5}(?P<presumptive_id>[^/]+?)(?:\.html)?/?(?:$|[?\#]) |
23            # Player
24            video\.pbs\.org/(?:widget/)?partnerplayer/(?P<player_id>[^/]+)/
25         )
26     '''
27
28     _TESTS = [
29         {
30             'url': 'http://www.pbs.org/tpt/constitution-usa-peter-sagal/watch/a-more-perfect-union/',
31             'md5': 'ce1888486f0908d555a8093cac9a7362',
32             'info_dict': {
33                 'id': '2365006249',
34                 'ext': 'mp4',
35                 'title': 'Constitution USA with Peter Sagal - A More Perfect Union',
36                 'description': 'md5:ba0c207295339c8d6eced00b7c363c6a',
37                 'duration': 3190,
38             },
39             'params': {
40                 'skip_download': True,  # requires ffmpeg
41             },
42         },
43         {
44             'url': 'http://www.pbs.org/wgbh/pages/frontline/losing-iraq/',
45             'md5': '143c98aa54a346738a3d78f54c925321',
46             'info_dict': {
47                 'id': '2365297690',
48                 'ext': 'mp4',
49                 'title': 'FRONTLINE - Losing Iraq',
50                 'description': 'md5:f5bfbefadf421e8bb8647602011caf8e',
51                 'duration': 5050,
52             },
53             'params': {
54                 'skip_download': True,  # requires ffmpeg
55             }
56         },
57         {
58             'url': 'http://www.pbs.org/newshour/bb/education-jan-june12-cyberschools_02-23/',
59             'md5': 'b19856d7f5351b17a5ab1dc6a64be633',
60             'info_dict': {
61                 'id': '2201174722',
62                 'ext': 'mp4',
63                 'title': 'PBS NewsHour - Cyber Schools Gain Popularity, but Quality Questions Persist',
64                 'description': 'md5:5871c15cba347c1b3d28ac47a73c7c28',
65                 'duration': 801,
66             },
67         },
68         {
69             'url': 'http://www.pbs.org/wnet/gperf/dudamel-conducts-verdi-requiem-hollywood-bowl-full-episode/3374/',
70             'md5': 'c62859342be2a0358d6c9eb306595978',
71             'info_dict': {
72                 'id': '2365297708',
73                 'ext': 'mp4',
74                 'description': 'md5:68d87ef760660eb564455eb30ca464fe',
75                 'title': 'Great Performances - Dudamel Conducts Verdi Requiem at the Hollywood Bowl - Full',
76                 'duration': 6559,
77                 'thumbnail': 're:^https?://.*\.jpg$',
78             },
79             'params': {
80                 'skip_download': True,  # requires ffmpeg
81             },
82         },
83         {
84             'url': 'http://www.pbs.org/wgbh/nova/earth/killer-typhoon.html',
85             'md5': '908f3e5473a693b266b84e25e1cf9703',
86             'info_dict': {
87                 'id': '2365160389',
88                 'display_id': 'killer-typhoon',
89                 'ext': 'mp4',
90                 'description': 'md5:c741d14e979fc53228c575894094f157',
91                 'title': 'NOVA - Killer Typhoon',
92                 'duration': 3172,
93                 'thumbnail': 're:^https?://.*\.jpg$',
94                 'upload_date': '20140122',
95                 'age_limit': 10,
96             },
97             'params': {
98                 'skip_download': True,  # requires ffmpeg
99             },
100         },
101         {
102             'url': 'http://www.pbs.org/wgbh/pages/frontline/united-states-of-secrets/',
103             'info_dict': {
104                 'id': 'united-states-of-secrets',
105             },
106             'playlist_count': 2,
107         },
108         {
109             'url': 'http://www.pbs.org/wgbh/americanexperience/films/death/player/',
110             'info_dict': {
111                 'id': '2276541483',
112                 'display_id': 'player',
113                 'ext': 'mp4',
114                 'title': 'American Experience - Death and the Civil War, Chapter 1',
115                 'description': 'American Experience, TV’s most-watched history series, brings to life the compelling stories from our past that inform our understanding of the world today.',
116                 'duration': 682,
117                 'thumbnail': 're:^https?://.*\.jpg$',
118             },
119             'params': {
120                 'skip_download': True,  # requires ffmpeg
121             },
122         },
123         {
124             'url': 'http://video.pbs.org/video/2365367186/',
125             'info_dict': {
126                 'id': '2365367186',
127                 'display_id': '2365367186',
128                 'ext': 'mp4',
129                 'title': 'To Catch A Comet - Full Episode',
130                 'description': 'On November 12, 2014, billions of kilometers from Earth, spacecraft orbiter Rosetta and lander Philae did what no other had dared to attempt \u2014 land on the volatile surface of a comet as it zooms around the sun at 67,000 km/hr. The European Space Agency hopes this mission can help peer into our past and unlock secrets of our origins.',
131                 'duration': 3342,
132                 'thumbnail': 're:^https?://.*\.jpg$',
133             },
134             'params': {
135                 'skip_download': True,  # requires ffmpeg
136             },
137             'skip': 'Expired',
138         },
139         {
140             # Video embedded in iframe containing angle brackets as attribute's value (e.g.
141             # "<iframe style='position: absolute;<br />\ntop: 0; left: 0;' ...", see
142             # https://github.com/rg3/youtube-dl/issues/7059)
143             'url': 'http://www.pbs.org/food/features/a-chefs-life-season-3-episode-5-prickly-business/',
144             'info_dict': {
145                 'id': '2365546844',
146                 'display_id': 'a-chefs-life-season-3-episode-5-prickly-business',
147                 'ext': 'mp4',
148                 'title': "A Chef's Life - Season 3, Ep. 5: Prickly Business",
149                 'description': 'md5:61db2ddf27c9912f09c241014b118ed1',
150                 'duration': 1480,
151                 'thumbnail': 're:^https?://.*\.jpg$',
152             },
153             'params': {
154                 'skip_download': True,  # requires ffmpeg
155             },
156         }
157     ]
158     _ERRORS = {
159         101: 'We\'re sorry, but this video is not yet available.',
160         403: 'We\'re sorry, but this video is not available in your region due to right restrictions.',
161         404: 'We are experiencing technical difficulties that are preventing us from playing the video at this time. Please check back again soon.',
162         410: 'This video has expired and is no longer available for online streaming.',
163     }
164
165     def _extract_webpage(self, url):
166         mobj = re.match(self._VALID_URL, url)
167
168         presumptive_id = mobj.group('presumptive_id')
169         display_id = presumptive_id
170         if presumptive_id:
171             webpage = self._download_webpage(url, display_id)
172
173             upload_date = unified_strdate(self._search_regex(
174                 r'<input type="hidden" id="air_date_[0-9]+" value="([^"]+)"',
175                 webpage, 'upload date', default=None))
176
177             # tabbed frontline videos
178             tabbed_videos = re.findall(
179                 r'<div[^>]+class="videotab[^"]*"[^>]+vid="(\d+)"', webpage)
180             if tabbed_videos:
181                 return tabbed_videos, presumptive_id, upload_date
182
183             MEDIA_ID_REGEXES = [
184                 r"div\s*:\s*'videoembed'\s*,\s*mediaid\s*:\s*'(\d+)'",  # frontline video embed
185                 r'class="coveplayerid">([^<]+)<',                       # coveplayer
186                 r'<input type="hidden" id="pbs_video_id_[0-9]+" value="([0-9]+)"/>',  # jwplayer
187             ]
188
189             media_id = self._search_regex(
190                 MEDIA_ID_REGEXES, webpage, 'media ID', fatal=False, default=None)
191             if media_id:
192                 return media_id, presumptive_id, upload_date
193
194             url = self._search_regex(
195                 r'(?s)<iframe[^>]+?(?:[a-z-]+?=["\'].*?["\'][^>]+?)*?\bsrc=["\']([^\'"]+partnerplayer[^\'"]+)["\']',
196                 webpage, 'player URL')
197             mobj = re.match(self._VALID_URL, url)
198
199         player_id = mobj.group('player_id')
200         if not display_id:
201             display_id = player_id
202         if player_id:
203             player_page = self._download_webpage(
204                 url, display_id, note='Downloading player page',
205                 errnote='Could not download player page')
206             video_id = self._search_regex(
207                 r'<div\s+id="video_([0-9]+)"', player_page, 'video ID')
208         else:
209             video_id = mobj.group('id')
210             display_id = video_id
211
212         return video_id, display_id, None
213
214     def _real_extract(self, url):
215         video_id, display_id, upload_date = self._extract_webpage(url)
216
217         if isinstance(video_id, list):
218             entries = [self.url_result(
219                 'http://video.pbs.org/video/%s' % vid_id, 'PBS', vid_id)
220                 for vid_id in video_id]
221             return self.playlist_result(entries, display_id)
222
223         info = self._download_json(
224             'http://video.pbs.org/videoInfo/%s?format=json&type=partner' % video_id,
225             display_id)
226
227         formats = []
228         for encoding_name in ('recommended_encoding', 'alternate_encoding'):
229             redirect = info.get(encoding_name)
230             if not redirect:
231                 continue
232             redirect_url = redirect.get('url')
233             if not redirect_url:
234                 continue
235
236             redirect_info = self._download_json(
237                 redirect_url + '?format=json', display_id,
238                 'Downloading %s video url info' % encoding_name)
239
240             if redirect_info['status'] == 'error':
241                 raise ExtractorError(
242                     '%s said: %s' % (
243                         self.IE_NAME,
244                         self._ERRORS.get(redirect_info['http_code'], redirect_info['message'])),
245                     expected=True)
246
247             format_url = redirect_info.get('url')
248             if not format_url:
249                 continue
250
251             if determine_ext(format_url) == 'm3u8':
252                 formats.extend(self._extract_m3u8_formats(
253                     format_url, display_id, 'mp4', preference=1, m3u8_id='hls'))
254             else:
255                 formats.append({
256                     'url': format_url,
257                     'format_id': redirect.get('eeid'),
258                 })
259         self._sort_formats(formats)
260
261         rating_str = info.get('rating')
262         if rating_str is not None:
263             rating_str = rating_str.rpartition('-')[2]
264         age_limit = US_RATINGS.get(rating_str)
265
266         subtitles = {}
267         closed_captions_url = info.get('closed_captions_url')
268         if closed_captions_url:
269             subtitles['en'] = [{
270                 'ext': 'ttml',
271                 'url': closed_captions_url,
272             }]
273
274         # info['title'] is often incomplete (e.g. 'Full Episode', 'Episode 5', etc)
275         # Try turning it to 'program - title' naming scheme if possible
276         alt_title = info.get('program', {}).get('title')
277         if alt_title:
278             info['title'] = alt_title + ' - ' + re.sub(r'^' + alt_title + '[\s\-:]+', '', info['title'])
279
280         return {
281             'id': video_id,
282             'display_id': display_id,
283             'title': info['title'],
284             'description': info['program'].get('description'),
285             'thumbnail': info.get('image_url'),
286             'duration': int_or_none(info.get('duration')),
287             'age_limit': age_limit,
288             'upload_date': upload_date,
289             'formats': formats,
290             'subtitles': subtitles,
291         }