[pbs] Fix player URL (closes #6139)
[youtube-dl] / youtube_dl / extractor / pbs.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..utils import (
7     ExtractorError,
8     determine_ext,
9     int_or_none,
10     unified_strdate,
11     US_RATINGS,
12 )
13
14
15 class PBSIE(InfoExtractor):
16     _VALID_URL = r'''(?x)https?://
17         (?:
18            # Direct video URL
19            video\.pbs\.org/(?:viralplayer|video)/(?P<id>[0-9]+)/? |
20            # Article with embedded player (or direct video)
21            (?:www\.)?pbs\.org/(?:[^/]+/){2,5}(?P<presumptive_id>[^/]+?)(?:\.html)?/?(?:$|[?\#]) |
22            # Player
23            video\.pbs\.org/(?:widget/)?partnerplayer/(?P<player_id>[^/]+)/
24         )
25     '''
26
27     _TESTS = [
28         {
29             'url': 'http://www.pbs.org/tpt/constitution-usa-peter-sagal/watch/a-more-perfect-union/',
30             'md5': 'ce1888486f0908d555a8093cac9a7362',
31             'info_dict': {
32                 'id': '2365006249',
33                 'ext': 'mp4',
34                 'title': 'A More Perfect Union',
35                 'description': 'md5:ba0c207295339c8d6eced00b7c363c6a',
36                 'duration': 3190,
37             },
38         },
39         {
40             'url': 'http://www.pbs.org/wgbh/pages/frontline/losing-iraq/',
41             'md5': '143c98aa54a346738a3d78f54c925321',
42             'info_dict': {
43                 'id': '2365297690',
44                 'ext': 'mp4',
45                 'title': 'Losing Iraq',
46                 'description': 'md5:f5bfbefadf421e8bb8647602011caf8e',
47                 'duration': 5050,
48             },
49         },
50         {
51             'url': 'http://www.pbs.org/newshour/bb/education-jan-june12-cyberschools_02-23/',
52             'md5': 'b19856d7f5351b17a5ab1dc6a64be633',
53             'info_dict': {
54                 'id': '2201174722',
55                 'ext': 'mp4',
56                 'title': 'Cyber Schools Gain Popularity, but Quality Questions Persist',
57                 'description': 'md5:5871c15cba347c1b3d28ac47a73c7c28',
58                 'duration': 801,
59             },
60         },
61         {
62             'url': 'http://www.pbs.org/wnet/gperf/dudamel-conducts-verdi-requiem-hollywood-bowl-full-episode/3374/',
63             'md5': 'c62859342be2a0358d6c9eb306595978',
64             'info_dict': {
65                 'id': '2365297708',
66                 'ext': 'mp4',
67                 'description': 'md5:68d87ef760660eb564455eb30ca464fe',
68                 'title': 'Dudamel Conducts Verdi Requiem at the Hollywood Bowl - Full',
69                 'duration': 6559,
70                 'thumbnail': 're:^https?://.*\.jpg$',
71             }
72         },
73         {
74             'url': 'http://www.pbs.org/wgbh/nova/earth/killer-typhoon.html',
75             'md5': '908f3e5473a693b266b84e25e1cf9703',
76             'info_dict': {
77                 'id': '2365160389',
78                 'display_id': 'killer-typhoon',
79                 'ext': 'mp4',
80                 'description': 'md5:c741d14e979fc53228c575894094f157',
81                 'title': 'Killer Typhoon',
82                 'duration': 3172,
83                 'thumbnail': 're:^https?://.*\.jpg$',
84                 'upload_date': '20140122',
85             }
86         },
87         {
88             'url': 'http://www.pbs.org/wgbh/pages/frontline/united-states-of-secrets/',
89             'info_dict': {
90                 'id': 'united-states-of-secrets',
91             },
92             'playlist_count': 2,
93         },
94         {
95             'url': 'http://www.pbs.org/wgbh/americanexperience/films/death/player/',
96             'info_dict': {
97                 'id': '2280706814',
98                 'display_id': 'player',
99                 'ext': 'mp4',
100                 'title': 'Death and the Civil War',
101                 '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.',
102                 'duration': 6705,
103                 'thumbnail': 're:^https?://.*\.jpg$',
104             },
105             'params': {
106                 'skip_download': True,  # requires ffmpeg
107             }
108         }
109     ]
110
111     def _extract_webpage(self, url):
112         mobj = re.match(self._VALID_URL, url)
113
114         presumptive_id = mobj.group('presumptive_id')
115         display_id = presumptive_id
116         if presumptive_id:
117             webpage = self._download_webpage(url, display_id)
118
119             upload_date = unified_strdate(self._search_regex(
120                 r'<input type="hidden" id="air_date_[0-9]+" value="([^"]+)"',
121                 webpage, 'upload date', default=None))
122
123             # tabbed frontline videos
124             tabbed_videos = re.findall(
125                 r'<div[^>]+class="videotab[^"]*"[^>]+vid="(\d+)"', webpage)
126             if tabbed_videos:
127                 return tabbed_videos, presumptive_id, upload_date
128
129             MEDIA_ID_REGEXES = [
130                 r"div\s*:\s*'videoembed'\s*,\s*mediaid\s*:\s*'(\d+)'",  # frontline video embed
131                 r'class="coveplayerid">([^<]+)<',                       # coveplayer
132                 r'<input type="hidden" id="pbs_video_id_[0-9]+" value="([0-9]+)"/>',  # jwplayer
133             ]
134
135             media_id = self._search_regex(
136                 MEDIA_ID_REGEXES, webpage, 'media ID', fatal=False, default=None)
137             if media_id:
138                 return media_id, presumptive_id, upload_date
139
140             url = self._search_regex(
141                 r'<iframe\s+[^>]*\s+src=["\']([^\'"]+partnerplayer[^\'"]+)["\']',
142                 webpage, 'player URL')
143             mobj = re.match(self._VALID_URL, url)
144
145         player_id = mobj.group('player_id')
146         if not display_id:
147             display_id = player_id
148         if player_id:
149             player_page = self._download_webpage(
150                 url, display_id, note='Downloading player page',
151                 errnote='Could not download player page')
152             video_id = self._search_regex(
153                 r'<div\s+id="video_([0-9]+)"', player_page, 'video ID')
154         else:
155             video_id = mobj.group('id')
156             display_id = video_id
157
158         return video_id, display_id, None
159
160     def _real_extract(self, url):
161         video_id, display_id, upload_date = self._extract_webpage(url)
162
163         if isinstance(video_id, list):
164             entries = [self.url_result(
165                 'http://video.pbs.org/video/%s' % vid_id, 'PBS', vid_id)
166                 for vid_id in video_id]
167             return self.playlist_result(entries, display_id)
168
169         info = self._download_json(
170             'http://video.pbs.org/videoInfo/%s?format=json&type=partner' % video_id,
171             display_id)
172
173         formats = []
174         for encoding_name in ('recommended_encoding', 'alternate_encoding'):
175             redirect = info.get(encoding_name)
176             if not redirect:
177                 continue
178             redirect_url = redirect.get('url')
179             if not redirect_url:
180                 continue
181
182             redirect_info = self._download_json(
183                 redirect_url + '?format=json', display_id,
184                 'Downloading %s video url info' % encoding_name)
185
186             if redirect_info['status'] == 'error':
187                 if redirect_info['http_code'] == 403:
188                     message = (
189                         'The video is not available in your region due to '
190                         'right restrictions')
191                 else:
192                     message = redirect_info['message']
193                 raise ExtractorError(message, expected=True)
194
195             format_url = redirect_info.get('url')
196             if not format_url:
197                 continue
198
199             if determine_ext(format_url) == 'm3u8':
200                 formats.extend(self._extract_m3u8_formats(
201                     format_url, display_id, 'mp4', preference=1, m3u8_id='hls'))
202             else:
203                 formats.append({
204                     'url': format_url,
205                     'format_id': redirect.get('eeid'),
206                 })
207         self._sort_formats(formats)
208
209         rating_str = info.get('rating')
210         if rating_str is not None:
211             rating_str = rating_str.rpartition('-')[2]
212         age_limit = US_RATINGS.get(rating_str)
213
214         return {
215             'id': video_id,
216             'display_id': display_id,
217             'title': info['title'],
218             'description': info['program'].get('description'),
219             'thumbnail': info.get('image_url'),
220             'duration': int_or_none(info.get('duration')),
221             'age_limit': age_limit,
222             'upload_date': upload_date,
223             'formats': formats,
224         }