[npo] Decrypting token (closes #6136)
[youtube-dl] / youtube_dl / extractor / npo.py
1 from __future__ import unicode_literals
2
3 from .common import InfoExtractor
4 from ..utils import (
5     fix_xml_ampersands,
6     parse_duration,
7     qualities,
8     strip_jsonp,
9     unified_strdate,
10     url_basename,
11 )
12
13
14 class NPOBaseIE(InfoExtractor):
15     def _get_token(self, video_id):
16         token_page = self._download_webpage(
17             'http://ida.omroep.nl/npoplayer/i.js',
18             video_id, note='Downloading token')
19         token = self._search_regex(
20             r'npoplayer\.token = "(.+?)"', token_page, 'token')
21         token_l = list(token)
22         first = second = None
23         for i in range(5, len(token_l) - 4):
24             if token_l[i].isdigit():
25                 if first is None:
26                     first = i
27                 elif second is None:
28                     second = i
29         if first is None or second is None:
30             first = 12
31             second = 13
32
33         token_l[first], token_l[second] = token_l[second], token_l[first]
34
35         return ''.join(token_l)
36
37
38 class NPOIE(NPOBaseIE):
39     IE_NAME = 'npo.nl'
40     _VALID_URL = r'https?://(?:www\.)?npo\.nl/(?!live|radio)[^/]+/[^/]+/(?P<id>[^/?]+)'
41
42     _TESTS = [
43         {
44             'url': 'http://www.npo.nl/nieuwsuur/22-06-2014/VPWON_1220719',
45             'md5': '4b3f9c429157ec4775f2c9cb7b911016',
46             'info_dict': {
47                 'id': 'VPWON_1220719',
48                 'ext': 'm4v',
49                 'title': 'Nieuwsuur',
50                 'description': 'Dagelijks tussen tien en elf: nieuws, sport en achtergronden.',
51                 'upload_date': '20140622',
52             },
53         },
54         {
55             'url': 'http://www.npo.nl/de-mega-mike-mega-thomas-show/27-02-2009/VARA_101191800',
56             'md5': 'da50a5787dbfc1603c4ad80f31c5120b',
57             'info_dict': {
58                 'id': 'VARA_101191800',
59                 'ext': 'm4v',
60                 'title': 'De Mega Mike & Mega Thomas show',
61                 'description': 'md5:3b74c97fc9d6901d5a665aac0e5400f4',
62                 'upload_date': '20090227',
63                 'duration': 2400,
64             },
65         },
66         {
67             'url': 'http://www.npo.nl/tegenlicht/25-02-2013/VPWON_1169289',
68             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
69             'info_dict': {
70                 'id': 'VPWON_1169289',
71                 'ext': 'm4v',
72                 'title': 'Tegenlicht',
73                 'description': 'md5:d6476bceb17a8c103c76c3b708f05dd1',
74                 'upload_date': '20130225',
75                 'duration': 3000,
76             },
77         },
78         {
79             'url': 'http://www.npo.nl/de-nieuwe-mens-deel-1/21-07-2010/WO_VPRO_043706',
80             'info_dict': {
81                 'id': 'WO_VPRO_043706',
82                 'ext': 'wmv',
83                 'title': 'De nieuwe mens - Deel 1',
84                 'description': 'md5:518ae51ba1293ffb80d8d8ce90b74e4b',
85                 'duration': 4680,
86             },
87             'params': {
88                 # mplayer mms download
89                 'skip_download': True,
90             }
91         },
92         # non asf in streams
93         {
94             'url': 'http://www.npo.nl/hoe-gaat-europa-verder-na-parijs/10-01-2015/WO_NOS_762771',
95             'md5': 'b3da13de374cbe2d5332a7e910bef97f',
96             'info_dict': {
97                 'id': 'WO_NOS_762771',
98                 'ext': 'mp4',
99                 'title': 'Hoe gaat Europa verder na Parijs?',
100             },
101         },
102     ]
103
104     def _real_extract(self, url):
105         video_id = self._match_id(url)
106         return self._get_info(video_id)
107
108     def _get_info(self, video_id):
109         metadata = self._download_json(
110             'http://e.omroep.nl/metadata/%s' % video_id,
111             video_id,
112             # We have to remove the javascript callback
113             transform_source=strip_jsonp,
114         )
115
116         token = self._get_token(video_id)
117
118         formats = []
119
120         pubopties = metadata.get('pubopties')
121         if pubopties:
122             quality = qualities(['adaptive', 'wmv_sb', 'h264_sb', 'wmv_bb', 'h264_bb', 'wvc1_std', 'h264_std'])
123             for format_id in pubopties:
124                 format_info = self._download_json(
125                     'http://ida.omroep.nl/odi/?prid=%s&puboptions=%s&adaptive=yes&token=%s'
126                     % (video_id, format_id, token),
127                     video_id, 'Downloading %s JSON' % format_id)
128                 if format_info.get('error_code', 0) or format_info.get('errorcode', 0):
129                     continue
130                 streams = format_info.get('streams')
131                 if streams:
132                     video_info = self._download_json(
133                         streams[0] + '&type=json',
134                         video_id, 'Downloading %s stream JSON' % format_id)
135                 else:
136                     video_info = format_info
137                 video_url = video_info.get('url')
138                 if not video_url:
139                     continue
140                 if format_id == 'adaptive':
141                     formats.extend(self._extract_m3u8_formats(video_url, video_id))
142                 else:
143                     formats.append({
144                         'url': video_url,
145                         'format_id': format_id,
146                         'quality': quality(format_id),
147                     })
148
149         streams = metadata.get('streams')
150         if streams:
151             for i, stream in enumerate(streams):
152                 stream_url = stream.get('url')
153                 if not stream_url:
154                     continue
155                 if '.asf' not in stream_url:
156                     formats.append({
157                         'url': stream_url,
158                         'quality': stream.get('kwaliteit'),
159                     })
160                     continue
161                 asx = self._download_xml(
162                     stream_url, video_id,
163                     'Downloading stream %d ASX playlist' % i,
164                     transform_source=fix_xml_ampersands)
165                 ref = asx.find('./ENTRY/Ref')
166                 if ref is None:
167                     continue
168                 video_url = ref.get('href')
169                 if not video_url:
170                     continue
171                 formats.append({
172                     'url': video_url,
173                     'ext': stream.get('formaat', 'asf'),
174                     'quality': stream.get('kwaliteit'),
175                 })
176
177         self._sort_formats(formats)
178
179         subtitles = {}
180         if metadata.get('tt888') == 'ja':
181             subtitles['nl'] = [{
182                 'ext': 'vtt',
183                 'url': 'http://e.omroep.nl/tt888/%s' % video_id,
184             }]
185
186         return {
187             'id': video_id,
188             'title': metadata['titel'],
189             'description': metadata['info'],
190             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
191             'upload_date': unified_strdate(metadata.get('gidsdatum')),
192             'duration': parse_duration(metadata.get('tijdsduur')),
193             'formats': formats,
194             'subtitles': subtitles,
195         }
196
197
198 class NPOLiveIE(NPOBaseIE):
199     IE_NAME = 'npo.nl:live'
200     _VALID_URL = r'https?://(?:www\.)?npo\.nl/live/(?P<id>.+)'
201
202     _TEST = {
203         'url': 'http://www.npo.nl/live/npo-1',
204         'info_dict': {
205             'id': 'LI_NEDERLAND1_136692',
206             'display_id': 'npo-1',
207             'ext': 'mp4',
208             'title': 're:^Nederland 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
209             'description': 'Livestream',
210             'is_live': True,
211         },
212         'params': {
213             'skip_download': True,
214         }
215     }
216
217     def _real_extract(self, url):
218         display_id = self._match_id(url)
219
220         webpage = self._download_webpage(url, display_id)
221
222         live_id = self._search_regex(
223             r'data-prid="([^"]+)"', webpage, 'live id')
224
225         metadata = self._download_json(
226             'http://e.omroep.nl/metadata/%s' % live_id,
227             display_id, transform_source=strip_jsonp)
228
229         token = self._get_token(display_id)
230
231         formats = []
232
233         streams = metadata.get('streams')
234         if streams:
235             for stream in streams:
236                 stream_type = stream.get('type').lower()
237                 # smooth streaming is not supported
238                 if stream_type in ['ss', 'ms']:
239                     continue
240                 stream_info = self._download_json(
241                     'http://ida.omroep.nl/aapi/?stream=%s&token=%s&type=jsonp'
242                     % (stream.get('url'), token),
243                     display_id, 'Downloading %s JSON' % stream_type)
244                 if stream_info.get('error_code', 0) or stream_info.get('errorcode', 0):
245                     continue
246                 stream_url = self._download_json(
247                     stream_info['stream'], display_id,
248                     'Downloading %s URL' % stream_type,
249                     'Unable to download %s URL' % stream_type,
250                     transform_source=strip_jsonp, fatal=False)
251                 if not stream_url:
252                     continue
253                 if stream_type == 'hds':
254                     f4m_formats = self._extract_f4m_formats(stream_url, display_id)
255                     # f4m downloader downloads only piece of live stream
256                     for f4m_format in f4m_formats:
257                         f4m_format['preference'] = -1
258                     formats.extend(f4m_formats)
259                 elif stream_type == 'hls':
260                     formats.extend(self._extract_m3u8_formats(stream_url, display_id, 'mp4'))
261                 else:
262                     formats.append({
263                         'url': stream_url,
264                         'preference': -10,
265                     })
266
267         self._sort_formats(formats)
268
269         return {
270             'id': live_id,
271             'display_id': display_id,
272             'title': self._live_title(metadata['titel']),
273             'description': metadata['info'],
274             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
275             'formats': formats,
276             'is_live': True,
277         }
278
279
280 class NPORadioIE(InfoExtractor):
281     IE_NAME = 'npo.nl:radio'
282     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/(?P<id>[^/]+)/?$'
283
284     _TEST = {
285         'url': 'http://www.npo.nl/radio/radio-1',
286         'info_dict': {
287             'id': 'radio-1',
288             'ext': 'mp3',
289             'title': 're:^NPO Radio 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
290             'is_live': True,
291         },
292         'params': {
293             'skip_download': True,
294         }
295     }
296
297     @staticmethod
298     def _html_get_attribute_regex(attribute):
299         return r'{0}\s*=\s*\'([^\']+)\''.format(attribute)
300
301     def _real_extract(self, url):
302         video_id = self._match_id(url)
303
304         webpage = self._download_webpage(url, video_id)
305
306         title = self._html_search_regex(
307             self._html_get_attribute_regex('data-channel'), webpage, 'title')
308
309         stream = self._parse_json(
310             self._html_search_regex(self._html_get_attribute_regex('data-streams'), webpage, 'data-streams'),
311             video_id)
312
313         codec = stream.get('codec')
314
315         return {
316             'id': video_id,
317             'url': stream['url'],
318             'title': self._live_title(title),
319             'acodec': codec,
320             'ext': codec,
321             'is_live': True,
322         }
323
324
325 class NPORadioFragmentIE(InfoExtractor):
326     IE_NAME = 'npo.nl:radio:fragment'
327     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/[^/]+/fragment/(?P<id>\d+)'
328
329     _TEST = {
330         'url': 'http://www.npo.nl/radio/radio-5/fragment/174356',
331         'md5': 'dd8cc470dad764d0fdc70a9a1e2d18c2',
332         'info_dict': {
333             'id': '174356',
334             'ext': 'mp3',
335             'title': 'Jubileumconcert Willeke Alberti',
336         },
337     }
338
339     def _real_extract(self, url):
340         audio_id = self._match_id(url)
341
342         webpage = self._download_webpage(url, audio_id)
343
344         title = self._html_search_regex(
345             r'href="/radio/[^/]+/fragment/%s" title="([^"]+)"' % audio_id,
346             webpage, 'title')
347
348         audio_url = self._search_regex(
349             r"data-streams='([^']+)'", webpage, 'audio url')
350
351         return {
352             'id': audio_id,
353             'url': audio_url,
354             'title': title,
355         }
356
357
358 class TegenlichtVproIE(NPOIE):
359     IE_NAME = 'tegenlicht.vpro.nl'
360     _VALID_URL = r'https?://tegenlicht\.vpro\.nl/afleveringen/.*?'
361
362     _TESTS = [
363         {
364             'url': 'http://tegenlicht.vpro.nl/afleveringen/2012-2013/de-toekomst-komt-uit-afrika.html',
365             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
366             'info_dict': {
367                 'id': 'VPWON_1169289',
368                 'ext': 'm4v',
369                 'title': 'Tegenlicht',
370                 'description': 'md5:d6476bceb17a8c103c76c3b708f05dd1',
371                 'upload_date': '20130225',
372             },
373         },
374     ]
375
376     def _real_extract(self, url):
377         name = url_basename(url)
378         webpage = self._download_webpage(url, name)
379         urn = self._html_search_meta('mediaurn', webpage)
380         info_page = self._download_json(
381             'http://rs.vpro.nl/v2/api/media/%s.json' % urn, name)
382         return self._get_info(info_page['mid'])