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