[npo] Relax _VALID_URL for zapp.nl
[youtube-dl] / youtube_dl / extractor / npo.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import compat_HTTPError
7 from ..utils import (
8     fix_xml_ampersands,
9     orderedSet,
10     parse_duration,
11     qualities,
12     strip_jsonp,
13     unified_strdate,
14     ExtractorError,
15 )
16
17
18 class NPOBaseIE(InfoExtractor):
19     def _get_token(self, video_id):
20         token_page = self._download_webpage(
21             'http://ida.omroep.nl/npoplayer/i.js',
22             video_id, note='Downloading token')
23         token = self._search_regex(
24             r'npoplayer\.token = "(.+?)"', token_page, 'token')
25         # Decryption algorithm extracted from http://npoplayer.omroep.nl/csjs/npoplayer-min.js
26         token_l = list(token)
27         first = second = None
28         for i in range(5, len(token_l) - 4):
29             if token_l[i].isdigit():
30                 if first is None:
31                     first = i
32                 elif second is None:
33                     second = i
34         if first is None or second is None:
35             first = 12
36             second = 13
37
38         token_l[first], token_l[second] = token_l[second], token_l[first]
39
40         return ''.join(token_l)
41
42
43 class NPOIE(NPOBaseIE):
44     IE_NAME = 'npo'
45     IE_DESC = 'npo.nl and ntr.nl'
46     _VALID_URL = r'''(?x)
47                     (?:
48                         npo:|
49                         https?://
50                             (?:www\.)?
51                             (?:
52                                 npo\.nl/(?!live|radio)(?:[^/]+/){2}|
53                                 ntr\.nl/(?:[^/]+/){2,}|
54                                 omroepwnl\.nl/video/fragment/[^/]+__|
55                                 zapp\.nl/[^/]+/[^/]+/
56                             )
57                         )
58                         (?P<id>[^/?#]+)
59                 '''
60
61     _TESTS = [
62         {
63             'url': 'http://www.npo.nl/nieuwsuur/22-06-2014/VPWON_1220719',
64             'md5': '4b3f9c429157ec4775f2c9cb7b911016',
65             'info_dict': {
66                 'id': 'VPWON_1220719',
67                 'ext': 'm4v',
68                 'title': 'Nieuwsuur',
69                 'description': 'Dagelijks tussen tien en elf: nieuws, sport en achtergronden.',
70                 'upload_date': '20140622',
71             },
72         },
73         {
74             'url': 'http://www.npo.nl/de-mega-mike-mega-thomas-show/27-02-2009/VARA_101191800',
75             'md5': 'da50a5787dbfc1603c4ad80f31c5120b',
76             'info_dict': {
77                 'id': 'VARA_101191800',
78                 'ext': 'm4v',
79                 'title': 'De Mega Mike & Mega Thomas show: The best of.',
80                 'description': 'md5:3b74c97fc9d6901d5a665aac0e5400f4',
81                 'upload_date': '20090227',
82                 'duration': 2400,
83             },
84         },
85         {
86             'url': 'http://www.npo.nl/tegenlicht/25-02-2013/VPWON_1169289',
87             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
88             'info_dict': {
89                 'id': 'VPWON_1169289',
90                 'ext': 'm4v',
91                 'title': 'Tegenlicht: De toekomst komt uit Afrika',
92                 'description': 'md5:52cf4eefbc96fffcbdc06d024147abea',
93                 'upload_date': '20130225',
94                 'duration': 3000,
95             },
96         },
97         {
98             'url': 'http://www.npo.nl/de-nieuwe-mens-deel-1/21-07-2010/WO_VPRO_043706',
99             'info_dict': {
100                 'id': 'WO_VPRO_043706',
101                 'ext': 'wmv',
102                 'title': 'De nieuwe mens - Deel 1',
103                 'description': 'md5:518ae51ba1293ffb80d8d8ce90b74e4b',
104                 'duration': 4680,
105             },
106             'params': {
107                 # mplayer mms download
108                 'skip_download': True,
109             }
110         },
111         # non asf in streams
112         {
113             'url': 'http://www.npo.nl/hoe-gaat-europa-verder-na-parijs/10-01-2015/WO_NOS_762771',
114             'md5': 'b3da13de374cbe2d5332a7e910bef97f',
115             'info_dict': {
116                 'id': 'WO_NOS_762771',
117                 'ext': 'mp4',
118                 'title': 'Hoe gaat Europa verder na Parijs?',
119             },
120         },
121         {
122             'url': 'http://www.ntr.nl/Aap-Poot-Pies/27/detail/Aap-poot-pies/VPWON_1233944#content',
123             'md5': '01c6a2841675995da1f0cf776f03a9c3',
124             'info_dict': {
125                 'id': 'VPWON_1233944',
126                 'ext': 'm4v',
127                 'title': 'Aap, poot, pies',
128                 'description': 'md5:c9c8005d1869ae65b858e82c01a91fde',
129                 'upload_date': '20150508',
130                 'duration': 599,
131             },
132         },
133         {
134             'url': 'http://www.omroepwnl.nl/video/fragment/vandaag-de-dag-verkiezingen__POMS_WNL_853698',
135             'md5': 'd30cd8417b8b9bca1fdff27428860d08',
136             'info_dict': {
137                 'id': 'POW_00996502',
138                 'ext': 'm4v',
139                 'title': '''"Dit is wel een 'landslide'..."''',
140                 'description': 'md5:f8d66d537dfb641380226e31ca57b8e8',
141                 'upload_date': '20150508',
142                 'duration': 462,
143             },
144         },
145         {
146             'url': 'http://www.zapp.nl/de-bzt-show/gemist/KN_1687547',
147             'only_matching': True,
148         },
149         {
150             'url': 'http://www.zapp.nl/de-bzt-show/filmpjes/POMS_KN_7315118',
151             'only_matching': True,
152         },
153         {
154             'url': 'http://www.zapp.nl/beste-vrienden-quiz/extra-video-s/WO_NTR_1067990',
155             'only_matching': True,
156         }
157     ]
158
159     def _real_extract(self, url):
160         video_id = self._match_id(url)
161         return self._get_info(video_id)
162
163     def _get_info(self, video_id):
164         metadata = self._download_json(
165             'http://e.omroep.nl/metadata/%s' % video_id,
166             video_id,
167             # We have to remove the javascript callback
168             transform_source=strip_jsonp,
169         )
170
171         # For some videos actual video id (prid) is different (e.g. for
172         # http://www.omroepwnl.nl/video/fragment/vandaag-de-dag-verkiezingen__POMS_WNL_853698
173         # video id is POMS_WNL_853698 but prid is POW_00996502)
174         video_id = metadata.get('prid') or video_id
175
176         # titel is too generic in some cases so utilize aflevering_titel as well
177         # when available (e.g. http://tegenlicht.vpro.nl/afleveringen/2014-2015/access-to-africa.html)
178         title = metadata['titel']
179         sub_title = metadata.get('aflevering_titel')
180         if sub_title and sub_title != title:
181             title += ': %s' % sub_title
182
183         token = self._get_token(video_id)
184
185         formats = []
186
187         pubopties = metadata.get('pubopties')
188         if pubopties:
189             quality = qualities(['adaptive', 'wmv_sb', 'h264_sb', 'wmv_bb', 'h264_bb', 'wvc1_std', 'h264_std'])
190             for format_id in pubopties:
191                 format_info = self._download_json(
192                     'http://ida.omroep.nl/odi/?prid=%s&puboptions=%s&adaptive=yes&token=%s'
193                     % (video_id, format_id, token),
194                     video_id, 'Downloading %s JSON' % format_id)
195                 if format_info.get('error_code', 0) or format_info.get('errorcode', 0):
196                     continue
197                 streams = format_info.get('streams')
198                 if streams:
199                     try:
200                         video_info = self._download_json(
201                             streams[0] + '&type=json',
202                             video_id, 'Downloading %s stream JSON' % format_id)
203                     except ExtractorError as ee:
204                         if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
205                             error = (self._parse_json(ee.cause.read().decode(), video_id, fatal=False) or {}).get('errorstring')
206                             if error:
207                                 raise ExtractorError(error, expected=True)
208                         raise
209                 else:
210                     video_info = format_info
211                 video_url = video_info.get('url')
212                 if not video_url:
213                     continue
214                 if format_id == 'adaptive':
215                     formats.extend(self._extract_m3u8_formats(video_url, video_id, 'mp4'))
216                 else:
217                     formats.append({
218                         'url': video_url,
219                         'format_id': format_id,
220                         'quality': quality(format_id),
221                     })
222
223         streams = metadata.get('streams')
224         if streams:
225             for i, stream in enumerate(streams):
226                 stream_url = stream.get('url')
227                 if not stream_url:
228                     continue
229                 if '.asf' not in stream_url:
230                     formats.append({
231                         'url': stream_url,
232                         'quality': stream.get('kwaliteit'),
233                     })
234                     continue
235                 asx = self._download_xml(
236                     stream_url, video_id,
237                     'Downloading stream %d ASX playlist' % i,
238                     transform_source=fix_xml_ampersands)
239                 ref = asx.find('./ENTRY/Ref')
240                 if ref is None:
241                     continue
242                 video_url = ref.get('href')
243                 if not video_url:
244                     continue
245                 formats.append({
246                     'url': video_url,
247                     'ext': stream.get('formaat', 'asf'),
248                     'quality': stream.get('kwaliteit'),
249                 })
250
251         self._sort_formats(formats)
252
253         subtitles = {}
254         if metadata.get('tt888') == 'ja':
255             subtitles['nl'] = [{
256                 'ext': 'vtt',
257                 'url': 'http://tt888.omroep.nl/tt888/%s' % video_id,
258             }]
259
260         return {
261             'id': video_id,
262             'title': title,
263             'description': metadata.get('info'),
264             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
265             'upload_date': unified_strdate(metadata.get('gidsdatum')),
266             'duration': parse_duration(metadata.get('tijdsduur')),
267             'formats': formats,
268             'subtitles': subtitles,
269         }
270
271
272 class NPOLiveIE(NPOBaseIE):
273     IE_NAME = 'npo.nl:live'
274     _VALID_URL = r'https?://(?:www\.)?npo\.nl/live/(?P<id>.+)'
275
276     _TEST = {
277         'url': 'http://www.npo.nl/live/npo-1',
278         'info_dict': {
279             'id': 'LI_NEDERLAND1_136692',
280             'display_id': 'npo-1',
281             'ext': 'mp4',
282             'title': 're:^Nederland 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
283             'description': 'Livestream',
284             'is_live': True,
285         },
286         'params': {
287             'skip_download': True,
288         }
289     }
290
291     def _real_extract(self, url):
292         display_id = self._match_id(url)
293
294         webpage = self._download_webpage(url, display_id)
295
296         live_id = self._search_regex(
297             r'data-prid="([^"]+)"', webpage, 'live id')
298
299         metadata = self._download_json(
300             'http://e.omroep.nl/metadata/%s' % live_id,
301             display_id, transform_source=strip_jsonp)
302
303         token = self._get_token(display_id)
304
305         formats = []
306
307         streams = metadata.get('streams')
308         if streams:
309             for stream in streams:
310                 stream_type = stream.get('type').lower()
311                 # smooth streaming is not supported
312                 if stream_type in ['ss', 'ms']:
313                     continue
314                 stream_info = self._download_json(
315                     'http://ida.omroep.nl/aapi/?stream=%s&token=%s&type=jsonp'
316                     % (stream.get('url'), token),
317                     display_id, 'Downloading %s JSON' % stream_type)
318                 if stream_info.get('error_code', 0) or stream_info.get('errorcode', 0):
319                     continue
320                 stream_url = self._download_json(
321                     stream_info['stream'], display_id,
322                     'Downloading %s URL' % stream_type,
323                     'Unable to download %s URL' % stream_type,
324                     transform_source=strip_jsonp, fatal=False)
325                 if not stream_url:
326                     continue
327                 if stream_type == 'hds':
328                     f4m_formats = self._extract_f4m_formats(stream_url, display_id)
329                     # f4m downloader downloads only piece of live stream
330                     for f4m_format in f4m_formats:
331                         f4m_format['preference'] = -1
332                     formats.extend(f4m_formats)
333                 elif stream_type == 'hls':
334                     formats.extend(self._extract_m3u8_formats(stream_url, display_id, 'mp4'))
335                 else:
336                     formats.append({
337                         'url': stream_url,
338                         'preference': -10,
339                     })
340
341         self._sort_formats(formats)
342
343         return {
344             'id': live_id,
345             'display_id': display_id,
346             'title': self._live_title(metadata['titel']),
347             'description': metadata['info'],
348             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
349             'formats': formats,
350             'is_live': True,
351         }
352
353
354 class NPORadioIE(InfoExtractor):
355     IE_NAME = 'npo.nl:radio'
356     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/(?P<id>[^/]+)/?$'
357
358     _TEST = {
359         'url': 'http://www.npo.nl/radio/radio-1',
360         'info_dict': {
361             'id': 'radio-1',
362             'ext': 'mp3',
363             'title': 're:^NPO Radio 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
364             'is_live': True,
365         },
366         'params': {
367             'skip_download': True,
368         }
369     }
370
371     @staticmethod
372     def _html_get_attribute_regex(attribute):
373         return r'{0}\s*=\s*\'([^\']+)\''.format(attribute)
374
375     def _real_extract(self, url):
376         video_id = self._match_id(url)
377
378         webpage = self._download_webpage(url, video_id)
379
380         title = self._html_search_regex(
381             self._html_get_attribute_regex('data-channel'), webpage, 'title')
382
383         stream = self._parse_json(
384             self._html_search_regex(self._html_get_attribute_regex('data-streams'), webpage, 'data-streams'),
385             video_id)
386
387         codec = stream.get('codec')
388
389         return {
390             'id': video_id,
391             'url': stream['url'],
392             'title': self._live_title(title),
393             'acodec': codec,
394             'ext': codec,
395             'is_live': True,
396         }
397
398
399 class NPORadioFragmentIE(InfoExtractor):
400     IE_NAME = 'npo.nl:radio:fragment'
401     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/[^/]+/fragment/(?P<id>\d+)'
402
403     _TEST = {
404         'url': 'http://www.npo.nl/radio/radio-5/fragment/174356',
405         'md5': 'dd8cc470dad764d0fdc70a9a1e2d18c2',
406         'info_dict': {
407             'id': '174356',
408             'ext': 'mp3',
409             'title': 'Jubileumconcert Willeke Alberti',
410         },
411     }
412
413     def _real_extract(self, url):
414         audio_id = self._match_id(url)
415
416         webpage = self._download_webpage(url, audio_id)
417
418         title = self._html_search_regex(
419             r'href="/radio/[^/]+/fragment/%s" title="([^"]+)"' % audio_id,
420             webpage, 'title')
421
422         audio_url = self._search_regex(
423             r"data-streams='([^']+)'", webpage, 'audio url')
424
425         return {
426             'id': audio_id,
427             'url': audio_url,
428             'title': title,
429         }
430
431
432 class NPODataMidEmbedIE(InfoExtractor):
433     def _real_extract(self, url):
434         display_id = self._match_id(url)
435         webpage = self._download_webpage(url, display_id)
436         video_id = self._search_regex(
437             r'data-mid=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video_id', group='id')
438         return {
439             '_type': 'url_transparent',
440             'ie_key': 'NPO',
441             'url': 'npo:%s' % video_id,
442             'display_id': display_id
443         }
444
445
446 class SchoolTVIE(NPODataMidEmbedIE):
447     IE_NAME = 'schooltv'
448     _VALID_URL = r'https?://(?:www\.)?schooltv\.nl/video/(?P<id>[^/?#&]+)'
449
450     _TEST = {
451         'url': 'http://www.schooltv.nl/video/ademhaling-de-hele-dag-haal-je-adem-maar-wat-gebeurt-er-dan-eigenlijk-in-je-lichaam/',
452         'info_dict': {
453             'id': 'WO_NTR_429477',
454             'display_id': 'ademhaling-de-hele-dag-haal-je-adem-maar-wat-gebeurt-er-dan-eigenlijk-in-je-lichaam',
455             'title': 'Ademhaling: De hele dag haal je adem. Maar wat gebeurt er dan eigenlijk in je lichaam?',
456             'ext': 'mp4',
457             'description': 'md5:abfa0ff690adb73fd0297fd033aaa631'
458         },
459         'params': {
460             # Skip because of m3u8 download
461             'skip_download': True
462         }
463     }
464
465
466 class HetKlokhuisIE(NPODataMidEmbedIE):
467     IE_NAME = 'hetklokhuis'
468     _VALID_URL = r'https?://(?:www\.)?hetklokhuis.nl/[^/]+/\d+/(?P<id>[^/?#&]+)'
469
470     _TEST = {
471         'url': 'http://hetklokhuis.nl/tv-uitzending/3471/Zwaartekrachtsgolven',
472         'info_dict': {
473             'id': 'VPWON_1260528',
474             'display_id': 'Zwaartekrachtsgolven',
475             'ext': 'm4v',
476             'title': 'Het Klokhuis: Zwaartekrachtsgolven',
477             'description': 'md5:c94f31fb930d76c2efa4a4a71651dd48',
478             'upload_date': '20170223',
479         },
480         'params': {
481             'skip_download': True
482         }
483     }
484
485
486 class NPOPlaylistBaseIE(NPOIE):
487     def _real_extract(self, url):
488         playlist_id = self._match_id(url)
489
490         webpage = self._download_webpage(url, playlist_id)
491
492         entries = [
493             self.url_result('npo:%s' % video_id if not video_id.startswith('http') else video_id)
494             for video_id in orderedSet(re.findall(self._PLAYLIST_ENTRY_RE, webpage))
495         ]
496
497         playlist_title = self._html_search_regex(
498             self._PLAYLIST_TITLE_RE, webpage, 'playlist title',
499             default=None) or self._og_search_title(webpage)
500
501         return self.playlist_result(entries, playlist_id, playlist_title)
502
503
504 class VPROIE(NPOPlaylistBaseIE):
505     IE_NAME = 'vpro'
506     _VALID_URL = r'https?://(?:www\.)?(?:(?:tegenlicht\.)?vpro|2doc)\.nl/(?:[^/]+/)*(?P<id>[^/]+)\.html'
507     _PLAYLIST_TITLE_RE = (r'<h1[^>]+class=["\'].*?\bmedia-platform-title\b.*?["\'][^>]*>([^<]+)',
508                           r'<h5[^>]+class=["\'].*?\bmedia-platform-subtitle\b.*?["\'][^>]*>([^<]+)')
509     _PLAYLIST_ENTRY_RE = r'data-media-id="([^"]+)"'
510
511     _TESTS = [
512         {
513             'url': 'http://tegenlicht.vpro.nl/afleveringen/2012-2013/de-toekomst-komt-uit-afrika.html',
514             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
515             'info_dict': {
516                 'id': 'VPWON_1169289',
517                 'ext': 'm4v',
518                 'title': 'De toekomst komt uit Afrika',
519                 'description': 'md5:52cf4eefbc96fffcbdc06d024147abea',
520                 'upload_date': '20130225',
521             },
522             'skip': 'Video gone',
523         },
524         {
525             'url': 'http://www.vpro.nl/programmas/2doc/2015/sergio-herman.html',
526             'info_dict': {
527                 'id': 'sergio-herman',
528                 'title': 'sergio herman: fucking perfect',
529             },
530             'playlist_count': 2,
531         },
532         {
533             # playlist with youtube embed
534             'url': 'http://www.vpro.nl/programmas/2doc/2015/education-education.html',
535             'info_dict': {
536                 'id': 'education-education',
537                 'title': 'education education',
538             },
539             'playlist_count': 2,
540         },
541         {
542             'url': 'http://www.2doc.nl/documentaires/series/2doc/2015/oktober/de-tegenprestatie.html',
543             'info_dict': {
544                 'id': 'de-tegenprestatie',
545                 'title': 'De Tegenprestatie',
546             },
547             'playlist_count': 2,
548         }, {
549             'url': 'http://www.2doc.nl/speel~VARA_101375237~mh17-het-verdriet-van-nederland~.html',
550             'info_dict': {
551                 'id': 'VARA_101375237',
552                 'ext': 'm4v',
553                 'title': 'MH17: Het verdriet van Nederland',
554                 'description': 'md5:09e1a37c1fdb144621e22479691a9f18',
555                 'upload_date': '20150716',
556             },
557             'params': {
558                 # Skip because of m3u8 download
559                 'skip_download': True
560             },
561         }
562     ]
563
564
565 class WNLIE(NPOPlaylistBaseIE):
566     IE_NAME = 'wnl'
567     _VALID_URL = r'https?://(?:www\.)?omroepwnl\.nl/video/detail/(?P<id>[^/]+)__\d+'
568     _PLAYLIST_TITLE_RE = r'(?s)<h1[^>]+class="subject"[^>]*>(.+?)</h1>'
569     _PLAYLIST_ENTRY_RE = r'<a[^>]+href="([^"]+)"[^>]+class="js-mid"[^>]*>Deel \d+'
570
571     _TESTS = [{
572         'url': 'http://www.omroepwnl.nl/video/detail/vandaag-de-dag-6-mei__060515',
573         'info_dict': {
574             'id': 'vandaag-de-dag-6-mei',
575             'title': 'Vandaag de Dag 6 mei',
576         },
577         'playlist_count': 4,
578     }]
579
580
581 class AndereTijdenIE(NPOPlaylistBaseIE):
582     IE_NAME = 'anderetijden'
583     _VALID_URL = r'https?://(?:www\.)?anderetijden\.nl/programma/(?:[^/]+/)+(?P<id>[^/?#&]+)'
584     _PLAYLIST_TITLE_RE = r'(?s)<h1[^>]+class=["\'].*?\bpage-title\b.*?["\'][^>]*>(.+?)</h1>'
585     _PLAYLIST_ENTRY_RE = r'<figure[^>]+class=["\']episode-container episode-page["\'][^>]+data-prid=["\'](.+?)["\']'
586
587     _TESTS = [{
588         'url': 'http://anderetijden.nl/programma/1/Andere-Tijden/aflevering/676/Duitse-soldaten-over-de-Slag-bij-Arnhem',
589         'info_dict': {
590             'id': 'Duitse-soldaten-over-de-Slag-bij-Arnhem',
591             'title': 'Duitse soldaten over de Slag bij Arnhem',
592         },
593         'playlist_count': 3,
594     }]