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