[pbs] Improve extraction (closes #16623, closes #16684)
[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 ..compat import compat_str
8 from ..utils import (
9     ExtractorError,
10     determine_ext,
11     int_or_none,
12     float_or_none,
13     js_to_json,
14     orderedSet,
15     strip_jsonp,
16     strip_or_none,
17     unified_strdate,
18     US_RATINGS,
19 )
20
21
22 class PBSIE(InfoExtractor):
23     _STATIONS = (
24         (r'(?:video|www|player)\.pbs\.org', 'PBS: Public Broadcasting Service'),  # http://www.pbs.org/
25         (r'video\.aptv\.org', 'APT - Alabama Public Television (WBIQ)'),  # http://aptv.org/
26         (r'video\.gpb\.org', 'GPB/Georgia Public Broadcasting (WGTV)'),  # http://www.gpb.org/
27         (r'video\.mpbonline\.org', 'Mississippi Public Broadcasting (WMPN)'),  # http://www.mpbonline.org
28         (r'video\.wnpt\.org', 'Nashville Public Television (WNPT)'),  # http://www.wnpt.org
29         (r'video\.wfsu\.org', 'WFSU-TV (WFSU)'),  # http://wfsu.org/
30         (r'video\.wsre\.org', 'WSRE (WSRE)'),  # http://www.wsre.org
31         (r'video\.wtcitv\.org', 'WTCI (WTCI)'),  # http://www.wtcitv.org
32         (r'video\.pba\.org', 'WPBA/Channel 30 (WPBA)'),  # http://pba.org/
33         (r'video\.alaskapublic\.org', 'Alaska Public Media (KAKM)'),  # http://alaskapublic.org/kakm
34         # (r'kuac\.org', 'KUAC (KUAC)'),  # http://kuac.org/kuac-tv/
35         # (r'ktoo\.org', '360 North (KTOO)'),  # http://www.ktoo.org/
36         # (r'azpm\.org', 'KUAT 6 (KUAT)'),  # http://www.azpm.org/
37         (r'video\.azpbs\.org', 'Arizona PBS (KAET)'),  # http://www.azpbs.org
38         (r'portal\.knme\.org', 'KNME-TV/Channel 5 (KNME)'),  # http://www.newmexicopbs.org/
39         (r'video\.vegaspbs\.org', 'Vegas PBS (KLVX)'),  # http://vegaspbs.org/
40         (r'watch\.aetn\.org', 'AETN/ARKANSAS ETV NETWORK (KETS)'),  # http://www.aetn.org/
41         (r'video\.ket\.org', 'KET (WKLE)'),  # http://www.ket.org/
42         (r'video\.wkno\.org', 'WKNO/Channel 10 (WKNO)'),  # http://www.wkno.org/
43         (r'video\.lpb\.org', 'LPB/LOUISIANA PUBLIC BROADCASTING (WLPB)'),  # http://www.lpb.org/
44         (r'videos\.oeta\.tv', 'OETA (KETA)'),  # http://www.oeta.tv
45         (r'video\.optv\.org', 'Ozarks Public Television (KOZK)'),  # http://www.optv.org/
46         (r'watch\.wsiu\.org', 'WSIU Public Broadcasting (WSIU)'),  # http://www.wsiu.org/
47         (r'video\.keet\.org', 'KEET TV (KEET)'),  # http://www.keet.org
48         (r'pbs\.kixe\.org', 'KIXE/Channel 9 (KIXE)'),  # http://kixe.org/
49         (r'video\.kpbs\.org', 'KPBS San Diego (KPBS)'),  # http://www.kpbs.org/
50         (r'video\.kqed\.org', 'KQED (KQED)'),  # http://www.kqed.org
51         (r'vids\.kvie\.org', 'KVIE Public Television (KVIE)'),  # http://www.kvie.org
52         (r'video\.pbssocal\.org', 'PBS SoCal/KOCE (KOCE)'),  # http://www.pbssocal.org/
53         (r'video\.valleypbs\.org', 'ValleyPBS (KVPT)'),  # http://www.valleypbs.org/
54         (r'video\.cptv\.org', 'CONNECTICUT PUBLIC TELEVISION (WEDH)'),  # http://cptv.org
55         (r'watch\.knpb\.org', 'KNPB Channel 5 (KNPB)'),  # http://www.knpb.org/
56         (r'video\.soptv\.org', 'SOPTV (KSYS)'),  # http://www.soptv.org
57         # (r'klcs\.org', 'KLCS/Channel 58 (KLCS)'),  # http://www.klcs.org
58         # (r'krcb\.org', 'KRCB Television & Radio (KRCB)'),  # http://www.krcb.org
59         # (r'kvcr\.org', 'KVCR TV/DT/FM :: Vision for the Future (KVCR)'),  # http://kvcr.org
60         (r'video\.rmpbs\.org', 'Rocky Mountain PBS (KRMA)'),  # http://www.rmpbs.org
61         (r'video\.kenw\.org', 'KENW-TV3 (KENW)'),  # http://www.kenw.org
62         (r'video\.kued\.org', 'KUED Channel 7 (KUED)'),  # http://www.kued.org
63         (r'video\.wyomingpbs\.org', 'Wyoming PBS (KCWC)'),  # http://www.wyomingpbs.org
64         (r'video\.cpt12\.org', 'Colorado Public Television / KBDI 12 (KBDI)'),  # http://www.cpt12.org/
65         (r'video\.kbyueleven\.org', 'KBYU-TV (KBYU)'),  # http://www.kbyutv.org/
66         (r'video\.thirteen\.org', 'Thirteen/WNET New York (WNET)'),  # http://www.thirteen.org
67         (r'video\.wgbh\.org', 'WGBH/Channel 2 (WGBH)'),  # http://wgbh.org
68         (r'video\.wgby\.org', 'WGBY (WGBY)'),  # http://www.wgby.org
69         (r'watch\.njtvonline\.org', 'NJTV Public Media NJ (WNJT)'),  # http://www.njtvonline.org/
70         # (r'ripbs\.org', 'Rhode Island PBS (WSBE)'),  # http://www.ripbs.org/home/
71         (r'watch\.wliw\.org', 'WLIW21 (WLIW)'),  # http://www.wliw.org/
72         (r'video\.mpt\.tv', 'mpt/Maryland Public Television (WMPB)'),  # http://www.mpt.org
73         (r'watch\.weta\.org', 'WETA Television and Radio (WETA)'),  # http://www.weta.org
74         (r'video\.whyy\.org', 'WHYY (WHYY)'),  # http://www.whyy.org
75         (r'video\.wlvt\.org', 'PBS 39 (WLVT)'),  # http://www.wlvt.org/
76         (r'video\.wvpt\.net', 'WVPT - Your Source for PBS and More! (WVPT)'),  # http://www.wvpt.net
77         (r'video\.whut\.org', 'Howard University Television (WHUT)'),  # http://www.whut.org
78         (r'video\.wedu\.org', 'WEDU PBS (WEDU)'),  # http://www.wedu.org
79         (r'video\.wgcu\.org', 'WGCU Public Media (WGCU)'),  # http://www.wgcu.org/
80         # (r'wjct\.org', 'WJCT Public Broadcasting (WJCT)'),  # http://www.wjct.org
81         (r'video\.wpbt2\.org', 'WPBT2 (WPBT)'),  # http://www.wpbt2.org
82         (r'video\.wucftv\.org', 'WUCF TV (WUCF)'),  # http://wucftv.org
83         (r'video\.wuft\.org', 'WUFT/Channel 5 (WUFT)'),  # http://www.wuft.org
84         (r'watch\.wxel\.org', 'WXEL/Channel 42 (WXEL)'),  # http://www.wxel.org/home/
85         (r'video\.wlrn\.org', 'WLRN/Channel 17 (WLRN)'),  # http://www.wlrn.org/
86         (r'video\.wusf\.usf\.edu', 'WUSF Public Broadcasting (WUSF)'),  # http://wusf.org/
87         (r'video\.scetv\.org', 'ETV (WRLK)'),  # http://www.scetv.org
88         (r'video\.unctv\.org', 'UNC-TV (WUNC)'),  # http://www.unctv.org/
89         # (r'pbsguam\.org', 'PBS Guam (KGTF)'),  # http://www.pbsguam.org/
90         (r'video\.pbshawaii\.org', 'PBS Hawaii - Oceanic Cable Channel 10 (KHET)'),  # http://www.pbshawaii.org/
91         (r'video\.idahoptv\.org', 'Idaho Public Television (KAID)'),  # http://idahoptv.org
92         (r'video\.ksps\.org', 'KSPS (KSPS)'),  # http://www.ksps.org/home/
93         (r'watch\.opb\.org', 'OPB (KOPB)'),  # http://www.opb.org
94         (r'watch\.nwptv\.org', 'KWSU/Channel 10 & KTNW/Channel 31 (KWSU)'),  # http://www.kwsu.org
95         (r'video\.will\.illinois\.edu', 'WILL-TV (WILL)'),  # http://will.illinois.edu/
96         (r'video\.networkknowledge\.tv', 'Network Knowledge - WSEC/Springfield (WSEC)'),  # http://www.wsec.tv
97         (r'video\.wttw\.com', 'WTTW11 (WTTW)'),  # http://www.wttw.com/
98         # (r'wtvp\.org', 'WTVP & WTVP.org, Public Media for Central Illinois (WTVP)'),  # http://www.wtvp.org/
99         (r'video\.iptv\.org', 'Iowa Public Television/IPTV (KDIN)'),  # http://www.iptv.org/
100         (r'video\.ninenet\.org', 'Nine Network (KETC)'),  # http://www.ninenet.org
101         (r'video\.wfwa\.org', 'PBS39 Fort Wayne (WFWA)'),  # http://wfwa.org/
102         (r'video\.wfyi\.org', 'WFYI Indianapolis (WFYI)'),  # http://www.wfyi.org
103         (r'video\.mptv\.org', 'Milwaukee Public Television (WMVS)'),  # http://www.mptv.org
104         (r'video\.wnin\.org', 'WNIN (WNIN)'),  # http://www.wnin.org/
105         (r'video\.wnit\.org', 'WNIT Public Television (WNIT)'),  # http://www.wnit.org/
106         (r'video\.wpt\.org', 'WPT (WPNE)'),  # http://www.wpt.org/
107         (r'video\.wvut\.org', 'WVUT/Channel 22 (WVUT)'),  # http://wvut.org/
108         (r'video\.weiu\.net', 'WEIU/Channel 51 (WEIU)'),  # http://www.weiu.net
109         (r'video\.wqpt\.org', 'WQPT-TV (WQPT)'),  # http://www.wqpt.org
110         (r'video\.wycc\.org', 'WYCC PBS Chicago (WYCC)'),  # http://www.wycc.org
111         # (r'lakeshorepublicmedia\.org', 'Lakeshore Public Television (WYIN)'),  # http://lakeshorepublicmedia.org/
112         (r'video\.wipb\.org', 'WIPB-TV (WIPB)'),  # http://wipb.org
113         (r'video\.indianapublicmedia\.org', 'WTIU (WTIU)'),  # http://indianapublicmedia.org/tv/
114         (r'watch\.cetconnect\.org', 'CET  (WCET)'),  # http://www.cetconnect.org
115         (r'video\.thinktv\.org', 'ThinkTVNetwork (WPTD)'),  # http://www.thinktv.org
116         (r'video\.wbgu\.org', 'WBGU-TV (WBGU)'),  # http://wbgu.org
117         (r'video\.wgvu\.org', 'WGVU TV (WGVU)'),  # http://www.wgvu.org/
118         (r'video\.netnebraska\.org', 'NET1 (KUON)'),  # http://netnebraska.org
119         (r'video\.pioneer\.org', 'Pioneer Public Television (KWCM)'),  # http://www.pioneer.org
120         (r'watch\.sdpb\.org', 'SDPB Television (KUSD)'),  # http://www.sdpb.org
121         (r'video\.tpt\.org', 'TPT (KTCA)'),  # http://www.tpt.org
122         (r'watch\.ksmq\.org', 'KSMQ (KSMQ)'),  # http://www.ksmq.org/
123         (r'watch\.kpts\.org', 'KPTS/Channel 8 (KPTS)'),  # http://www.kpts.org/
124         (r'watch\.ktwu\.org', 'KTWU/Channel 11 (KTWU)'),  # http://ktwu.org
125         # (r'shptv\.org', 'Smoky Hills Public Television (KOOD)'),  # http://www.shptv.org
126         # (r'kcpt\.org', 'KCPT Kansas City Public Television (KCPT)'),  # http://kcpt.org/
127         # (r'blueridgepbs\.org', 'Blue Ridge PBS (WBRA)'),  # http://www.blueridgepbs.org/
128         (r'watch\.easttennesseepbs\.org', 'East Tennessee PBS (WSJK)'),  # http://easttennesseepbs.org
129         (r'video\.wcte\.tv', 'WCTE-TV (WCTE)'),  # http://www.wcte.org
130         (r'video\.wljt\.org', 'WLJT, Channel 11 (WLJT)'),  # http://wljt.org/
131         (r'video\.wosu\.org', 'WOSU TV (WOSU)'),  # http://wosu.org/
132         (r'video\.woub\.org', 'WOUB/WOUC (WOUB)'),  # http://woub.org/tv/index.php?section=5
133         (r'video\.wvpublic\.org', 'WVPB (WVPB)'),  # http://wvpublic.org/
134         (r'video\.wkyupbs\.org', 'WKYU-PBS (WKYU)'),  # http://www.wkyupbs.org
135         # (r'wyes\.org', 'WYES-TV/New Orleans (WYES)'),  # http://www.wyes.org
136         (r'video\.kera\.org', 'KERA 13 (KERA)'),  # http://www.kera.org/
137         (r'video\.mpbn\.net', 'MPBN (WCBB)'),  # http://www.mpbn.net/
138         (r'video\.mountainlake\.org', 'Mountain Lake PBS (WCFE)'),  # http://www.mountainlake.org/
139         (r'video\.nhptv\.org', 'NHPTV (WENH)'),  # http://nhptv.org/
140         (r'video\.vpt\.org', 'Vermont PBS (WETK)'),  # http://www.vpt.org
141         (r'video\.witf\.org', 'witf (WITF)'),  # http://www.witf.org
142         (r'watch\.wqed\.org', 'WQED Multimedia (WQED)'),  # http://www.wqed.org/
143         (r'video\.wmht\.org', 'WMHT Educational Telecommunications (WMHT)'),  # http://www.wmht.org/home/
144         (r'video\.deltabroadcasting\.org', 'Q-TV (WDCQ)'),  # http://www.deltabroadcasting.org
145         (r'video\.dptv\.org', 'WTVS Detroit Public TV (WTVS)'),  # http://www.dptv.org/
146         (r'video\.wcmu\.org', 'CMU Public Television (WCMU)'),  # http://www.wcmu.org
147         (r'video\.wkar\.org', 'WKAR-TV (WKAR)'),  # http://wkar.org/
148         (r'wnmuvideo\.nmu\.edu', 'WNMU-TV Public TV 13 (WNMU)'),  # http://wnmutv.nmu.edu
149         (r'video\.wdse\.org', 'WDSE - WRPT (WDSE)'),  # http://www.wdse.org/
150         (r'video\.wgte\.org', 'WGTE TV (WGTE)'),  # http://www.wgte.org
151         (r'video\.lptv\.org', 'Lakeland Public Television (KAWE)'),  # http://www.lakelandptv.org
152         # (r'prairiepublic\.org', 'PRAIRIE PUBLIC (KFME)'),  # http://www.prairiepublic.org/
153         (r'video\.kmos\.org', 'KMOS-TV - Channels 6.1, 6.2 and 6.3 (KMOS)'),  # http://www.kmos.org/
154         (r'watch\.montanapbs\.org', 'MontanaPBS (KUSM)'),  # http://montanapbs.org
155         (r'video\.krwg\.org', 'KRWG/Channel 22 (KRWG)'),  # http://www.krwg.org
156         (r'video\.kacvtv\.org', 'KACV (KACV)'),  # http://www.panhandlepbs.org/home/
157         (r'video\.kcostv\.org', 'KCOS/Channel 13 (KCOS)'),  # www.kcostv.org
158         (r'video\.wcny\.org', 'WCNY/Channel 24 (WCNY)'),  # http://www.wcny.org
159         (r'video\.wned\.org', 'WNED (WNED)'),  # http://www.wned.org/
160         (r'watch\.wpbstv\.org', 'WPBS (WPBS)'),  # http://www.wpbstv.org
161         (r'video\.wskg\.org', 'WSKG Public TV (WSKG)'),  # http://wskg.org
162         (r'video\.wxxi\.org', 'WXXI (WXXI)'),  # http://wxxi.org
163         (r'video\.wpsu\.org', 'WPSU (WPSU)'),  # http://www.wpsu.org
164         # (r'wqln\.org', 'WQLN/Channel 54 (WQLN)'),  # http://www.wqln.org
165         (r'on-demand\.wvia\.org', 'WVIA Public Media Studios (WVIA)'),  # http://www.wvia.org/
166         (r'video\.wtvi\.org', 'WTVI (WTVI)'),  # http://www.wtvi.org/
167         # (r'whro\.org', 'WHRO (WHRO)'),  # http://whro.org
168         (r'video\.westernreservepublicmedia\.org', 'Western Reserve PBS (WNEO)'),  # http://www.WesternReservePublicMedia.org/
169         (r'video\.ideastream\.org', 'WVIZ/PBS ideastream (WVIZ)'),  # http://www.wviz.org/
170         (r'video\.kcts9\.org', 'KCTS 9 (KCTS)'),  # http://kcts9.org/
171         (r'video\.basinpbs\.org', 'Basin PBS (KPBT)'),  # http://www.basinpbs.org
172         (r'video\.houstonpbs\.org', 'KUHT / Channel 8 (KUHT)'),  # http://www.houstonpublicmedia.org/
173         # (r'tamu\.edu', 'KAMU - TV (KAMU)'),  # http://KAMU.tamu.edu
174         # (r'kedt\.org', 'KEDT/Channel 16 (KEDT)'),  # http://www.kedt.org
175         (r'video\.klrn\.org', 'KLRN (KLRN)'),  # http://www.klrn.org
176         (r'video\.klru\.tv', 'KLRU (KLRU)'),  # http://www.klru.org
177         # (r'kmbh\.org', 'KMBH-TV (KMBH)'),  # http://www.kmbh.org
178         # (r'knct\.org', 'KNCT (KNCT)'),  # http://www.knct.org
179         # (r'ktxt\.org', 'KTTZ-TV (KTXT)'),  # http://www.ktxt.org
180         (r'video\.wtjx\.org', 'WTJX Channel 12 (WTJX)'),  # http://www.wtjx.org/
181         (r'video\.ideastations\.org', 'WCVE PBS (WCVE)'),  # http://ideastations.org/
182         (r'video\.kbtc\.org', 'KBTC Public Television (KBTC)'),  # http://kbtc.org
183     )
184
185     IE_NAME = 'pbs'
186     IE_DESC = 'Public Broadcasting Service (PBS) and member stations: %s' % ', '.join(list(zip(*_STATIONS))[1])
187
188     _VALID_URL = r'''(?x)https?://
189         (?:
190            # Direct video URL
191            (?:%s)/(?:(?:vir|port)alplayer|video)/(?P<id>[0-9]+)(?:[?/]|$) |
192            # Article with embedded player (or direct video)
193            (?:www\.)?pbs\.org/(?:[^/]+/){1,5}(?P<presumptive_id>[^/]+?)(?:\.html)?/?(?:$|[?\#]) |
194            # Player
195            (?:video|player)\.pbs\.org/(?:widget/)?partnerplayer/(?P<player_id>[^/]+)/
196         )
197     ''' % '|'.join(list(zip(*_STATIONS))[0])
198
199     _GEO_COUNTRIES = ['US']
200
201     _TESTS = [
202         {
203             'url': 'http://www.pbs.org/tpt/constitution-usa-peter-sagal/watch/a-more-perfect-union/',
204             'md5': '173dc391afd361fa72eab5d3d918968d',
205             'info_dict': {
206                 'id': '2365006249',
207                 'ext': 'mp4',
208                 'title': 'Constitution USA with Peter Sagal - A More Perfect Union',
209                 'description': 'md5:31b664af3c65fd07fa460d306b837d00',
210                 'duration': 3190,
211             },
212         },
213         {
214             'url': 'http://www.pbs.org/wgbh/pages/frontline/losing-iraq/',
215             'md5': '6f722cb3c3982186d34b0f13374499c7',
216             'info_dict': {
217                 'id': '2365297690',
218                 'ext': 'mp4',
219                 'title': 'FRONTLINE - Losing Iraq',
220                 'description': 'md5:5979a4d069b157f622d02bff62fbe654',
221                 'duration': 5050,
222             },
223         },
224         {
225             'url': 'http://www.pbs.org/newshour/bb/education-jan-june12-cyberschools_02-23/',
226             'md5': 'b19856d7f5351b17a5ab1dc6a64be633',
227             'info_dict': {
228                 'id': '2201174722',
229                 'ext': 'mp4',
230                 'title': 'PBS NewsHour - Cyber Schools Gain Popularity, but Quality Questions Persist',
231                 'description': 'md5:86ab9a3d04458b876147b355788b8781',
232                 'duration': 801,
233             },
234         },
235         {
236             'url': 'http://www.pbs.org/wnet/gperf/dudamel-conducts-verdi-requiem-hollywood-bowl-full-episode/3374/',
237             'md5': 'c62859342be2a0358d6c9eb306595978',
238             'info_dict': {
239                 'id': '2365297708',
240                 'ext': 'mp4',
241                 'title': 'Great Performances - Dudamel Conducts Verdi Requiem at the Hollywood Bowl - Full',
242                 'description': 'md5:657897370e09e2bc6bf0f8d2cd313c6b',
243                 'duration': 6559,
244                 'thumbnail': r're:^https?://.*\.jpg$',
245             },
246         },
247         {
248             'url': 'http://www.pbs.org/wgbh/nova/earth/killer-typhoon.html',
249             'md5': '908f3e5473a693b266b84e25e1cf9703',
250             'info_dict': {
251                 'id': '2365160389',
252                 'display_id': 'killer-typhoon',
253                 'ext': 'mp4',
254                 'description': 'md5:c741d14e979fc53228c575894094f157',
255                 'title': 'NOVA - Killer Typhoon',
256                 'duration': 3172,
257                 'thumbnail': r're:^https?://.*\.jpg$',
258                 'upload_date': '20140122',
259                 'age_limit': 10,
260             },
261         },
262         {
263             'url': 'http://www.pbs.org/wgbh/pages/frontline/united-states-of-secrets/',
264             'info_dict': {
265                 'id': 'united-states-of-secrets',
266             },
267             'playlist_count': 2,
268         },
269         {
270             'url': 'http://www.pbs.org/wgbh/americanexperience/films/great-war/',
271             'info_dict': {
272                 'id': 'great-war',
273             },
274             'playlist_count': 3,
275         },
276         {
277             'url': 'http://www.pbs.org/wgbh/americanexperience/films/death/player/',
278             'info_dict': {
279                 'id': '2276541483',
280                 'display_id': 'player',
281                 'ext': 'mp4',
282                 'title': 'American Experience - Death and the Civil War, Chapter 1',
283                 'description': 'md5:67fa89a9402e2ee7d08f53b920674c18',
284                 'duration': 682,
285                 'thumbnail': r're:^https?://.*\.jpg$',
286             },
287             'params': {
288                 'skip_download': True,  # requires ffmpeg
289             },
290         },
291         {
292             'url': 'http://www.pbs.org/video/2365245528/',
293             'md5': '115223d41bd55cda8ae5cd5ed4e11497',
294             'info_dict': {
295                 'id': '2365245528',
296                 'display_id': '2365245528',
297                 'ext': 'mp4',
298                 'title': 'FRONTLINE - United States of Secrets (Part One)',
299                 'description': 'md5:55756bd5c551519cc4b7703e373e217e',
300                 'duration': 6851,
301                 'thumbnail': r're:^https?://.*\.jpg$',
302             },
303         },
304         {
305             # Video embedded in iframe containing angle brackets as attribute's value (e.g.
306             # "<iframe style='position: absolute;<br />\ntop: 0; left: 0;' ...", see
307             # https://github.com/rg3/youtube-dl/issues/7059)
308             'url': 'http://www.pbs.org/food/features/a-chefs-life-season-3-episode-5-prickly-business/',
309             'md5': '59b0ef5009f9ac8a319cc5efebcd865e',
310             'info_dict': {
311                 'id': '2365546844',
312                 'display_id': 'a-chefs-life-season-3-episode-5-prickly-business',
313                 'ext': 'mp4',
314                 'title': "A Chef's Life - Season 3, Ep. 5: Prickly Business",
315                 'description': 'md5:c0ff7475a4b70261c7e58f493c2792a5',
316                 'duration': 1480,
317                 'thumbnail': r're:^https?://.*\.jpg$',
318             },
319         },
320         {
321             # Frontline video embedded via flp2012.js
322             'url': 'http://www.pbs.org/wgbh/pages/frontline/the-atomic-artists',
323             'info_dict': {
324                 'id': '2070868960',
325                 'display_id': 'the-atomic-artists',
326                 'ext': 'mp4',
327                 'title': 'FRONTLINE - The Atomic Artists',
328                 'description': 'md5:f677e4520cfacb4a5ce1471e31b57800',
329                 'duration': 723,
330                 'thumbnail': r're:^https?://.*\.jpg$',
331             },
332             'params': {
333                 'skip_download': True,  # requires ffmpeg
334             },
335         },
336         {
337             # Serves hd only via wigget/partnerplayer page
338             'url': 'http://www.pbs.org/video/2365641075/',
339             'md5': 'fdf907851eab57211dd589cf12006666',
340             'info_dict': {
341                 'id': '2365641075',
342                 'ext': 'mp4',
343                 'title': 'FRONTLINE - Netanyahu at War',
344                 'duration': 6852,
345                 'thumbnail': r're:^https?://.*\.jpg$',
346                 'formats': 'mincount:8',
347             },
348         },
349         {
350             # https://github.com/rg3/youtube-dl/issues/13801
351             'url': 'https://www.pbs.org/video/pbs-newshour-full-episode-july-31-2017-1501539057/',
352             'info_dict': {
353                 'id': '3003333873',
354                 'ext': 'mp4',
355                 'title': 'PBS NewsHour - full episode July 31, 2017',
356                 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
357                 'duration': 3265,
358                 'thumbnail': r're:^https?://.*\.jpg$',
359             },
360             'params': {
361                 'skip_download': True,
362             },
363         },
364         {
365             'url': 'http://www.pbs.org/wgbh/roadshow/watch/episode/2105-indianapolis-hour-2/',
366             'info_dict': {
367                 'id': '2365936247',
368                 'ext': 'mp4',
369                 'title': 'Antiques Roadshow - Indianapolis, Hour 2',
370                 'description': 'md5:524b32249db55663e7231b6b8d1671a2',
371                 'duration': 3180,
372                 'thumbnail': r're:^https?://.*\.jpg$',
373             },
374             'params': {
375                 'skip_download': True,
376             },
377             'expected_warnings': ['HTTP Error 403: Forbidden'],
378         },
379         {
380             'url': 'https://www.pbs.org/wgbh/masterpiece/episodes/victoria-s2-e1/',
381             'info_dict': {
382                 'id': '3007193718',
383                 'ext': 'mp4',
384                 'title': "Victoria - A Soldier's Daughter / The Green-Eyed Monster",
385                 'description': 'md5:37efbac85e0c09b009586523ec143652',
386                 'duration': 6292,
387                 'thumbnail': r're:^https?://.*\.(?:jpg|JPG)$',
388             },
389             'params': {
390                 'skip_download': True,
391             },
392             'expected_warnings': ['HTTP Error 403: Forbidden'],
393         },
394         {
395             'url': 'https://player.pbs.org/partnerplayer/tOz9tM5ljOXQqIIWke53UA==/',
396             'info_dict': {
397                 'id': '3011407934',
398                 'ext': 'mp4',
399                 'title': 'Stories from the Stage - Road Trip',
400                 'duration': 1619,
401                 'thumbnail': r're:^https?://.*\.(?:jpg|JPG)$',
402             },
403             'params': {
404                 'skip_download': True,
405             },
406             'expected_warnings': ['HTTP Error 403: Forbidden'],
407         },
408         {
409             'url': 'http://player.pbs.org/widget/partnerplayer/2365297708/?start=0&end=0&chapterbar=false&endscreen=false&topbar=true',
410             'only_matching': True,
411         },
412         {
413             'url': 'http://watch.knpb.org/video/2365616055/',
414             'only_matching': True,
415         },
416         {
417             'url': 'https://player.pbs.org/portalplayer/3004638221/?uid=',
418             'only_matching': True,
419         }
420     ]
421     _ERRORS = {
422         101: 'We\'re sorry, but this video is not yet available.',
423         403: 'We\'re sorry, but this video is not available in your region due to right restrictions.',
424         404: 'We are experiencing technical difficulties that are preventing us from playing the video at this time. Please check back again soon.',
425         410: 'This video has expired and is no longer available for online streaming.',
426     }
427
428     def _real_initialize(self):
429         cookie = (self._download_json(
430             'http://localization.services.pbs.org/localize/auto/cookie/',
431             None, headers=self.geo_verification_headers(), fatal=False) or {}).get('cookie')
432         if cookie:
433             station = self._search_regex(r'#?s=\["([^"]+)"', cookie, 'station')
434             if station:
435                 self._set_cookie('.pbs.org', 'pbsol.station', station)
436
437     def _extract_webpage(self, url):
438         mobj = re.match(self._VALID_URL, url)
439
440         description = None
441
442         presumptive_id = mobj.group('presumptive_id')
443         display_id = presumptive_id
444         if presumptive_id:
445             webpage = self._download_webpage(url, display_id)
446
447             description = strip_or_none(self._og_search_description(
448                 webpage, default=None) or self._html_search_meta(
449                 'description', webpage, default=None))
450             upload_date = unified_strdate(self._search_regex(
451                 r'<input type="hidden" id="air_date_[0-9]+" value="([^"]+)"',
452                 webpage, 'upload date', default=None))
453
454             # tabbed frontline videos
455             MULTI_PART_REGEXES = (
456                 r'<div[^>]+class="videotab[^"]*"[^>]+vid="(\d+)"',
457                 r'<a[^>]+href=["\']#(?:video-|part)\d+["\'][^>]+data-cove[Ii]d=["\'](\d+)',
458             )
459             for p in MULTI_PART_REGEXES:
460                 tabbed_videos = orderedSet(re.findall(p, webpage))
461                 if tabbed_videos:
462                     return tabbed_videos, presumptive_id, upload_date, description
463
464             MEDIA_ID_REGEXES = [
465                 r"div\s*:\s*'videoembed'\s*,\s*mediaid\s*:\s*'(\d+)'",  # frontline video embed
466                 r'class="coveplayerid">([^<]+)<',                       # coveplayer
467                 r'<section[^>]+data-coveid="(\d+)"',                    # coveplayer from http://www.pbs.org/wgbh/frontline/film/real-csi/
468                 r'<input type="hidden" id="pbs_video_id_[0-9]+" value="([0-9]+)"/>',  # jwplayer
469                 r"(?s)window\.PBS\.playerConfig\s*=\s*{.*?id\s*:\s*'([0-9]+)',",
470                 r'<div[^>]+\bdata-cove-id=["\'](\d+)"',  # http://www.pbs.org/wgbh/roadshow/watch/episode/2105-indianapolis-hour-2/
471                 r'<iframe[^>]+\bsrc=["\'](?:https?:)?//video\.pbs\.org/widget/partnerplayer/(\d+)',  # https://www.pbs.org/wgbh/masterpiece/episodes/victoria-s2-e1/
472             ]
473
474             media_id = self._search_regex(
475                 MEDIA_ID_REGEXES, webpage, 'media ID', fatal=False, default=None)
476             if media_id:
477                 return media_id, presumptive_id, upload_date, description
478
479             # Fronline video embedded via flp
480             video_id = self._search_regex(
481                 r'videoid\s*:\s*"([\d+a-z]{7,})"', webpage, 'videoid', default=None)
482             if video_id:
483                 # pkg_id calculation is reverse engineered from
484                 # http://www.pbs.org/wgbh/pages/frontline/js/flp2012.js
485                 prg_id = self._search_regex(
486                     r'videoid\s*:\s*"([\d+a-z]{7,})"', webpage, 'videoid')[7:]
487                 if 'q' in prg_id:
488                     prg_id = prg_id.split('q')[1]
489                 prg_id = int(prg_id, 16)
490                 getdir = self._download_json(
491                     'http://www.pbs.org/wgbh/pages/frontline/.json/getdir/getdir%d.json' % prg_id,
492                     presumptive_id, 'Downloading getdir JSON',
493                     transform_source=strip_jsonp)
494                 return getdir['mid'], presumptive_id, upload_date, description
495
496             for iframe in re.findall(r'(?s)<iframe(.+?)></iframe>', webpage):
497                 url = self._search_regex(
498                     r'src=(["\'])(?P<url>.+?partnerplayer.+?)\1', iframe,
499                     'player URL', default=None, group='url')
500                 if url:
501                     break
502
503             if not url:
504                 url = self._og_search_url(webpage)
505
506             mobj = re.match(
507                 self._VALID_URL, self._proto_relative_url(url.strip()))
508
509         player_id = mobj.group('player_id')
510         if not display_id:
511             display_id = player_id
512         if player_id:
513             player_page = self._download_webpage(
514                 url, display_id, note='Downloading player page',
515                 errnote='Could not download player page')
516             video_id = self._search_regex(
517                 r'<div\s+id=["\']video_(\d+)', player_page, 'video ID',
518                 default=None)
519             if not video_id:
520                 video_info = self._extract_video_data(
521                     player_page, 'video data', display_id)
522                 video_id = compat_str(
523                     video_info.get('id') or video_info['contentID'])
524         else:
525             video_id = mobj.group('id')
526             display_id = video_id
527
528         return video_id, display_id, None, description
529
530     def _extract_video_data(self, string, name, video_id, fatal=True):
531         return self._parse_json(
532             self._search_regex(
533                 [r'(?s)PBS\.videoData\s*=\s*({.+?});\n',
534                  r'window\.videoBridge\s*=\s*({.+?});'],
535                 string, name, default='{}'),
536             video_id, transform_source=js_to_json, fatal=fatal)
537
538     def _real_extract(self, url):
539         video_id, display_id, upload_date, description = self._extract_webpage(url)
540
541         if isinstance(video_id, list):
542             entries = [self.url_result(
543                 'http://video.pbs.org/video/%s' % vid_id, 'PBS', vid_id)
544                 for vid_id in video_id]
545             return self.playlist_result(entries, display_id)
546
547         info = None
548         redirects = []
549         redirect_urls = set()
550
551         def extract_redirect_urls(info):
552             for encoding_name in ('recommended_encoding', 'alternate_encoding'):
553                 redirect = info.get(encoding_name)
554                 if not redirect:
555                     continue
556                 redirect_url = redirect.get('url')
557                 if redirect_url and redirect_url not in redirect_urls:
558                     redirects.append(redirect)
559                     redirect_urls.add(redirect_url)
560
561         chapters = []
562         # Player pages may also serve different qualities
563         for page in ('widget/partnerplayer', 'portalplayer'):
564             player = self._download_webpage(
565                 'http://player.pbs.org/%s/%s' % (page, video_id),
566                 display_id, 'Downloading %s page' % page, fatal=False)
567             if player:
568                 video_info = self._extract_video_data(
569                     player, '%s video data' % page, display_id, fatal=False)
570                 if video_info:
571                     extract_redirect_urls(video_info)
572                     if not info:
573                         info = video_info
574                 if not chapters:
575                     raw_chapters = video_info.get('chapters') or []
576                     if not raw_chapters:
577                         for chapter_data in re.findall(r'(?s)chapters\.push\(({.*?})\)', player):
578                             chapter = self._parse_json(chapter_data, video_id, js_to_json, fatal=False)
579                             if not chapter:
580                                 continue
581                             raw_chapters.append(chapter)
582                     for chapter in raw_chapters:
583                         start_time = float_or_none(chapter.get('start_time'), 1000)
584                         duration = float_or_none(chapter.get('duration'), 1000)
585                         if start_time is None or duration is None:
586                             continue
587                         chapters.append({
588                             'start_time': start_time,
589                             'end_time': start_time + duration,
590                             'title': chapter.get('title'),
591                         })
592
593         formats = []
594         http_url = None
595         for num, redirect in enumerate(redirects):
596             redirect_id = redirect.get('eeid')
597
598             redirect_info = self._download_json(
599                 '%s?format=json' % redirect['url'], display_id,
600                 'Downloading %s video url info' % (redirect_id or num),
601                 headers=self.geo_verification_headers())
602
603             if redirect_info['status'] == 'error':
604                 message = self._ERRORS.get(
605                     redirect_info['http_code'], redirect_info['message'])
606                 if redirect_info['http_code'] == 403:
607                     self.raise_geo_restricted(
608                         msg=message, countries=self._GEO_COUNTRIES)
609                 raise ExtractorError(
610                     '%s said: %s' % (self.IE_NAME, message), expected=True)
611
612             format_url = redirect_info.get('url')
613             if not format_url:
614                 continue
615
616             if determine_ext(format_url) == 'm3u8':
617                 formats.extend(self._extract_m3u8_formats(
618                     format_url, display_id, 'mp4', m3u8_id='hls', fatal=False))
619             else:
620                 formats.append({
621                     'url': format_url,
622                     'format_id': redirect_id,
623                 })
624                 if re.search(r'^https?://.*(?:\d+k|baseline)', format_url):
625                     http_url = format_url
626         self._remove_duplicate_formats(formats)
627         m3u8_formats = list(filter(
628             lambda f: f.get('protocol') == 'm3u8' and f.get('vcodec') != 'none',
629             formats))
630         if http_url:
631             for m3u8_format in m3u8_formats:
632                 bitrate = self._search_regex(r'(\d+)k', m3u8_format['url'], 'bitrate', default=None)
633                 # Lower qualities (150k and 192k) are not available as HTTP formats (see [1]),
634                 # we won't try extracting them.
635                 # Since summer 2016 higher quality formats (4500k and 6500k) are also available
636                 # albeit they are not documented in [2].
637                 # 1. https://github.com/rg3/youtube-dl/commit/cbc032c8b70a038a69259378c92b4ba97b42d491#commitcomment-17313656
638                 # 2. https://projects.pbs.org/confluence/display/coveapi/COVE+Video+Specifications
639                 if not bitrate or int(bitrate) < 400:
640                     continue
641                 f_url = re.sub(r'\d+k|baseline', bitrate + 'k', http_url)
642                 # This may produce invalid links sometimes (e.g.
643                 # http://www.pbs.org/wgbh/frontline/film/suicide-plan)
644                 if not self._is_valid_url(f_url, display_id, 'http-%sk video' % bitrate):
645                     continue
646                 f = m3u8_format.copy()
647                 f.update({
648                     'url': f_url,
649                     'format_id': m3u8_format['format_id'].replace('hls', 'http'),
650                     'protocol': 'http',
651                 })
652                 formats.append(f)
653         self._sort_formats(formats)
654
655         rating_str = info.get('rating')
656         if rating_str is not None:
657             rating_str = rating_str.rpartition('-')[2]
658         age_limit = US_RATINGS.get(rating_str)
659
660         subtitles = {}
661         closed_captions_url = info.get('closed_captions_url')
662         if closed_captions_url:
663             subtitles['en'] = [{
664                 'ext': 'ttml',
665                 'url': closed_captions_url,
666             }]
667             mobj = re.search(r'/(\d+)_Encoded\.dfxp', closed_captions_url)
668             if mobj:
669                 ttml_caption_suffix, ttml_caption_id = mobj.group(0, 1)
670                 ttml_caption_id = int(ttml_caption_id)
671                 subtitles['en'].extend([{
672                     'url': closed_captions_url.replace(
673                         ttml_caption_suffix, '/%d_Encoded.srt' % (ttml_caption_id + 1)),
674                     'ext': 'srt',
675                 }, {
676                     'url': closed_captions_url.replace(
677                         ttml_caption_suffix, '/%d_Encoded.vtt' % (ttml_caption_id + 2)),
678                     'ext': 'vtt',
679                 }])
680
681         # info['title'] is often incomplete (e.g. 'Full Episode', 'Episode 5', etc)
682         # Try turning it to 'program - title' naming scheme if possible
683         alt_title = info.get('program', {}).get('title')
684         if alt_title:
685             info['title'] = alt_title + ' - ' + re.sub(r'^' + alt_title + r'[\s\-:]+', '', info['title'])
686
687         description = info.get('description') or info.get(
688             'program', {}).get('description') or description
689
690         return {
691             'id': video_id,
692             'display_id': display_id,
693             'title': info['title'],
694             'description': description,
695             'thumbnail': info.get('image_url'),
696             'duration': int_or_none(info.get('duration')),
697             'age_limit': age_limit,
698             'upload_date': upload_date,
699             'formats': formats,
700             'subtitles': subtitles,
701             'chapters': chapters,
702         }