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