]> asedeno.scripts.mit.edu Git - youtube-dl.git/blob - youtube_dl/extractor/nrk.py
[nrk] Improve error extraction
[youtube-dl.git] / youtube_dl / extractor / nrk.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_str,
10     compat_urllib_parse_unquote,
11 )
12 from ..utils import (
13     determine_ext,
14     ExtractorError,
15     int_or_none,
16     js_to_json,
17     NO_DEFAULT,
18     parse_age_limit,
19     parse_duration,
20     try_get,
21     urljoin,
22     url_or_none,
23 )
24
25
26 class NRKBaseIE(InfoExtractor):
27     _GEO_COUNTRIES = ['NO']
28
29     def _extract_nrk_formats(self, asset_url, video_id):
30         return self._extract_m3u8_formats(
31             re.sub(r'(?:bw_(?:low|high)=\d+|no_audio_only)&?', '', asset_url),
32             video_id, 'mp4', 'm3u8_native', fatal=False)
33
34     def _raise_error(self, data):
35         MESSAGES = {
36             'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
37             'ProgramRightsHasExpired': 'Programmet har gått ut',
38             'NoProgramRights': 'Ikke tilgjengelig',
39             'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
40         }
41         message_type = data.get('messageType', '')
42         # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
43         if 'IsGeoBlocked' in message_type or try_get(data, lambda x: x['usageRights']['isGeoBlocked']) is True:
44             self.raise_geo_restricted(
45                 msg=MESSAGES.get('ProgramIsGeoBlocked'),
46                 countries=self._GEO_COUNTRIES)
47         message = data.get('endUserMessage') or MESSAGES.get(message_type, message_type)
48         raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
49
50
51 class NRKIE(NRKBaseIE):
52     _VALID_URL = r'''(?x)
53                         (?:
54                             nrk:|
55                             https?://
56                                 (?:
57                                     (?:www\.)?nrk\.no/video/(?:PS\*|[^_]+_)|
58                                     v8[-.]psapi\.nrk\.no/mediaelement/
59                                 )
60                             )
61                             (?P<id>[^?\#&]+)
62                         '''
63
64     _TESTS = [{
65         # video
66         'url': 'http://www.nrk.no/video/PS*150533',
67         'md5': '706f34cdf1322577589e369e522b50ef',
68         'info_dict': {
69             'id': '150533',
70             'ext': 'mp4',
71             'title': 'Dompap og andre fugler i Piip-Show',
72             'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
73             'duration': 262,
74         }
75     }, {
76         # audio
77         'url': 'http://www.nrk.no/video/PS*154915',
78         # MD5 is unstable
79         'info_dict': {
80             'id': '154915',
81             'ext': 'flv',
82             'title': 'Slik høres internett ut når du er blind',
83             'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
84             'duration': 20,
85         }
86     }, {
87         'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
88         'only_matching': True,
89     }, {
90         'url': 'nrk:clip/7707d5a3-ebe7-434a-87d5-a3ebe7a34a70',
91         'only_matching': True,
92     }, {
93         'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
94         'only_matching': True,
95     }, {
96         'url': 'https://www.nrk.no/video/dompap-og-andre-fugler-i-piip-show_150533',
97         'only_matching': True,
98     }, {
99         'url': 'https://www.nrk.no/video/humor/kommentatorboksen-reiser-til-sjos_d1fda11f-a4ad-437a-a374-0398bc84e999',
100         'only_matching': True,
101     }]
102
103     def _extract_from_playback(self, video_id):
104         manifest = self._download_json(
105             'http://psapi.nrk.no/playback/manifest/%s' % video_id,
106             video_id, 'Downloading manifest JSON')
107
108         if manifest.get('playability') == 'nonPlayable':
109             self._raise_error(manifest['nonPlayable'])
110
111         playable = manifest['playable']
112
113         formats = []
114         for asset in playable['assets']:
115             if not isinstance(asset, dict):
116                 continue
117             if asset.get('encrypted'):
118                 continue
119             format_url = url_or_none(asset.get('url'))
120             if not format_url:
121                 continue
122             if asset.get('format') == 'HLS' or determine_ext(format_url) == 'm3u8':
123                 formats.extend(self._extract_nrk_formats(format_url, video_id))
124         self._sort_formats(formats)
125
126         data = self._download_json(
127             'http://psapi.nrk.no/playback/metadata/%s' % video_id,
128             video_id, 'Downloading metadata JSON')
129
130         preplay = data['preplay']
131         titles = preplay['titles']
132         title = titles['title']
133         alt_title = titles.get('subtitle')
134
135         description = preplay.get('description')
136         duration = parse_duration(playable.get('duration')) or parse_duration(data.get('duration'))
137
138         thumbnails = []
139         for image in try_get(
140                 preplay, lambda x: x['poster']['images'], list) or []:
141             if not isinstance(image, dict):
142                 continue
143             image_url = url_or_none(image.get('url'))
144             if not image_url:
145                 continue
146             thumbnails.append({
147                 'url': image_url,
148                 'width': int_or_none(image.get('pixelWidth')),
149                 'height': int_or_none(image.get('pixelHeight')),
150             })
151
152         return {
153             'id': video_id,
154             'title': title,
155             'alt_title': alt_title,
156             'description': description,
157             'duration': duration,
158             'thumbnails': thumbnails,
159             'formats': formats,
160         }
161
162     def _real_extract(self, url):
163         video_id = self._match_id(url)
164         return self._extract_from_playback(video_id)
165
166
167 class NRKTVIE(NRKBaseIE):
168     IE_DESC = 'NRK TV and NRK Radio'
169     _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
170     _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/(?:[^/]+/)*%s' % _EPISODE_RE
171     _API_HOSTS = ('psapi-ne.nrk.no', 'psapi-we.nrk.no')
172     _TESTS = [{
173         'url': 'https://tv.nrk.no/program/MDDP12000117',
174         'md5': '8270824df46ec629b66aeaa5796b36fb',
175         'info_dict': {
176             'id': 'MDDP12000117AA',
177             'ext': 'mp4',
178             'title': 'Alarm Trolltunga',
179             'description': 'md5:46923a6e6510eefcce23d5ef2a58f2ce',
180             'duration': 2223,
181             'age_limit': 6,
182         },
183     }, {
184         'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
185         'md5': '9a167e54d04671eb6317a37b7bc8a280',
186         'info_dict': {
187             'id': 'MUHH48000314AA',
188             'ext': 'mp4',
189             'title': '20 spørsmål 23.05.2014',
190             'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
191             'duration': 1741,
192             'series': '20 spørsmål',
193             'episode': '23.05.2014',
194         },
195         'skip': 'NoProgramRights',
196     }, {
197         'url': 'https://tv.nrk.no/program/mdfp15000514',
198         'info_dict': {
199             'id': 'MDFP15000514CA',
200             'ext': 'mp4',
201             'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
202             'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
203             'duration': 4605,
204             'series': 'Kunnskapskanalen',
205             'episode': '24.05.2014',
206         },
207         'params': {
208             'skip_download': True,
209         },
210     }, {
211         # single playlist video
212         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
213         'info_dict': {
214             'id': 'MSPO40010515-part2',
215             'ext': 'flv',
216             'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
217             'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
218         },
219         'params': {
220             'skip_download': True,
221         },
222         'expected_warnings': ['Video is geo restricted'],
223         'skip': 'particular part is not supported currently',
224     }, {
225         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
226         'playlist': [{
227             'info_dict': {
228                 'id': 'MSPO40010515AH',
229                 'ext': 'mp4',
230                 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 1)',
231                 'description': 'md5:1f97a41f05a9486ee00c56f35f82993d',
232                 'duration': 772,
233                 'series': 'Tour de Ski',
234                 'episode': '06.01.2015',
235             },
236             'params': {
237                 'skip_download': True,
238             },
239         }, {
240             'info_dict': {
241                 'id': 'MSPO40010515BH',
242                 'ext': 'mp4',
243                 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 2)',
244                 'description': 'md5:1f97a41f05a9486ee00c56f35f82993d',
245                 'duration': 6175,
246                 'series': 'Tour de Ski',
247                 'episode': '06.01.2015',
248             },
249             'params': {
250                 'skip_download': True,
251             },
252         }],
253         'info_dict': {
254             'id': 'MSPO40010515',
255             'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
256             'description': 'md5:1f97a41f05a9486ee00c56f35f82993d',
257         },
258         'expected_warnings': ['Video is geo restricted'],
259     }, {
260         'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
261         'info_dict': {
262             'id': 'KMTE50001317AA',
263             'ext': 'mp4',
264             'title': 'Anno 13:30',
265             'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
266             'duration': 2340,
267             'series': 'Anno',
268             'episode': '13:30',
269             'season_number': 3,
270             'episode_number': 13,
271         },
272         'params': {
273             'skip_download': True,
274         },
275     }, {
276         'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
277         'info_dict': {
278             'id': 'MUHH46000317AA',
279             'ext': 'mp4',
280             'title': 'Nytt på Nytt 27.01.2017',
281             'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
282             'duration': 1796,
283             'series': 'Nytt på nytt',
284             'episode': '27.01.2017',
285         },
286         'params': {
287             'skip_download': True,
288         },
289     }, {
290         'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
291         'only_matching': True,
292     }, {
293         'url': 'https://tv.nrk.no/serie/lindmo/2018/MUHU11006318/avspiller',
294         'only_matching': True,
295     }, {
296         'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201507/NPUB21019315',
297         'only_matching': True,
298     }]
299
300     _api_host = None
301
302     def _extract_from_mediaelement(self, video_id):
303         api_hosts = (self._api_host, ) if self._api_host else self._API_HOSTS
304
305         for api_host in api_hosts:
306             data = self._download_json(
307                 'http://%s/mediaelement/%s' % (api_host, video_id),
308                 video_id, 'Downloading mediaelement JSON',
309                 fatal=api_host == api_hosts[-1])
310             if not data:
311                 continue
312             self._api_host = api_host
313             break
314
315         title = data.get('fullTitle') or data.get('mainTitle') or data['title']
316         video_id = data.get('id') or video_id
317
318         urls = []
319         entries = []
320
321         conviva = data.get('convivaStatistics') or {}
322         live = (data.get('mediaElementType') == 'Live'
323                 or data.get('isLive') is True or conviva.get('isLive'))
324
325         def make_title(t):
326             return self._live_title(t) if live else t
327
328         media_assets = data.get('mediaAssets')
329         if media_assets and isinstance(media_assets, list):
330             def video_id_and_title(idx):
331                 return ((video_id, title) if len(media_assets) == 1
332                         else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
333             for num, asset in enumerate(media_assets, 1):
334                 asset_url = asset.get('url')
335                 if not asset_url or asset_url in urls:
336                     continue
337                 formats = self._extract_nrk_formats(asset_url, video_id)
338                 if not formats:
339                     continue
340                 self._sort_formats(formats)
341
342                 entry_id, entry_title = video_id_and_title(num)
343                 duration = parse_duration(asset.get('duration'))
344                 subtitles = {}
345                 for subtitle in ('webVtt', 'timedText'):
346                     subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
347                     if subtitle_url:
348                         subtitles.setdefault('no', []).append({
349                             'url': compat_urllib_parse_unquote(subtitle_url)
350                         })
351                 entries.append({
352                     'id': asset.get('carrierId') or entry_id,
353                     'title': make_title(entry_title),
354                     'duration': duration,
355                     'subtitles': subtitles,
356                     'formats': formats,
357                 })
358
359         if not entries:
360             media_url = data.get('mediaUrl')
361             if media_url and media_url not in urls:
362                 formats = self._extract_nrk_formats(media_url, video_id)
363                 if formats:
364                     self._sort_formats(formats)
365                     duration = parse_duration(data.get('duration'))
366                     entries = [{
367                         'id': video_id,
368                         'title': make_title(title),
369                         'duration': duration,
370                         'formats': formats,
371                     }]
372
373         if not entries:
374             self._raise_error(data)
375
376         series = conviva.get('seriesName') or data.get('seriesTitle')
377         episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
378
379         season_number = None
380         episode_number = None
381         if data.get('mediaElementType') == 'Episode':
382             _season_episode = data.get('scoresStatistics', {}).get('springStreamStream') or \
383                 data.get('relativeOriginUrl', '')
384             EPISODENUM_RE = [
385                 r'/s(?P<season>\d{,2})e(?P<episode>\d{,2})\.',
386                 r'/sesong-(?P<season>\d{,2})/episode-(?P<episode>\d{,2})',
387             ]
388             season_number = int_or_none(self._search_regex(
389                 EPISODENUM_RE, _season_episode, 'season number',
390                 default=None, group='season'))
391             episode_number = int_or_none(self._search_regex(
392                 EPISODENUM_RE, _season_episode, 'episode number',
393                 default=None, group='episode'))
394
395         thumbnails = None
396         images = data.get('images')
397         if images and isinstance(images, dict):
398             web_images = images.get('webImages')
399             if isinstance(web_images, list):
400                 thumbnails = [{
401                     'url': image['imageUrl'],
402                     'width': int_or_none(image.get('width')),
403                     'height': int_or_none(image.get('height')),
404                 } for image in web_images if image.get('imageUrl')]
405
406         description = data.get('description')
407         category = data.get('mediaAnalytics', {}).get('category')
408
409         common_info = {
410             'description': description,
411             'series': series,
412             'episode': episode,
413             'season_number': season_number,
414             'episode_number': episode_number,
415             'categories': [category] if category else None,
416             'age_limit': parse_age_limit(data.get('legalAge')),
417             'thumbnails': thumbnails,
418         }
419
420         vcodec = 'none' if data.get('mediaType') == 'Audio' else None
421
422         for entry in entries:
423             entry.update(common_info)
424             for f in entry['formats']:
425                 f['vcodec'] = vcodec
426
427         points = data.get('shortIndexPoints')
428         if isinstance(points, list):
429             chapters = []
430             for next_num, point in enumerate(points, start=1):
431                 if not isinstance(point, dict):
432                     continue
433                 start_time = parse_duration(point.get('startPoint'))
434                 if start_time is None:
435                     continue
436                 end_time = parse_duration(
437                     data.get('duration')
438                     if next_num == len(points)
439                     else points[next_num].get('startPoint'))
440                 if end_time is None:
441                     continue
442                 chapters.append({
443                     'start_time': start_time,
444                     'end_time': end_time,
445                     'title': point.get('title'),
446                 })
447             if chapters and len(entries) == 1:
448                 entries[0]['chapters'] = chapters
449
450         return self.playlist_result(entries, video_id, title, description)
451
452     def _real_extract(self, url):
453         video_id = self._match_id(url)
454         return self._extract_from_mediaelement(video_id)
455
456
457 class NRKTVEpisodeIE(InfoExtractor):
458     _VALID_URL = r'https?://tv\.nrk\.no/serie/(?P<id>[^/]+/sesong/\d+/episode/\d+)'
459     _TESTS = [{
460         'url': 'https://tv.nrk.no/serie/hellums-kro/sesong/1/episode/2',
461         'info_dict': {
462             'id': 'MUHH36005220BA',
463             'ext': 'mp4',
464             'title': 'Kro, krig og kjærlighet 2:6',
465             'description': 'md5:b32a7dc0b1ed27c8064f58b97bda4350',
466             'duration': 1563,
467             'series': 'Hellums kro',
468             'season_number': 1,
469             'episode_number': 2,
470             'episode': '2:6',
471             'age_limit': 6,
472         },
473         'params': {
474             'skip_download': True,
475         },
476     }, {
477         'url': 'https://tv.nrk.no/serie/backstage/sesong/1/episode/8',
478         'info_dict': {
479             'id': 'MSUI14000816AA',
480             'ext': 'mp4',
481             'title': 'Backstage 8:30',
482             'description': 'md5:de6ca5d5a2d56849e4021f2bf2850df4',
483             'duration': 1320,
484             'series': 'Backstage',
485             'season_number': 1,
486             'episode_number': 8,
487             'episode': '8:30',
488         },
489         'params': {
490             'skip_download': True,
491         },
492         'skip': 'ProgramRightsHasExpired',
493     }]
494
495     def _real_extract(self, url):
496         display_id = self._match_id(url)
497
498         webpage = self._download_webpage(url, display_id)
499
500         info = self._search_json_ld(webpage, display_id, default={})
501         nrk_id = info.get('@id') or self._html_search_meta(
502             'nrk:program-id', webpage, default=None) or self._search_regex(
503             r'data-program-id=["\'](%s)' % NRKTVIE._EPISODE_RE, webpage,
504             'nrk id')
505         assert re.match(NRKTVIE._EPISODE_RE, nrk_id)
506
507         info.update({
508             '_type': 'url_transparent',
509             'id': nrk_id,
510             'url': 'nrk:%s' % nrk_id,
511             'ie_key': NRKIE.ie_key(),
512         })
513         return info
514
515
516 class NRKTVSerieBaseIE(InfoExtractor):
517     def _extract_series(self, webpage, display_id, fatal=True):
518         config = self._parse_json(
519             self._search_regex(
520                 (r'INITIAL_DATA(?:_V\d)?_*\s*=\s*({.+?})\s*;',
521                  r'({.+?})\s*,\s*"[^"]+"\s*\)\s*</script>',
522                  r'PRELOADED_STATE_*\s*=\s*({.+?})\s*\n'),
523                 webpage, 'config', default='{}' if not fatal else NO_DEFAULT),
524             display_id, fatal=False, transform_source=js_to_json)
525         if not config:
526             return
527         return try_get(
528             config,
529             (lambda x: x['initialState']['series'], lambda x: x['series']),
530             dict)
531
532     def _extract_seasons(self, domain, series_id, seasons):
533         if isinstance(seasons, dict):
534             seasons = seasons.get('seasons')
535         if not isinstance(seasons, list):
536             return []
537         entries = []
538         for season in seasons:
539             if not isinstance(season, dict):
540                 continue
541             episodes = self._extract_episodes(season)
542             if episodes:
543                 entries.extend(episodes)
544                 continue
545             season_name = season.get('name')
546             if season_name and isinstance(season_name, compat_str):
547                 entries.append(self.url_result(
548                     'https://%s.nrk.no/serie/%s/sesong/%s'
549                     % (domain, series_id, season_name),
550                     ie=NRKTVSeasonIE.ie_key(),
551                     video_title=season.get('title')))
552         return entries
553
554     def _extract_episodes(self, season):
555         if not isinstance(season, dict):
556             return []
557         return self._extract_entries(season.get('episodes'))
558
559     def _extract_entries(self, entry_list):
560         if not isinstance(entry_list, list):
561             return []
562         entries = []
563         for episode in entry_list:
564             nrk_id = episode.get('prfId') or episode.get('episodeId')
565             if not nrk_id or not isinstance(nrk_id, compat_str):
566                 continue
567             if not re.match(NRKTVIE._EPISODE_RE, nrk_id):
568                 continue
569             entries.append(self.url_result(
570                 'nrk:%s' % nrk_id, ie=NRKIE.ie_key(), video_id=nrk_id))
571         return entries
572
573     _ASSETS_KEYS = ('episodes', 'instalments',)
574
575     def _extract_assets_key(self, embedded):
576         for asset_key in self._ASSETS_KEYS:
577             if embedded.get(asset_key):
578                 return asset_key
579
580     def _entries(self, data, display_id):
581         for page_num in itertools.count(1):
582             embedded = data.get('_embedded')
583             if not isinstance(embedded, dict):
584                 break
585             assets_key = self._extract_assets_key(embedded)
586             if not assets_key:
587                 break
588             # Extract entries
589             entries = try_get(
590                 embedded,
591                 (lambda x: x[assets_key]['_embedded'][assets_key],
592                  lambda x: x[assets_key]),
593                 list)
594             for e in self._extract_entries(entries):
595                 yield e
596             # Find next URL
597             next_url = urljoin(
598                 'https://psapi.nrk.no/',
599                 try_get(
600                     data,
601                     (lambda x: x['_links']['next']['href'],
602                      lambda x: x['_embedded'][assets_key]['_links']['next']['href']),
603                     compat_str))
604             if not next_url:
605                 break
606             data = self._download_json(
607                 next_url, display_id,
608                 'Downloading %s JSON page %d' % (assets_key, page_num),
609                 fatal=False)
610             if not data:
611                 break
612
613
614 class NRKTVSeasonIE(NRKTVSerieBaseIE):
615     _VALID_URL = r'https?://(?P<domain>tv|radio)\.nrk\.no/serie/(?P<serie>[^/]+)/(?:sesong/)?(?P<id>\d+)'
616     _TESTS = [{
617         'url': 'https://tv.nrk.no/serie/backstage/sesong/1',
618         'info_dict': {
619             'id': 'backstage/1',
620             'title': 'Sesong 1',
621         },
622         'playlist_mincount': 30,
623     }, {
624         # no /sesong/ in path
625         'url': 'https://tv.nrk.no/serie/lindmo/2016',
626         'info_dict': {
627             'id': 'lindmo/2016',
628             'title': '2016',
629         },
630         'playlist_mincount': 29,
631     }, {
632         # weird nested _embedded in catalog JSON response
633         'url': 'https://radio.nrk.no/serie/dickie-dick-dickens/sesong/1',
634         'info_dict': {
635             'id': 'dickie-dick-dickens/1',
636             'title': 'Sesong 1',
637         },
638         'playlist_mincount': 11,
639     }, {
640         # 841 entries, multi page
641         'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201509',
642         'info_dict': {
643             'id': 'dagsnytt/201509',
644             'title': 'September 2015',
645         },
646         'playlist_mincount': 841,
647     }, {
648         # 180 entries, single page
649         'url': 'https://tv.nrk.no/serie/spangas/sesong/1',
650         'only_matching': True,
651     }]
652
653     @classmethod
654     def suitable(cls, url):
655         return (False if NRKTVIE.suitable(url) or NRKTVEpisodeIE.suitable(url)
656                 else super(NRKTVSeasonIE, cls).suitable(url))
657
658     def _real_extract(self, url):
659         mobj = re.match(self._VALID_URL, url)
660         domain = mobj.group('domain')
661         serie = mobj.group('serie')
662         season_id = mobj.group('id')
663         display_id = '%s/%s' % (serie, season_id)
664
665         data = self._download_json(
666             'https://psapi.nrk.no/%s/catalog/series/%s/seasons/%s'
667             % (domain, serie, season_id), display_id, query={'pageSize': 50})
668
669         title = try_get(data, lambda x: x['titles']['title'], compat_str) or display_id
670         return self.playlist_result(
671             self._entries(data, display_id),
672             display_id, title)
673
674
675 class NRKTVSeriesIE(NRKTVSerieBaseIE):
676     _VALID_URL = r'https?://(?P<domain>tv|radio)\.nrk(?:super)?\.no/serie/(?P<id>[^/]+)'
677     _ITEM_RE = r'(?:data-season=["\']|id=["\']season-)(?P<id>\d+)'
678     _TESTS = [{
679         # new layout, instalments
680         'url': 'https://tv.nrk.no/serie/groenn-glede',
681         'info_dict': {
682             'id': 'groenn-glede',
683             'title': 'Grønn glede',
684             'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
685         },
686         'playlist_mincount': 90,
687     }, {
688         # new layout, instalments, more entries
689         'url': 'https://tv.nrk.no/serie/lindmo',
690         'only_matching': True,
691     }, {
692         'url': 'https://tv.nrk.no/serie/blank',
693         'info_dict': {
694             'id': 'blank',
695             'title': 'Blank',
696             'description': 'md5:7664b4e7e77dc6810cd3bca367c25b6e',
697         },
698         'playlist_mincount': 30,
699         'expected_warnings': ['HTTP Error 404: Not Found'],
700     }, {
701         # new layout, seasons
702         'url': 'https://tv.nrk.no/serie/backstage',
703         'info_dict': {
704             'id': 'backstage',
705             'title': 'Backstage',
706             'description': 'md5:63692ceb96813d9a207e9910483d948b',
707         },
708         'playlist_mincount': 60,
709         'expected_warnings': ['HTTP Error 404: Not Found'],
710     }, {
711         # old layout
712         'url': 'https://tv.nrksuper.no/serie/labyrint',
713         'info_dict': {
714             'id': 'labyrint',
715             'title': 'Labyrint',
716             'description': 'md5:318b597330fdac5959247c9b69fdb1ec',
717         },
718         'playlist_mincount': 3,
719     }, {
720         'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
721         'only_matching': True,
722     }, {
723         'url': 'https://tv.nrk.no/serie/saving-the-human-race',
724         'only_matching': True,
725     }, {
726         'url': 'https://tv.nrk.no/serie/postmann-pat',
727         'only_matching': True,
728     }, {
729         'url': 'https://radio.nrk.no/serie/dickie-dick-dickens',
730         'info_dict': {
731             'id': 'dickie-dick-dickens',
732         },
733         'playlist_mincount': 8,
734         'expected_warnings': ['HTTP Error 404: Not Found'],
735     }]
736
737     @classmethod
738     def suitable(cls, url):
739         return (
740             False if any(ie.suitable(url)
741                          for ie in (NRKTVIE, NRKTVEpisodeIE, NRKTVSeasonIE))
742             else super(NRKTVSeriesIE, cls).suitable(url))
743
744     def _real_extract(self, url):
745         mobj = re.match(self._VALID_URL, url)
746         domain = mobj.group('domain')
747         series_id = mobj.group('id')
748
749         title = description = None
750
751         webpage = self._download_webpage(url, series_id)
752
753         series = self._extract_series(webpage, series_id, fatal=False)
754         if series:
755             title = try_get(series, lambda x: x['titles']['title'], compat_str)
756             description = try_get(
757                 series, lambda x: x['titles']['subtitle'], compat_str)
758
759         data = self._download_json(
760             'https://psapi.nrk.no/%s/catalog/series/%s/instalments'
761             % (domain, series_id), series_id, query={'pageSize': 50},
762             fatal=False)
763         if data:
764             return self.playlist_result(
765                 self._entries(data, series_id), series_id, title, description)
766
767         # New layout (e.g. https://tv.nrk.no/serie/backstage)
768         if series:
769             entries = []
770             entries.extend(self._extract_seasons(domain, series_id, series.get('seasons')))
771             entries.extend(self._extract_entries(series.get('instalments')))
772             entries.extend(self._extract_episodes(series.get('extraMaterial')))
773             return self.playlist_result(entries, series_id, title, description)
774
775         # Old layout (e.g. https://tv.nrksuper.no/serie/labyrint)
776         entries = [
777             self.url_result(
778                 'https://tv.nrk.no/program/Episodes/{series}/{season}'.format(
779                     series=series_id, season=season_id))
780             for season_id in re.findall(self._ITEM_RE, webpage)
781         ]
782
783         title = self._html_search_meta(
784             'seriestitle', webpage,
785             'title', default=None) or self._og_search_title(
786             webpage, fatal=False)
787         if title:
788             title = self._search_regex(
789                 r'NRK (?:Super )?TV\s*[-–]\s*(.+)', title, 'title', default=title)
790
791         description = self._html_search_meta(
792             'series_description', webpage,
793             'description', default=None) or self._og_search_description(webpage)
794
795         return self.playlist_result(entries, series_id, title, description)
796
797
798 class NRKTVDirekteIE(NRKTVIE):
799     IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
800     _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
801
802     _TESTS = [{
803         'url': 'https://tv.nrk.no/direkte/nrk1',
804         'only_matching': True,
805     }, {
806         'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
807         'only_matching': True,
808     }]
809
810
811 class NRKPlaylistBaseIE(InfoExtractor):
812     def _extract_description(self, webpage):
813         pass
814
815     def _real_extract(self, url):
816         playlist_id = self._match_id(url)
817
818         webpage = self._download_webpage(url, playlist_id)
819
820         entries = [
821             self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
822             for video_id in re.findall(self._ITEM_RE, webpage)
823         ]
824
825         playlist_title = self. _extract_title(webpage)
826         playlist_description = self._extract_description(webpage)
827
828         return self.playlist_result(
829             entries, playlist_id, playlist_title, playlist_description)
830
831
832 class NRKPlaylistIE(NRKPlaylistBaseIE):
833     _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
834     _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
835     _TESTS = [{
836         'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
837         'info_dict': {
838             'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
839             'title': 'Gjenopplev den historiske solformørkelsen',
840             'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
841         },
842         'playlist_count': 2,
843     }, {
844         'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
845         'info_dict': {
846             'id': 'rivertonprisen-til-karin-fossum-1.12266449',
847             'title': 'Rivertonprisen til Karin Fossum',
848             'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
849         },
850         'playlist_count': 2,
851     }]
852
853     def _extract_title(self, webpage):
854         return self._og_search_title(webpage, fatal=False)
855
856     def _extract_description(self, webpage):
857         return self._og_search_description(webpage)
858
859
860 class NRKTVEpisodesIE(NRKPlaylistBaseIE):
861     _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
862     _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
863     _TESTS = [{
864         'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
865         'info_dict': {
866             'id': '69031',
867             'title': 'Nytt på nytt, sesong: 201210',
868         },
869         'playlist_count': 4,
870     }]
871
872     def _extract_title(self, webpage):
873         return self._html_search_regex(
874             r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
875
876
877 class NRKSkoleIE(InfoExtractor):
878     IE_DESC = 'NRK Skole'
879     _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
880
881     _TESTS = [{
882         'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
883         'md5': '18c12c3d071953c3bf8d54ef6b2587b7',
884         'info_dict': {
885             'id': '6021',
886             'ext': 'mp4',
887             'title': 'Genetikk og eneggede tvillinger',
888             'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
889             'duration': 399,
890         },
891     }, {
892         'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
893         'only_matching': True,
894     }]
895
896     def _real_extract(self, url):
897         video_id = self._match_id(url)
898
899         webpage = self._download_webpage(
900             'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
901             video_id)
902
903         nrk_id = self._parse_json(
904             self._search_regex(
905                 r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
906                 webpage, 'application json'),
907             video_id)['activeMedia']['psId']
908
909         return self.url_result('nrk:%s' % nrk_id)