]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/nrk.py
Merge tag 'upstream/2017.02.07'
[youtubedl] / youtube_dl / extractor / nrk.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import random
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import compat_urllib_parse_unquote
9 from ..utils import (
10 ExtractorError,
11 int_or_none,
12 parse_age_limit,
13 parse_duration,
14 )
15
16
17 class NRKBaseIE(InfoExtractor):
18 _faked_ip = None
19
20 def _download_webpage_handle(self, *args, **kwargs):
21 # NRK checks X-Forwarded-For HTTP header in order to figure out the
22 # origin of the client behind proxy. This allows to bypass geo
23 # restriction by faking this header's value to some Norway IP.
24 # We will do so once we encounter any geo restriction error.
25 if self._faked_ip:
26 # NB: str is intentional
27 kwargs.setdefault(str('headers'), {})['X-Forwarded-For'] = self._faked_ip
28 return super(NRKBaseIE, self)._download_webpage_handle(*args, **kwargs)
29
30 def _fake_ip(self):
31 # Use fake IP from 37.191.128.0/17 in order to workaround geo
32 # restriction
33 def octet(lb=0, ub=255):
34 return random.randint(lb, ub)
35 self._faked_ip = '37.191.%d.%d' % (octet(128), octet())
36
37 def _real_extract(self, url):
38 video_id = self._match_id(url)
39
40 data = self._download_json(
41 'http://%s/mediaelement/%s' % (self._API_HOST, video_id),
42 video_id, 'Downloading mediaelement JSON')
43
44 title = data.get('fullTitle') or data.get('mainTitle') or data['title']
45 video_id = data.get('id') or video_id
46
47 http_headers = {'X-Forwarded-For': self._faked_ip} if self._faked_ip else {}
48
49 entries = []
50
51 conviva = data.get('convivaStatistics') or {}
52 live = (data.get('mediaElementType') == 'Live' or
53 data.get('isLive') is True or conviva.get('isLive'))
54
55 def make_title(t):
56 return self._live_title(t) if live else t
57
58 media_assets = data.get('mediaAssets')
59 if media_assets and isinstance(media_assets, list):
60 def video_id_and_title(idx):
61 return ((video_id, title) if len(media_assets) == 1
62 else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
63 for num, asset in enumerate(media_assets, 1):
64 asset_url = asset.get('url')
65 if not asset_url:
66 continue
67 formats = self._extract_akamai_formats(asset_url, video_id)
68 if not formats:
69 continue
70 self._sort_formats(formats)
71
72 # Some f4m streams may not work with hdcore in fragments' URLs
73 for f in formats:
74 extra_param = f.get('extra_param_to_segment_url')
75 if extra_param and 'hdcore' in extra_param:
76 del f['extra_param_to_segment_url']
77
78 entry_id, entry_title = video_id_and_title(num)
79 duration = parse_duration(asset.get('duration'))
80 subtitles = {}
81 for subtitle in ('webVtt', 'timedText'):
82 subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
83 if subtitle_url:
84 subtitles.setdefault('no', []).append({
85 'url': compat_urllib_parse_unquote(subtitle_url)
86 })
87 entries.append({
88 'id': asset.get('carrierId') or entry_id,
89 'title': make_title(entry_title),
90 'duration': duration,
91 'subtitles': subtitles,
92 'formats': formats,
93 'http_headers': http_headers,
94 })
95
96 if not entries:
97 media_url = data.get('mediaUrl')
98 if media_url:
99 formats = self._extract_akamai_formats(media_url, video_id)
100 self._sort_formats(formats)
101 duration = parse_duration(data.get('duration'))
102 entries = [{
103 'id': video_id,
104 'title': make_title(title),
105 'duration': duration,
106 'formats': formats,
107 }]
108
109 if not entries:
110 message_type = data.get('messageType', '')
111 # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
112 if 'IsGeoBlocked' in message_type and not self._faked_ip:
113 self.report_warning(
114 'Video is geo restricted, trying to fake IP')
115 self._fake_ip()
116 return self._real_extract(url)
117
118 MESSAGES = {
119 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
120 'ProgramRightsHasExpired': 'Programmet har gått ut',
121 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
122 }
123 raise ExtractorError(
124 '%s said: %s' % (self.IE_NAME, MESSAGES.get(
125 message_type, message_type)),
126 expected=True)
127
128 series = conviva.get('seriesName') or data.get('seriesTitle')
129 episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
130
131 season_number = None
132 episode_number = None
133 if data.get('mediaElementType') == 'Episode':
134 _season_episode = data.get('scoresStatistics', {}).get('springStreamStream') or \
135 data.get('relativeOriginUrl', '')
136 EPISODENUM_RE = [
137 r'/s(?P<season>\d{,2})e(?P<episode>\d{,2})\.',
138 r'/sesong-(?P<season>\d{,2})/episode-(?P<episode>\d{,2})',
139 ]
140 season_number = int_or_none(self._search_regex(
141 EPISODENUM_RE, _season_episode, 'season number',
142 default=None, group='season'))
143 episode_number = int_or_none(self._search_regex(
144 EPISODENUM_RE, _season_episode, 'episode number',
145 default=None, group='episode'))
146
147 thumbnails = None
148 images = data.get('images')
149 if images and isinstance(images, dict):
150 web_images = images.get('webImages')
151 if isinstance(web_images, list):
152 thumbnails = [{
153 'url': image['imageUrl'],
154 'width': int_or_none(image.get('width')),
155 'height': int_or_none(image.get('height')),
156 } for image in web_images if image.get('imageUrl')]
157
158 description = data.get('description')
159 category = data.get('mediaAnalytics', {}).get('category')
160
161 common_info = {
162 'description': description,
163 'series': series,
164 'episode': episode,
165 'season_number': season_number,
166 'episode_number': episode_number,
167 'categories': [category] if category else None,
168 'age_limit': parse_age_limit(data.get('legalAge')),
169 'thumbnails': thumbnails,
170 }
171
172 vcodec = 'none' if data.get('mediaType') == 'Audio' else None
173
174 # TODO: extract chapters when https://github.com/rg3/youtube-dl/pull/9409 is merged
175
176 for entry in entries:
177 entry.update(common_info)
178 for f in entry['formats']:
179 f['vcodec'] = vcodec
180
181 return self.playlist_result(entries, video_id, title, description)
182
183
184 class NRKIE(NRKBaseIE):
185 _VALID_URL = r'''(?x)
186 (?:
187 nrk:|
188 https?://
189 (?:
190 (?:www\.)?nrk\.no/video/PS\*|
191 v8-psapi\.nrk\.no/mediaelement/
192 )
193 )
194 (?P<id>[^/?#&]+)
195 '''
196 _API_HOST = 'v8.psapi.nrk.no'
197 _TESTS = [{
198 # video
199 'url': 'http://www.nrk.no/video/PS*150533',
200 'md5': '2f7f6eeb2aacdd99885f355428715cfa',
201 'info_dict': {
202 'id': '150533',
203 'ext': 'mp4',
204 'title': 'Dompap og andre fugler i Piip-Show',
205 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
206 'duration': 263,
207 }
208 }, {
209 # audio
210 'url': 'http://www.nrk.no/video/PS*154915',
211 # MD5 is unstable
212 'info_dict': {
213 'id': '154915',
214 'ext': 'flv',
215 'title': 'Slik høres internett ut når du er blind',
216 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
217 'duration': 20,
218 }
219 }, {
220 'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
221 'only_matching': True,
222 }, {
223 'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
224 'only_matching': True,
225 }]
226
227
228 class NRKTVIE(NRKBaseIE):
229 IE_DESC = 'NRK TV and NRK Radio'
230 _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
231 _VALID_URL = r'''(?x)
232 https?://
233 (?:tv|radio)\.nrk(?:super)?\.no/
234 (?:serie/[^/]+|program)/
235 (?![Ee]pisodes)%s
236 (?:/\d{2}-\d{2}-\d{4})?
237 (?:\#del=(?P<part_id>\d+))?
238 ''' % _EPISODE_RE
239 _API_HOST = 'psapi-we.nrk.no'
240
241 _TESTS = [{
242 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
243 'md5': '4e9ca6629f09e588ed240fb11619922a',
244 'info_dict': {
245 'id': 'MUHH48000314AA',
246 'ext': 'mp4',
247 'title': '20 spørsmål 23.05.2014',
248 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
249 'duration': 1741,
250 'series': '20 spørsmål - TV',
251 'episode': '23.05.2014',
252 },
253 }, {
254 'url': 'https://tv.nrk.no/program/mdfp15000514',
255 'info_dict': {
256 'id': 'MDFP15000514CA',
257 'ext': 'mp4',
258 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
259 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
260 'duration': 4605,
261 'series': 'Kunnskapskanalen',
262 'episode': '24.05.2014',
263 },
264 'params': {
265 'skip_download': True,
266 },
267 }, {
268 # single playlist video
269 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
270 'info_dict': {
271 'id': 'MSPO40010515-part2',
272 'ext': 'flv',
273 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
274 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
275 },
276 'params': {
277 'skip_download': True,
278 },
279 'expected_warnings': ['Video is geo restricted'],
280 'skip': 'particular part is not supported currently',
281 }, {
282 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
283 'playlist': [{
284 'info_dict': {
285 'id': 'MSPO40010515AH',
286 'ext': 'mp4',
287 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 1)',
288 'description': 'md5:c03aba1e917561eface5214020551b7a',
289 'duration': 772,
290 'series': 'Tour de Ski',
291 'episode': '06.01.2015',
292 },
293 'params': {
294 'skip_download': True,
295 },
296 }, {
297 'info_dict': {
298 'id': 'MSPO40010515BH',
299 'ext': 'mp4',
300 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 2)',
301 'description': 'md5:c03aba1e917561eface5214020551b7a',
302 'duration': 6175,
303 'series': 'Tour de Ski',
304 'episode': '06.01.2015',
305 },
306 'params': {
307 'skip_download': True,
308 },
309 }],
310 'info_dict': {
311 'id': 'MSPO40010515',
312 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
313 'description': 'md5:c03aba1e917561eface5214020551b7a',
314 },
315 'expected_warnings': ['Video is geo restricted'],
316 }, {
317 'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
318 'info_dict': {
319 'id': 'KMTE50001317AA',
320 'ext': 'mp4',
321 'title': 'Anno 13:30',
322 'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
323 'duration': 2340,
324 'series': 'Anno',
325 'episode': '13:30',
326 'season_number': 3,
327 'episode_number': 13,
328 },
329 'params': {
330 'skip_download': True,
331 },
332 }, {
333 'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
334 'info_dict': {
335 'id': 'MUHH46000317AA',
336 'ext': 'mp4',
337 'title': 'Nytt på Nytt 27.01.2017',
338 'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
339 'duration': 1796,
340 'series': 'Nytt på nytt',
341 'episode': '27.01.2017',
342 },
343 'params': {
344 'skip_download': True,
345 },
346 }, {
347 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
348 'only_matching': True,
349 }]
350
351
352 class NRKTVDirekteIE(NRKTVIE):
353 IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
354 _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
355
356 _TESTS = [{
357 'url': 'https://tv.nrk.no/direkte/nrk1',
358 'only_matching': True,
359 }, {
360 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
361 'only_matching': True,
362 }]
363
364
365 class NRKPlaylistBaseIE(InfoExtractor):
366 def _extract_description(self, webpage):
367 pass
368
369 def _real_extract(self, url):
370 playlist_id = self._match_id(url)
371
372 webpage = self._download_webpage(url, playlist_id)
373
374 entries = [
375 self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
376 for video_id in re.findall(self._ITEM_RE, webpage)
377 ]
378
379 playlist_title = self. _extract_title(webpage)
380 playlist_description = self._extract_description(webpage)
381
382 return self.playlist_result(
383 entries, playlist_id, playlist_title, playlist_description)
384
385
386 class NRKPlaylistIE(NRKPlaylistBaseIE):
387 _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
388 _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
389 _TESTS = [{
390 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
391 'info_dict': {
392 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
393 'title': 'Gjenopplev den historiske solformørkelsen',
394 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
395 },
396 'playlist_count': 2,
397 }, {
398 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
399 'info_dict': {
400 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
401 'title': 'Rivertonprisen til Karin Fossum',
402 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
403 },
404 'playlist_count': 5,
405 }]
406
407 def _extract_title(self, webpage):
408 return self._og_search_title(webpage, fatal=False)
409
410 def _extract_description(self, webpage):
411 return self._og_search_description(webpage)
412
413
414 class NRKTVEpisodesIE(NRKPlaylistBaseIE):
415 _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
416 _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
417 _TESTS = [{
418 'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
419 'info_dict': {
420 'id': '69031',
421 'title': 'Nytt på nytt, sesong: 201210',
422 },
423 'playlist_count': 4,
424 }]
425
426 def _extract_title(self, webpage):
427 return self._html_search_regex(
428 r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
429
430
431 class NRKTVSeriesIE(InfoExtractor):
432 _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/serie/(?P<id>[^/]+)'
433 _ITEM_RE = r'(?:data-season=["\']|id=["\']season-)(?P<id>\d+)'
434 _TESTS = [{
435 'url': 'https://tv.nrk.no/serie/groenn-glede',
436 'info_dict': {
437 'id': 'groenn-glede',
438 'title': 'Grønn glede',
439 'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
440 },
441 'playlist_mincount': 9,
442 }, {
443 'url': 'http://tv.nrksuper.no/serie/labyrint',
444 'info_dict': {
445 'id': 'labyrint',
446 'title': 'Labyrint',
447 'description': 'md5:58afd450974c89e27d5a19212eee7115',
448 },
449 'playlist_mincount': 3,
450 }, {
451 'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
452 'only_matching': True,
453 }, {
454 'url': 'https://tv.nrk.no/serie/saving-the-human-race',
455 'only_matching': True,
456 }, {
457 'url': 'https://tv.nrk.no/serie/postmann-pat',
458 'only_matching': True,
459 }]
460
461 @classmethod
462 def suitable(cls, url):
463 return False if NRKTVIE.suitable(url) else super(NRKTVSeriesIE, cls).suitable(url)
464
465 def _real_extract(self, url):
466 series_id = self._match_id(url)
467
468 webpage = self._download_webpage(url, series_id)
469
470 entries = [
471 self.url_result(
472 'https://tv.nrk.no/program/Episodes/{series}/{season}'.format(
473 series=series_id, season=season_id))
474 for season_id in re.findall(self._ITEM_RE, webpage)
475 ]
476
477 title = self._html_search_meta(
478 'seriestitle', webpage,
479 'title', default=None) or self._og_search_title(
480 webpage, fatal=False)
481
482 description = self._html_search_meta(
483 'series_description', webpage,
484 'description', default=None) or self._og_search_description(webpage)
485
486 return self.playlist_result(entries, series_id, title, description)
487
488
489 class NRKSkoleIE(InfoExtractor):
490 IE_DESC = 'NRK Skole'
491 _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
492
493 _TESTS = [{
494 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
495 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
496 'info_dict': {
497 'id': '6021',
498 'ext': 'mp4',
499 'title': 'Genetikk og eneggede tvillinger',
500 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
501 'duration': 399,
502 },
503 }, {
504 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
505 'only_matching': True,
506 }]
507
508 def _real_extract(self, url):
509 video_id = self._match_id(url)
510
511 webpage = self._download_webpage(
512 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
513 video_id)
514
515 nrk_id = self._parse_json(
516 self._search_regex(
517 r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
518 webpage, 'application json'),
519 video_id)['activeMedia']['psId']
520
521 return self.url_result('nrk:%s' % nrk_id)