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