[hetklokhuis] Fix IE_NAME
[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/[^/]+/(?:gemist|filmpjes)/
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
155     def _real_extract(self, url):
156         video_id = self._match_id(url)
157         return self._get_info(video_id)
158
159     def _get_info(self, video_id):
160         metadata = self._download_json(
161             'http://e.omroep.nl/metadata/%s' % video_id,
162             video_id,
163             # We have to remove the javascript callback
164             transform_source=strip_jsonp,
165         )
166
167         # For some videos actual video id (prid) is different (e.g. for
168         # http://www.omroepwnl.nl/video/fragment/vandaag-de-dag-verkiezingen__POMS_WNL_853698
169         # video id is POMS_WNL_853698 but prid is POW_00996502)
170         video_id = metadata.get('prid') or video_id
171
172         # titel is too generic in some cases so utilize aflevering_titel as well
173         # when available (e.g. http://tegenlicht.vpro.nl/afleveringen/2014-2015/access-to-africa.html)
174         title = metadata['titel']
175         sub_title = metadata.get('aflevering_titel')
176         if sub_title and sub_title != title:
177             title += ': %s' % sub_title
178
179         token = self._get_token(video_id)
180
181         formats = []
182
183         pubopties = metadata.get('pubopties')
184         if pubopties:
185             quality = qualities(['adaptive', 'wmv_sb', 'h264_sb', 'wmv_bb', 'h264_bb', 'wvc1_std', 'h264_std'])
186             for format_id in pubopties:
187                 format_info = self._download_json(
188                     'http://ida.omroep.nl/odi/?prid=%s&puboptions=%s&adaptive=yes&token=%s'
189                     % (video_id, format_id, token),
190                     video_id, 'Downloading %s JSON' % format_id)
191                 if format_info.get('error_code', 0) or format_info.get('errorcode', 0):
192                     continue
193                 streams = format_info.get('streams')
194                 if streams:
195                     try:
196                         video_info = self._download_json(
197                             streams[0] + '&type=json',
198                             video_id, 'Downloading %s stream JSON' % format_id)
199                     except ExtractorError as ee:
200                         if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
201                             error = (self._parse_json(ee.cause.read().decode(), video_id, fatal=False) or {}).get('errorstring')
202                             if error:
203                                 raise ExtractorError(error, expected=True)
204                         raise
205                 else:
206                     video_info = format_info
207                 video_url = video_info.get('url')
208                 if not video_url:
209                     continue
210                 if format_id == 'adaptive':
211                     formats.extend(self._extract_m3u8_formats(video_url, video_id, 'mp4'))
212                 else:
213                     formats.append({
214                         'url': video_url,
215                         'format_id': format_id,
216                         'quality': quality(format_id),
217                     })
218
219         streams = metadata.get('streams')
220         if streams:
221             for i, stream in enumerate(streams):
222                 stream_url = stream.get('url')
223                 if not stream_url:
224                     continue
225                 if '.asf' not in stream_url:
226                     formats.append({
227                         'url': stream_url,
228                         'quality': stream.get('kwaliteit'),
229                     })
230                     continue
231                 asx = self._download_xml(
232                     stream_url, video_id,
233                     'Downloading stream %d ASX playlist' % i,
234                     transform_source=fix_xml_ampersands)
235                 ref = asx.find('./ENTRY/Ref')
236                 if ref is None:
237                     continue
238                 video_url = ref.get('href')
239                 if not video_url:
240                     continue
241                 formats.append({
242                     'url': video_url,
243                     'ext': stream.get('formaat', 'asf'),
244                     'quality': stream.get('kwaliteit'),
245                 })
246
247         self._sort_formats(formats)
248
249         subtitles = {}
250         if metadata.get('tt888') == 'ja':
251             subtitles['nl'] = [{
252                 'ext': 'vtt',
253                 'url': 'http://tt888.omroep.nl/tt888/%s' % video_id,
254             }]
255
256         return {
257             'id': video_id,
258             'title': title,
259             'description': metadata.get('info'),
260             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
261             'upload_date': unified_strdate(metadata.get('gidsdatum')),
262             'duration': parse_duration(metadata.get('tijdsduur')),
263             'formats': formats,
264             'subtitles': subtitles,
265         }
266
267
268 class NPOLiveIE(NPOBaseIE):
269     IE_NAME = 'npo.nl:live'
270     _VALID_URL = r'https?://(?:www\.)?npo\.nl/live/(?P<id>.+)'
271
272     _TEST = {
273         'url': 'http://www.npo.nl/live/npo-1',
274         'info_dict': {
275             'id': 'LI_NEDERLAND1_136692',
276             'display_id': 'npo-1',
277             'ext': 'mp4',
278             'title': 're:^Nederland 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
279             'description': 'Livestream',
280             'is_live': True,
281         },
282         'params': {
283             'skip_download': True,
284         }
285     }
286
287     def _real_extract(self, url):
288         display_id = self._match_id(url)
289
290         webpage = self._download_webpage(url, display_id)
291
292         live_id = self._search_regex(
293             r'data-prid="([^"]+)"', webpage, 'live id')
294
295         metadata = self._download_json(
296             'http://e.omroep.nl/metadata/%s' % live_id,
297             display_id, transform_source=strip_jsonp)
298
299         token = self._get_token(display_id)
300
301         formats = []
302
303         streams = metadata.get('streams')
304         if streams:
305             for stream in streams:
306                 stream_type = stream.get('type').lower()
307                 # smooth streaming is not supported
308                 if stream_type in ['ss', 'ms']:
309                     continue
310                 stream_info = self._download_json(
311                     'http://ida.omroep.nl/aapi/?stream=%s&token=%s&type=jsonp'
312                     % (stream.get('url'), token),
313                     display_id, 'Downloading %s JSON' % stream_type)
314                 if stream_info.get('error_code', 0) or stream_info.get('errorcode', 0):
315                     continue
316                 stream_url = self._download_json(
317                     stream_info['stream'], display_id,
318                     'Downloading %s URL' % stream_type,
319                     'Unable to download %s URL' % stream_type,
320                     transform_source=strip_jsonp, fatal=False)
321                 if not stream_url:
322                     continue
323                 if stream_type == 'hds':
324                     f4m_formats = self._extract_f4m_formats(stream_url, display_id)
325                     # f4m downloader downloads only piece of live stream
326                     for f4m_format in f4m_formats:
327                         f4m_format['preference'] = -1
328                     formats.extend(f4m_formats)
329                 elif stream_type == 'hls':
330                     formats.extend(self._extract_m3u8_formats(stream_url, display_id, 'mp4'))
331                 else:
332                     formats.append({
333                         'url': stream_url,
334                         'preference': -10,
335                     })
336
337         self._sort_formats(formats)
338
339         return {
340             'id': live_id,
341             'display_id': display_id,
342             'title': self._live_title(metadata['titel']),
343             'description': metadata['info'],
344             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
345             'formats': formats,
346             'is_live': True,
347         }
348
349
350 class NPORadioIE(InfoExtractor):
351     IE_NAME = 'npo.nl:radio'
352     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/(?P<id>[^/]+)/?$'
353
354     _TEST = {
355         'url': 'http://www.npo.nl/radio/radio-1',
356         'info_dict': {
357             'id': 'radio-1',
358             'ext': 'mp3',
359             'title': 're:^NPO Radio 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
360             'is_live': True,
361         },
362         'params': {
363             'skip_download': True,
364         }
365     }
366
367     @staticmethod
368     def _html_get_attribute_regex(attribute):
369         return r'{0}\s*=\s*\'([^\']+)\''.format(attribute)
370
371     def _real_extract(self, url):
372         video_id = self._match_id(url)
373
374         webpage = self._download_webpage(url, video_id)
375
376         title = self._html_search_regex(
377             self._html_get_attribute_regex('data-channel'), webpage, 'title')
378
379         stream = self._parse_json(
380             self._html_search_regex(self._html_get_attribute_regex('data-streams'), webpage, 'data-streams'),
381             video_id)
382
383         codec = stream.get('codec')
384
385         return {
386             'id': video_id,
387             'url': stream['url'],
388             'title': self._live_title(title),
389             'acodec': codec,
390             'ext': codec,
391             'is_live': True,
392         }
393
394
395 class NPORadioFragmentIE(InfoExtractor):
396     IE_NAME = 'npo.nl:radio:fragment'
397     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/[^/]+/fragment/(?P<id>\d+)'
398
399     _TEST = {
400         'url': 'http://www.npo.nl/radio/radio-5/fragment/174356',
401         'md5': 'dd8cc470dad764d0fdc70a9a1e2d18c2',
402         'info_dict': {
403             'id': '174356',
404             'ext': 'mp3',
405             'title': 'Jubileumconcert Willeke Alberti',
406         },
407     }
408
409     def _real_extract(self, url):
410         audio_id = self._match_id(url)
411
412         webpage = self._download_webpage(url, audio_id)
413
414         title = self._html_search_regex(
415             r'href="/radio/[^/]+/fragment/%s" title="([^"]+)"' % audio_id,
416             webpage, 'title')
417
418         audio_url = self._search_regex(
419             r"data-streams='([^']+)'", webpage, 'audio url')
420
421         return {
422             'id': audio_id,
423             'url': audio_url,
424             'title': title,
425         }
426
427
428 class NPODataMidEmbedIE(InfoExtractor):
429     def _real_extract(self, url):
430         display_id = self._match_id(url)
431         webpage = self._download_webpage(url, display_id)
432         video_id = self._search_regex(
433             r'data-mid=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video_id', group='id')
434         return {
435             '_type': 'url_transparent',
436             'ie_key': 'NPO',
437             'url': 'npo:%s' % video_id,
438             'display_id': display_id
439         }
440
441
442 class SchoolTVIE(NPODataMidEmbedIE):
443     IE_NAME = 'schooltv'
444     _VALID_URL = r'https?://(?:www\.)?schooltv\.nl/video/(?P<id>[^/?#&]+)'
445
446     _TEST = {
447         'url': 'http://www.schooltv.nl/video/ademhaling-de-hele-dag-haal-je-adem-maar-wat-gebeurt-er-dan-eigenlijk-in-je-lichaam/',
448         'info_dict': {
449             'id': 'WO_NTR_429477',
450             'display_id': 'ademhaling-de-hele-dag-haal-je-adem-maar-wat-gebeurt-er-dan-eigenlijk-in-je-lichaam',
451             'title': 'Ademhaling: De hele dag haal je adem. Maar wat gebeurt er dan eigenlijk in je lichaam?',
452             'ext': 'mp4',
453             'description': 'md5:abfa0ff690adb73fd0297fd033aaa631'
454         },
455         'params': {
456             # Skip because of m3u8 download
457             'skip_download': True
458         }
459     }
460
461
462 class HetKlokhuisIE(NPODataMidEmbedIE):
463     IE_NAME = 'hetklokhuis'
464     _VALID_URL = r'https?://(?:www\.)?hetklokhuis.nl/[^/]+/\d+/(?P<id>[^/?#&]+)'
465
466     _TEST = {
467         'url': 'http://hetklokhuis.nl/tv-uitzending/3471/Zwaartekrachtsgolven',
468         'info_dict': {
469             'id': 'VPWON_1260528',
470             'display_id': 'Zwaartekrachtsgolven',
471             'ext': 'm4v',
472             'title': 'Het Klokhuis: Zwaartekrachtsgolven',
473             'description': 'md5:c94f31fb930d76c2efa4a4a71651dd48',
474             'upload_date': '20170223',
475         },
476         'params': {
477             'skip_download': True
478         }
479     }
480
481
482 class NPOPlaylistBaseIE(NPOIE):
483     def _real_extract(self, url):
484         playlist_id = self._match_id(url)
485
486         webpage = self._download_webpage(url, playlist_id)
487
488         entries = [
489             self.url_result('npo:%s' % video_id if not video_id.startswith('http') else video_id)
490             for video_id in orderedSet(re.findall(self._PLAYLIST_ENTRY_RE, webpage))
491         ]
492
493         playlist_title = self._html_search_regex(
494             self._PLAYLIST_TITLE_RE, webpage, 'playlist title',
495             default=None) or self._og_search_title(webpage)
496
497         return self.playlist_result(entries, playlist_id, playlist_title)
498
499
500 class VPROIE(NPOPlaylistBaseIE):
501     IE_NAME = 'vpro'
502     _VALID_URL = r'https?://(?:www\.)?(?:(?:tegenlicht\.)?vpro|2doc)\.nl/(?:[^/]+/)*(?P<id>[^/]+)\.html'
503     _PLAYLIST_TITLE_RE = (r'<h1[^>]+class=["\'].*?\bmedia-platform-title\b.*?["\'][^>]*>([^<]+)',
504                           r'<h5[^>]+class=["\'].*?\bmedia-platform-subtitle\b.*?["\'][^>]*>([^<]+)')
505     _PLAYLIST_ENTRY_RE = r'data-media-id="([^"]+)"'
506
507     _TESTS = [
508         {
509             'url': 'http://tegenlicht.vpro.nl/afleveringen/2012-2013/de-toekomst-komt-uit-afrika.html',
510             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
511             'info_dict': {
512                 'id': 'VPWON_1169289',
513                 'ext': 'm4v',
514                 'title': 'De toekomst komt uit Afrika',
515                 'description': 'md5:52cf4eefbc96fffcbdc06d024147abea',
516                 'upload_date': '20130225',
517             },
518             'skip': 'Video gone',
519         },
520         {
521             'url': 'http://www.vpro.nl/programmas/2doc/2015/sergio-herman.html',
522             'info_dict': {
523                 'id': 'sergio-herman',
524                 'title': 'sergio herman: fucking perfect',
525             },
526             'playlist_count': 2,
527         },
528         {
529             # playlist with youtube embed
530             'url': 'http://www.vpro.nl/programmas/2doc/2015/education-education.html',
531             'info_dict': {
532                 'id': 'education-education',
533                 'title': 'education education',
534             },
535             'playlist_count': 2,
536         },
537         {
538             'url': 'http://www.2doc.nl/documentaires/series/2doc/2015/oktober/de-tegenprestatie.html',
539             'info_dict': {
540                 'id': 'de-tegenprestatie',
541                 'title': 'De Tegenprestatie',
542             },
543             'playlist_count': 2,
544         }, {
545             'url': 'http://www.2doc.nl/speel~VARA_101375237~mh17-het-verdriet-van-nederland~.html',
546             'info_dict': {
547                 'id': 'VARA_101375237',
548                 'ext': 'm4v',
549                 'title': 'MH17: Het verdriet van Nederland',
550                 'description': 'md5:09e1a37c1fdb144621e22479691a9f18',
551                 'upload_date': '20150716',
552             },
553             'params': {
554                 # Skip because of m3u8 download
555                 'skip_download': True
556             },
557         }
558     ]
559
560
561 class WNLIE(NPOPlaylistBaseIE):
562     IE_NAME = 'wnl'
563     _VALID_URL = r'https?://(?:www\.)?omroepwnl\.nl/video/detail/(?P<id>[^/]+)__\d+'
564     _PLAYLIST_TITLE_RE = r'(?s)<h1[^>]+class="subject"[^>]*>(.+?)</h1>'
565     _PLAYLIST_ENTRY_RE = r'<a[^>]+href="([^"]+)"[^>]+class="js-mid"[^>]*>Deel \d+'
566
567     _TESTS = [{
568         'url': 'http://www.omroepwnl.nl/video/detail/vandaag-de-dag-6-mei__060515',
569         'info_dict': {
570             'id': 'vandaag-de-dag-6-mei',
571             'title': 'Vandaag de Dag 6 mei',
572         },
573         'playlist_count': 4,
574     }]
575
576
577 class AndereTijdenIE(NPOPlaylistBaseIE):
578     IE_NAME = 'anderetijden'
579     _VALID_URL = r'https?://(?:www\.)?anderetijden\.nl/programma/(?:[^/]+/)+(?P<id>[^/?#&]+)'
580     _PLAYLIST_TITLE_RE = r'(?s)<h1[^>]+class=["\'].*?\bpage-title\b.*?["\'][^>]*>(.+?)</h1>'
581     _PLAYLIST_ENTRY_RE = r'<figure[^>]+class=["\']episode-container episode-page["\'][^>]+data-prid=["\'](.+?)["\']'
582
583     _TESTS = [{
584         'url': 'http://anderetijden.nl/programma/1/Andere-Tijden/aflevering/676/Duitse-soldaten-over-de-Slag-bij-Arnhem',
585         'info_dict': {
586             'id': 'Duitse-soldaten-over-de-Slag-bij-Arnhem',
587             'title': 'Duitse soldaten over de Slag bij Arnhem',
588         },
589         'playlist_count': 3,
590     }]