[wnl] Add extractor for omroepwnl playlists
[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_urllib_request,
8     compat_urllib_parse,
9 )
10 from ..utils import (
11     fix_xml_ampersands,
12     parse_duration,
13     qualities,
14     strip_jsonp,
15     unified_strdate,
16     url_basename,
17 )
18
19
20 class NPOBaseIE(InfoExtractor):
21     def _get_token(self, video_id):
22         token_page = self._download_webpage(
23             'http://ida.omroep.nl/npoplayer/i.js',
24             video_id, note='Downloading token')
25         token = self._search_regex(
26             r'npoplayer\.token = "(.+?)"', token_page, 'token')
27         # Decryption algorithm extracted from http://npoplayer.omroep.nl/csjs/npoplayer-min.js
28         token_l = list(token)
29         first = second = None
30         for i in range(5, len(token_l) - 4):
31             if token_l[i].isdigit():
32                 if first is None:
33                     first = i
34                 elif second is None:
35                     second = i
36         if first is None or second is None:
37             first = 12
38             second = 13
39
40         token_l[first], token_l[second] = token_l[second], token_l[first]
41
42         return ''.join(token_l)
43
44
45 class NPOIE(NPOBaseIE):
46     IE_NAME = 'npo'
47     IE_DESC = 'npo.nl and ntr.nl'
48     _VALID_URL = r'''(?x)
49                     (?:
50                         npo:|
51                         https?://
52                             (?:www\.)?
53                             (?:
54                                 npo\.nl/(?!live|radio)(?:[^/]+/){2}|
55                                 ntr\.nl/(?:[^/]+/){2,}|
56                                 omroepwnl\.nl/video/fragment/[^/]+__
57                             )
58                         )
59                         (?P<id>[^/?#]+)
60                 '''
61
62     _TESTS = [
63         {
64             'url': 'http://www.npo.nl/nieuwsuur/22-06-2014/VPWON_1220719',
65             'md5': '4b3f9c429157ec4775f2c9cb7b911016',
66             'info_dict': {
67                 'id': 'VPWON_1220719',
68                 'ext': 'm4v',
69                 'title': 'Nieuwsuur',
70                 'description': 'Dagelijks tussen tien en elf: nieuws, sport en achtergronden.',
71                 'upload_date': '20140622',
72             },
73         },
74         {
75             'url': 'http://www.npo.nl/de-mega-mike-mega-thomas-show/27-02-2009/VARA_101191800',
76             'md5': 'da50a5787dbfc1603c4ad80f31c5120b',
77             'info_dict': {
78                 'id': 'VARA_101191800',
79                 'ext': 'm4v',
80                 'title': 'De Mega Mike & Mega Thomas show',
81                 'description': 'md5:3b74c97fc9d6901d5a665aac0e5400f4',
82                 'upload_date': '20090227',
83                 'duration': 2400,
84             },
85         },
86         {
87             'url': 'http://www.npo.nl/tegenlicht/25-02-2013/VPWON_1169289',
88             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
89             'info_dict': {
90                 'id': 'VPWON_1169289',
91                 'ext': 'm4v',
92                 'title': 'Tegenlicht',
93                 'description': 'md5:52cf4eefbc96fffcbdc06d024147abea',
94                 'upload_date': '20130225',
95                 'duration': 3000,
96             },
97         },
98         {
99             'url': 'http://www.npo.nl/de-nieuwe-mens-deel-1/21-07-2010/WO_VPRO_043706',
100             'info_dict': {
101                 'id': 'WO_VPRO_043706',
102                 'ext': 'wmv',
103                 'title': 'De nieuwe mens - Deel 1',
104                 'description': 'md5:518ae51ba1293ffb80d8d8ce90b74e4b',
105                 'duration': 4680,
106             },
107             'params': {
108                 # mplayer mms download
109                 'skip_download': True,
110             }
111         },
112         # non asf in streams
113         {
114             'url': 'http://www.npo.nl/hoe-gaat-europa-verder-na-parijs/10-01-2015/WO_NOS_762771',
115             'md5': 'b3da13de374cbe2d5332a7e910bef97f',
116             'info_dict': {
117                 'id': 'WO_NOS_762771',
118                 'ext': 'mp4',
119                 'title': 'Hoe gaat Europa verder na Parijs?',
120             },
121         },
122         {
123             'url': 'http://www.ntr.nl/Aap-Poot-Pies/27/detail/Aap-poot-pies/VPWON_1233944#content',
124             'md5': '01c6a2841675995da1f0cf776f03a9c3',
125             'info_dict': {
126                 'id': 'VPWON_1233944',
127                 'ext': 'm4v',
128                 'title': 'Aap, poot, pies',
129                 'description': 'md5:c9c8005d1869ae65b858e82c01a91fde',
130                 'upload_date': '20150508',
131                 'duration': 599,
132             },
133         },
134         {
135             'url': 'http://www.omroepwnl.nl/video/fragment/vandaag-de-dag-verkiezingen__POMS_WNL_853698',
136             'md5': 'd30cd8417b8b9bca1fdff27428860d08',
137             'info_dict': {
138                 'id': 'POW_00996502',
139                 'ext': 'm4v',
140                 'title': '''"Dit is wel een 'landslide'..."''',
141                 'description': 'md5:f8d66d537dfb641380226e31ca57b8e8',
142                 'upload_date': '20150508',
143                 'duration': 462,
144             },
145         }
146     ]
147
148     def _real_extract(self, url):
149         video_id = self._match_id(url)
150         return self._get_info(video_id)
151
152     def _get_info(self, video_id):
153         metadata = self._download_json(
154             'http://e.omroep.nl/metadata/%s' % video_id,
155             video_id,
156             # We have to remove the javascript callback
157             transform_source=strip_jsonp,
158         )
159
160         # For some videos actual video id (prid) is different (e.g. for
161         # http://www.omroepwnl.nl/video/fragment/vandaag-de-dag-verkiezingen__POMS_WNL_853698
162         # video id is POMS_WNL_853698 but prid is POW_00996502)
163         video_id = metadata.get('prid') or video_id
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             for format_id in pubopties:
173                 format_info = self._download_json(
174                     'http://ida.omroep.nl/odi/?prid=%s&puboptions=%s&adaptive=yes&token=%s'
175                     % (video_id, format_id, token),
176                     video_id, 'Downloading %s JSON' % format_id)
177                 if format_info.get('error_code', 0) or format_info.get('errorcode', 0):
178                     continue
179                 streams = format_info.get('streams')
180                 if streams:
181                     video_info = self._download_json(
182                         streams[0] + '&type=json',
183                         video_id, 'Downloading %s stream JSON' % format_id)
184                 else:
185                     video_info = format_info
186                 video_url = video_info.get('url')
187                 if not video_url:
188                     continue
189                 if format_id == 'adaptive':
190                     formats.extend(self._extract_m3u8_formats(video_url, video_id))
191                 else:
192                     formats.append({
193                         'url': video_url,
194                         'format_id': format_id,
195                         'quality': quality(format_id),
196                     })
197
198         streams = metadata.get('streams')
199         if streams:
200             for i, stream in enumerate(streams):
201                 stream_url = stream.get('url')
202                 if not stream_url:
203                     continue
204                 if '.asf' not in stream_url:
205                     formats.append({
206                         'url': stream_url,
207                         'quality': stream.get('kwaliteit'),
208                     })
209                     continue
210                 asx = self._download_xml(
211                     stream_url, video_id,
212                     'Downloading stream %d ASX playlist' % i,
213                     transform_source=fix_xml_ampersands)
214                 ref = asx.find('./ENTRY/Ref')
215                 if ref is None:
216                     continue
217                 video_url = ref.get('href')
218                 if not video_url:
219                     continue
220                 formats.append({
221                     'url': video_url,
222                     'ext': stream.get('formaat', 'asf'),
223                     'quality': stream.get('kwaliteit'),
224                 })
225
226         self._sort_formats(formats)
227
228         subtitles = {}
229         if metadata.get('tt888') == 'ja':
230             subtitles['nl'] = [{
231                 'ext': 'vtt',
232                 'url': 'http://e.omroep.nl/tt888/%s' % video_id,
233             }]
234
235         return {
236             'id': video_id,
237             'title': metadata['titel'],
238             'description': metadata['info'],
239             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
240             'upload_date': unified_strdate(metadata.get('gidsdatum')),
241             'duration': parse_duration(metadata.get('tijdsduur')),
242             'formats': formats,
243             'subtitles': subtitles,
244         }
245
246
247 class NPOLiveIE(NPOBaseIE):
248     IE_NAME = 'npo.nl:live'
249     _VALID_URL = r'https?://(?:www\.)?npo\.nl/live/(?P<id>.+)'
250
251     _TEST = {
252         'url': 'http://www.npo.nl/live/npo-1',
253         'info_dict': {
254             'id': 'LI_NEDERLAND1_136692',
255             'display_id': 'npo-1',
256             'ext': 'mp4',
257             'title': 're:^Nederland 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
258             'description': 'Livestream',
259             'is_live': True,
260         },
261         'params': {
262             'skip_download': True,
263         }
264     }
265
266     def _real_extract(self, url):
267         display_id = self._match_id(url)
268
269         webpage = self._download_webpage(url, display_id)
270
271         live_id = self._search_regex(
272             r'data-prid="([^"]+)"', webpage, 'live id')
273
274         metadata = self._download_json(
275             'http://e.omroep.nl/metadata/%s' % live_id,
276             display_id, transform_source=strip_jsonp)
277
278         token = self._get_token(display_id)
279
280         formats = []
281
282         streams = metadata.get('streams')
283         if streams:
284             for stream in streams:
285                 stream_type = stream.get('type').lower()
286                 # smooth streaming is not supported
287                 if stream_type in ['ss', 'ms']:
288                     continue
289                 stream_info = self._download_json(
290                     'http://ida.omroep.nl/aapi/?stream=%s&token=%s&type=jsonp'
291                     % (stream.get('url'), token),
292                     display_id, 'Downloading %s JSON' % stream_type)
293                 if stream_info.get('error_code', 0) or stream_info.get('errorcode', 0):
294                     continue
295                 stream_url = self._download_json(
296                     stream_info['stream'], display_id,
297                     'Downloading %s URL' % stream_type,
298                     'Unable to download %s URL' % stream_type,
299                     transform_source=strip_jsonp, fatal=False)
300                 if not stream_url:
301                     continue
302                 if stream_type == 'hds':
303                     f4m_formats = self._extract_f4m_formats(stream_url, display_id)
304                     # f4m downloader downloads only piece of live stream
305                     for f4m_format in f4m_formats:
306                         f4m_format['preference'] = -1
307                     formats.extend(f4m_formats)
308                 elif stream_type == 'hls':
309                     formats.extend(self._extract_m3u8_formats(stream_url, display_id, 'mp4'))
310                 else:
311                     formats.append({
312                         'url': stream_url,
313                         'preference': -10,
314                     })
315
316         self._sort_formats(formats)
317
318         return {
319             'id': live_id,
320             'display_id': display_id,
321             'title': self._live_title(metadata['titel']),
322             'description': metadata['info'],
323             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
324             'formats': formats,
325             'is_live': True,
326         }
327
328
329 class NPORadioIE(InfoExtractor):
330     IE_NAME = 'npo.nl:radio'
331     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/(?P<id>[^/]+)/?$'
332
333     _TEST = {
334         'url': 'http://www.npo.nl/radio/radio-1',
335         'info_dict': {
336             'id': 'radio-1',
337             'ext': 'mp3',
338             'title': 're:^NPO Radio 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
339             'is_live': True,
340         },
341         'params': {
342             'skip_download': True,
343         }
344     }
345
346     @staticmethod
347     def _html_get_attribute_regex(attribute):
348         return r'{0}\s*=\s*\'([^\']+)\''.format(attribute)
349
350     def _real_extract(self, url):
351         video_id = self._match_id(url)
352
353         webpage = self._download_webpage(url, video_id)
354
355         title = self._html_search_regex(
356             self._html_get_attribute_regex('data-channel'), webpage, 'title')
357
358         stream = self._parse_json(
359             self._html_search_regex(self._html_get_attribute_regex('data-streams'), webpage, 'data-streams'),
360             video_id)
361
362         codec = stream.get('codec')
363
364         return {
365             'id': video_id,
366             'url': stream['url'],
367             'title': self._live_title(title),
368             'acodec': codec,
369             'ext': codec,
370             'is_live': True,
371         }
372
373
374 class NPORadioFragmentIE(InfoExtractor):
375     IE_NAME = 'npo.nl:radio:fragment'
376     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/[^/]+/fragment/(?P<id>\d+)'
377
378     _TEST = {
379         'url': 'http://www.npo.nl/radio/radio-5/fragment/174356',
380         'md5': 'dd8cc470dad764d0fdc70a9a1e2d18c2',
381         'info_dict': {
382             'id': '174356',
383             'ext': 'mp3',
384             'title': 'Jubileumconcert Willeke Alberti',
385         },
386     }
387
388     def _real_extract(self, url):
389         audio_id = self._match_id(url)
390
391         webpage = self._download_webpage(url, audio_id)
392
393         title = self._html_search_regex(
394             r'href="/radio/[^/]+/fragment/%s" title="([^"]+)"' % audio_id,
395             webpage, 'title')
396
397         audio_url = self._search_regex(
398             r"data-streams='([^']+)'", webpage, 'audio url')
399
400         return {
401             'id': audio_id,
402             'url': audio_url,
403             'title': title,
404         }
405
406
407 class TegenlichtVproIE(NPOIE):
408     IE_NAME = 'tegenlicht.vpro.nl'
409     _VALID_URL = r'https?://tegenlicht\.vpro\.nl/afleveringen/.*?'
410
411     _TESTS = [
412         {
413             'url': 'http://tegenlicht.vpro.nl/afleveringen/2012-2013/de-toekomst-komt-uit-afrika.html',
414             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
415             'info_dict': {
416                 'id': 'VPWON_1169289',
417                 'ext': 'm4v',
418                 'title': 'Tegenlicht',
419                 'description': 'md5:d6476bceb17a8c103c76c3b708f05dd1',
420                 'upload_date': '20130225',
421             },
422         },
423     ]
424
425     def _real_extract(self, url):
426         name = url_basename(url)
427         webpage = self._download_webpage(url, name)
428         urn = self._html_search_meta('mediaurn', webpage)
429         info_page = self._download_json(
430             'http://rs.vpro.nl/v2/api/media/%s.json' % urn, name)
431         return self._get_info(info_page['mid'])
432
433
434 class WNLIE(InfoExtractor):
435     _VALID_URL = r'https?://(?:www\.)?omroepwnl\.nl/video/detail/(?P<id>[^/]+)__\d+'
436
437     _TEST = {
438         'url': 'http://www.omroepwnl.nl/video/detail/vandaag-de-dag-6-mei__060515',
439         'info_dict': {
440             'id': 'vandaag-de-dag-6-mei',
441             'title': 'Vandaag de Dag 6 mei',
442         },
443         'playlist_count': 4,
444     }
445
446     def _real_extract(self, url):
447         playlist_id = self._match_id(url)
448
449         webpage = self._download_webpage(url, playlist_id)
450
451         entries = [
452             self.url_result('npo:%s' % video_id, 'NPO')
453             for video_id, part in re.findall(
454                 r'<a[^>]+href="([^"]+)"[^>]+class="js-mid"[^>]*>(Deel \d+)', webpage)
455         ]
456
457         playlist_title = self._html_search_regex(
458             r'(?s)<h1[^>]+class="subject"[^>]*>(.+?)</h1>',
459             webpage, 'playlist title')
460
461         return self.playlist_result(entries, playlist_id, playlist_title)