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