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