Merge branch 'qqmusic-album-fix' of https://github.com/ping/youtube-dl into ping...
[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         # Decryption algorithm extracted from http://npoplayer.omroep.nl/csjs/npoplayer-min.js
22         token_l = list(token)
23         first = second = None
24         for i in range(5, len(token_l) - 4):
25             if token_l[i].isdigit():
26                 if first is None:
27                     first = i
28                 elif second is None:
29                     second = i
30         if first is None or second is None:
31             first = 12
32             second = 13
33
34         token_l[first], token_l[second] = token_l[second], token_l[first]
35
36         return ''.join(token_l)
37
38
39 class NPOIE(NPOBaseIE):
40     IE_NAME = 'npo.nl'
41     _VALID_URL = r'https?://(?:www\.)?npo\.nl/(?!live|radio)[^/]+/[^/]+/(?P<id>[^/?]+)'
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',
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',
74                 'description': 'md5:d6476bceb17a8c103c76c3b708f05dd1',
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
105     def _real_extract(self, url):
106         video_id = self._match_id(url)
107         return self._get_info(video_id)
108
109     def _get_info(self, video_id):
110         metadata = self._download_json(
111             'http://e.omroep.nl/metadata/%s' % video_id,
112             video_id,
113             # We have to remove the javascript callback
114             transform_source=strip_jsonp,
115         )
116
117         token = self._get_token(video_id)
118
119         formats = []
120
121         pubopties = metadata.get('pubopties')
122         if pubopties:
123             quality = qualities(['adaptive', 'wmv_sb', 'h264_sb', 'wmv_bb', 'h264_bb', 'wvc1_std', 'h264_std'])
124             for format_id in pubopties:
125                 format_info = self._download_json(
126                     'http://ida.omroep.nl/odi/?prid=%s&puboptions=%s&adaptive=yes&token=%s'
127                     % (video_id, format_id, token),
128                     video_id, 'Downloading %s JSON' % format_id)
129                 if format_info.get('error_code', 0) or format_info.get('errorcode', 0):
130                     continue
131                 streams = format_info.get('streams')
132                 if streams:
133                     video_info = self._download_json(
134                         streams[0] + '&type=json',
135                         video_id, 'Downloading %s stream JSON' % format_id)
136                 else:
137                     video_info = format_info
138                 video_url = video_info.get('url')
139                 if not video_url:
140                     continue
141                 if format_id == 'adaptive':
142                     formats.extend(self._extract_m3u8_formats(video_url, video_id))
143                 else:
144                     formats.append({
145                         'url': video_url,
146                         'format_id': format_id,
147                         'quality': quality(format_id),
148                     })
149
150         streams = metadata.get('streams')
151         if streams:
152             for i, stream in enumerate(streams):
153                 stream_url = stream.get('url')
154                 if not stream_url:
155                     continue
156                 if '.asf' not in stream_url:
157                     formats.append({
158                         'url': stream_url,
159                         'quality': stream.get('kwaliteit'),
160                     })
161                     continue
162                 asx = self._download_xml(
163                     stream_url, video_id,
164                     'Downloading stream %d ASX playlist' % i,
165                     transform_source=fix_xml_ampersands)
166                 ref = asx.find('./ENTRY/Ref')
167                 if ref is None:
168                     continue
169                 video_url = ref.get('href')
170                 if not video_url:
171                     continue
172                 formats.append({
173                     'url': video_url,
174                     'ext': stream.get('formaat', 'asf'),
175                     'quality': stream.get('kwaliteit'),
176                 })
177
178         self._sort_formats(formats)
179
180         subtitles = {}
181         if metadata.get('tt888') == 'ja':
182             subtitles['nl'] = [{
183                 'ext': 'vtt',
184                 'url': 'http://e.omroep.nl/tt888/%s' % video_id,
185             }]
186
187         return {
188             'id': video_id,
189             'title': metadata['titel'],
190             'description': metadata['info'],
191             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
192             'upload_date': unified_strdate(metadata.get('gidsdatum')),
193             'duration': parse_duration(metadata.get('tijdsduur')),
194             'formats': formats,
195             'subtitles': subtitles,
196         }
197
198
199 class NPOLiveIE(NPOBaseIE):
200     IE_NAME = 'npo.nl:live'
201     _VALID_URL = r'https?://(?:www\.)?npo\.nl/live/(?P<id>.+)'
202
203     _TEST = {
204         'url': 'http://www.npo.nl/live/npo-1',
205         'info_dict': {
206             'id': 'LI_NEDERLAND1_136692',
207             'display_id': 'npo-1',
208             'ext': 'mp4',
209             'title': 're:^Nederland 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
210             'description': 'Livestream',
211             'is_live': True,
212         },
213         'params': {
214             'skip_download': True,
215         }
216     }
217
218     def _real_extract(self, url):
219         display_id = self._match_id(url)
220
221         webpage = self._download_webpage(url, display_id)
222
223         live_id = self._search_regex(
224             r'data-prid="([^"]+)"', webpage, 'live id')
225
226         metadata = self._download_json(
227             'http://e.omroep.nl/metadata/%s' % live_id,
228             display_id, transform_source=strip_jsonp)
229
230         token = self._get_token(display_id)
231
232         formats = []
233
234         streams = metadata.get('streams')
235         if streams:
236             for stream in streams:
237                 stream_type = stream.get('type').lower()
238                 # smooth streaming is not supported
239                 if stream_type in ['ss', 'ms']:
240                     continue
241                 stream_info = self._download_json(
242                     'http://ida.omroep.nl/aapi/?stream=%s&token=%s&type=jsonp'
243                     % (stream.get('url'), token),
244                     display_id, 'Downloading %s JSON' % stream_type)
245                 if stream_info.get('error_code', 0) or stream_info.get('errorcode', 0):
246                     continue
247                 stream_url = self._download_json(
248                     stream_info['stream'], display_id,
249                     'Downloading %s URL' % stream_type,
250                     'Unable to download %s URL' % stream_type,
251                     transform_source=strip_jsonp, fatal=False)
252                 if not stream_url:
253                     continue
254                 if stream_type == 'hds':
255                     f4m_formats = self._extract_f4m_formats(stream_url, display_id)
256                     # f4m downloader downloads only piece of live stream
257                     for f4m_format in f4m_formats:
258                         f4m_format['preference'] = -1
259                     formats.extend(f4m_formats)
260                 elif stream_type == 'hls':
261                     formats.extend(self._extract_m3u8_formats(stream_url, display_id, 'mp4'))
262                 else:
263                     formats.append({
264                         'url': stream_url,
265                         'preference': -10,
266                     })
267
268         self._sort_formats(formats)
269
270         return {
271             'id': live_id,
272             'display_id': display_id,
273             'title': self._live_title(metadata['titel']),
274             'description': metadata['info'],
275             'thumbnail': metadata.get('images', [{'url': None}])[-1]['url'],
276             'formats': formats,
277             'is_live': True,
278         }
279
280
281 class NPORadioIE(InfoExtractor):
282     IE_NAME = 'npo.nl:radio'
283     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/(?P<id>[^/]+)/?$'
284
285     _TEST = {
286         'url': 'http://www.npo.nl/radio/radio-1',
287         'info_dict': {
288             'id': 'radio-1',
289             'ext': 'mp3',
290             'title': 're:^NPO Radio 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
291             'is_live': True,
292         },
293         'params': {
294             'skip_download': True,
295         }
296     }
297
298     @staticmethod
299     def _html_get_attribute_regex(attribute):
300         return r'{0}\s*=\s*\'([^\']+)\''.format(attribute)
301
302     def _real_extract(self, url):
303         video_id = self._match_id(url)
304
305         webpage = self._download_webpage(url, video_id)
306
307         title = self._html_search_regex(
308             self._html_get_attribute_regex('data-channel'), webpage, 'title')
309
310         stream = self._parse_json(
311             self._html_search_regex(self._html_get_attribute_regex('data-streams'), webpage, 'data-streams'),
312             video_id)
313
314         codec = stream.get('codec')
315
316         return {
317             'id': video_id,
318             'url': stream['url'],
319             'title': self._live_title(title),
320             'acodec': codec,
321             'ext': codec,
322             'is_live': True,
323         }
324
325
326 class NPORadioFragmentIE(InfoExtractor):
327     IE_NAME = 'npo.nl:radio:fragment'
328     _VALID_URL = r'https?://(?:www\.)?npo\.nl/radio/[^/]+/fragment/(?P<id>\d+)'
329
330     _TEST = {
331         'url': 'http://www.npo.nl/radio/radio-5/fragment/174356',
332         'md5': 'dd8cc470dad764d0fdc70a9a1e2d18c2',
333         'info_dict': {
334             'id': '174356',
335             'ext': 'mp3',
336             'title': 'Jubileumconcert Willeke Alberti',
337         },
338     }
339
340     def _real_extract(self, url):
341         audio_id = self._match_id(url)
342
343         webpage = self._download_webpage(url, audio_id)
344
345         title = self._html_search_regex(
346             r'href="/radio/[^/]+/fragment/%s" title="([^"]+)"' % audio_id,
347             webpage, 'title')
348
349         audio_url = self._search_regex(
350             r"data-streams='([^']+)'", webpage, 'audio url')
351
352         return {
353             'id': audio_id,
354             'url': audio_url,
355             'title': title,
356         }
357
358
359 class TegenlichtVproIE(NPOIE):
360     IE_NAME = 'tegenlicht.vpro.nl'
361     _VALID_URL = r'https?://tegenlicht\.vpro\.nl/afleveringen/.*?'
362
363     _TESTS = [
364         {
365             'url': 'http://tegenlicht.vpro.nl/afleveringen/2012-2013/de-toekomst-komt-uit-afrika.html',
366             'md5': 'f8065e4e5a7824068ed3c7e783178f2c',
367             'info_dict': {
368                 'id': 'VPWON_1169289',
369                 'ext': 'm4v',
370                 'title': 'Tegenlicht',
371                 'description': 'md5:d6476bceb17a8c103c76c3b708f05dd1',
372                 'upload_date': '20130225',
373             },
374         },
375     ]
376
377     def _real_extract(self, url):
378         name = url_basename(url)
379         webpage = self._download_webpage(url, name)
380         urn = self._html_search_meta('mediaurn', webpage)
381         info_page = self._download_json(
382             'http://rs.vpro.nl/v2/api/media/%s.json' % urn, name)
383         return self._get_info(info_page['mid'])