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