]> asedeno.scripts.mit.edu Git - youtube-dl.git/blob - youtube_dl/extractor/nrk.py
[nrk] Inline _extract_from_playback
[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         return {
208             'id': video_id,
209             'title': title,
210             'alt_title': alt_title,
211             'description': description,
212             'duration': duration,
213             'thumbnails': thumbnails,
214             'formats': formats,
215         }
216
217
218 class NRKTVIE(InfoExtractor):
219     IE_DESC = 'NRK TV and NRK Radio'
220     _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
221     _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/(?:[^/]+/)*%s' % _EPISODE_RE
222     _TESTS = [{
223         'url': 'https://tv.nrk.no/program/MDDP12000117',
224         'md5': 'c4a5960f1b00b40d47db65c1064e0ab1',
225         'info_dict': {
226             'id': 'MDDP12000117AA',
227             'ext': 'mp4',
228             'title': 'Alarm Trolltunga',
229             'description': 'md5:46923a6e6510eefcce23d5ef2a58f2ce',
230             'duration': 2223.44,
231             'age_limit': 6,
232         },
233     }, {
234         'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
235         'md5': '8d40dab61cea8ab0114e090b029a0565',
236         'info_dict': {
237             'id': 'MUHH48000314AA',
238             'ext': 'mp4',
239             'title': '20 spørsmål 23.05.2014',
240             'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
241             'duration': 1741,
242             'series': '20 spørsmål',
243             'episode': '23.05.2014',
244         },
245     }, {
246         'url': 'https://tv.nrk.no/program/mdfp15000514',
247         'info_dict': {
248             'id': 'MDFP15000514CA',
249             'ext': 'mp4',
250             'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
251             'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
252             'duration': 4605.08,
253             'series': 'Kunnskapskanalen',
254             'episode': '24.05.2014',
255         },
256         'params': {
257             'skip_download': True,
258         },
259     }, {
260         # single playlist video
261         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
262         'info_dict': {
263             'id': 'MSPO40010515AH',
264             'ext': 'mp4',
265             'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
266             'description': 'md5:c03aba1e917561eface5214020551b7a',
267         },
268         'params': {
269             'skip_download': True,
270         },
271         'expected_warnings': ['Failed to download m3u8 information'],
272         'skip': 'particular part is not supported currently',
273     }, {
274         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
275         'info_dict': {
276             'id': 'MSPO40010515AH',
277             'ext': 'mp4',
278             'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
279             'description': 'md5:c03aba1e917561eface5214020551b7a',
280         },
281         'expected_warnings': ['Failed to download m3u8 information'],
282     }, {
283         'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
284         'info_dict': {
285             'id': 'KMTE50001317AA',
286             'ext': 'mp4',
287             'title': 'Anno 13:30',
288             'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
289             'duration': 2340,
290             'series': 'Anno',
291             'episode': '13:30',
292             'season_number': 3,
293             'episode_number': 13,
294         },
295         'params': {
296             'skip_download': True,
297         },
298     }, {
299         'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
300         'info_dict': {
301             'id': 'MUHH46000317AA',
302             'ext': 'mp4',
303             'title': 'Nytt på Nytt 27.01.2017',
304             'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
305             'duration': 1796,
306             'series': 'Nytt på nytt',
307             'episode': '27.01.2017',
308         },
309         'params': {
310             'skip_download': True,
311         },
312         'skip': 'ProgramRightsHasExpired',
313     }, {
314         'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
315         'only_matching': True,
316     }, {
317         'url': 'https://tv.nrk.no/serie/lindmo/2018/MUHU11006318/avspiller',
318         'only_matching': True,
319     }, {
320         'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201507/NPUB21019315',
321         'only_matching': True,
322     }]
323
324     def _real_extract(self, url):
325         video_id = self._match_id(url)
326         return self.url_result(
327             'nrk:%s' % video_id, ie=NRKIE.ie_key(), video_id=video_id)
328
329
330 class NRKTVEpisodeIE(InfoExtractor):
331     _VALID_URL = r'https?://tv\.nrk\.no/serie/(?P<id>[^/]+/sesong/\d+/episode/\d+)'
332     _TESTS = [{
333         'url': 'https://tv.nrk.no/serie/hellums-kro/sesong/1/episode/2',
334         'info_dict': {
335             'id': 'MUHH36005220BA',
336             'ext': 'mp4',
337             'title': 'Kro, krig og kjærlighet 2:6',
338             'description': 'md5:b32a7dc0b1ed27c8064f58b97bda4350',
339             'duration': 1563,
340             'series': 'Hellums kro',
341             'season_number': 1,
342             'episode_number': 2,
343             'episode': '2:6',
344             'age_limit': 6,
345         },
346         'params': {
347             'skip_download': True,
348         },
349     }, {
350         'url': 'https://tv.nrk.no/serie/backstage/sesong/1/episode/8',
351         'info_dict': {
352             'id': 'MSUI14000816AA',
353             'ext': 'mp4',
354             'title': 'Backstage 8:30',
355             'description': 'md5:de6ca5d5a2d56849e4021f2bf2850df4',
356             'duration': 1320,
357             'series': 'Backstage',
358             'season_number': 1,
359             'episode_number': 8,
360             'episode': '8:30',
361         },
362         'params': {
363             'skip_download': True,
364         },
365         'skip': 'ProgramRightsHasExpired',
366     }]
367
368     def _real_extract(self, url):
369         display_id = self._match_id(url)
370
371         webpage = self._download_webpage(url, display_id)
372
373         info = self._search_json_ld(webpage, display_id, default={})
374         nrk_id = info.get('@id') or self._html_search_meta(
375             'nrk:program-id', webpage, default=None) or self._search_regex(
376             r'data-program-id=["\'](%s)' % NRKTVIE._EPISODE_RE, webpage,
377             'nrk id')
378         assert re.match(NRKTVIE._EPISODE_RE, nrk_id)
379
380         info.update({
381             '_type': 'url_transparent',
382             'id': nrk_id,
383             'url': 'nrk:%s' % nrk_id,
384             'ie_key': NRKIE.ie_key(),
385         })
386         return info
387
388
389 class NRKTVSerieBaseIE(NRKBaseIE):
390     def _extract_entries(self, entry_list):
391         if not isinstance(entry_list, list):
392             return []
393         entries = []
394         for episode in entry_list:
395             nrk_id = episode.get('prfId') or episode.get('episodeId')
396             if not nrk_id or not isinstance(nrk_id, compat_str):
397                 continue
398             entries.append(self.url_result(
399                 'nrk:%s' % nrk_id, ie=NRKIE.ie_key(), video_id=nrk_id))
400         return entries
401
402     _ASSETS_KEYS = ('episodes', 'instalments',)
403
404     def _extract_assets_key(self, embedded):
405         for asset_key in self._ASSETS_KEYS:
406             if embedded.get(asset_key):
407                 return asset_key
408
409     @staticmethod
410     def _catalog_name(serie_kind):
411         return 'podcast' if serie_kind in ('podcast', 'podkast') else 'series'
412
413     def _entries(self, data, display_id):
414         for page_num in itertools.count(1):
415             embedded = data.get('_embedded') or data
416             if not isinstance(embedded, dict):
417                 break
418             assets_key = self._extract_assets_key(embedded)
419             if not assets_key:
420                 break
421             # Extract entries
422             entries = try_get(
423                 embedded,
424                 (lambda x: x[assets_key]['_embedded'][assets_key],
425                  lambda x: x[assets_key]),
426                 list)
427             for e in self._extract_entries(entries):
428                 yield e
429             # Find next URL
430             next_url_path = try_get(
431                 data,
432                 (lambda x: x['_links']['next']['href'],
433                  lambda x: x['_embedded'][assets_key]['_links']['next']['href']),
434                 compat_str)
435             if not next_url_path:
436                 break
437             data = self._call_api(
438                 next_url_path, display_id,
439                 note='Downloading %s JSON page %d' % (assets_key, page_num),
440                 fatal=False)
441             if not data:
442                 break
443
444
445 class NRKTVSeasonIE(NRKTVSerieBaseIE):
446     _VALID_URL = r'''(?x)
447                     https?://
448                         (?P<domain>tv|radio)\.nrk\.no/
449                         (?P<serie_kind>serie|pod[ck]ast)/
450                         (?P<serie>[^/]+)/
451                         (?:
452                             (?:sesong/)?(?P<id>\d+)|
453                             sesong/(?P<id_2>[^/?#&]+)
454                         )
455                     '''
456     _TESTS = [{
457         'url': 'https://tv.nrk.no/serie/backstage/sesong/1',
458         'info_dict': {
459             'id': 'backstage/1',
460             'title': 'Sesong 1',
461         },
462         'playlist_mincount': 30,
463     }, {
464         # no /sesong/ in path
465         'url': 'https://tv.nrk.no/serie/lindmo/2016',
466         'info_dict': {
467             'id': 'lindmo/2016',
468             'title': '2016',
469         },
470         'playlist_mincount': 29,
471     }, {
472         # weird nested _embedded in catalog JSON response
473         'url': 'https://radio.nrk.no/serie/dickie-dick-dickens/sesong/1',
474         'info_dict': {
475             'id': 'dickie-dick-dickens/1',
476             'title': 'Sesong 1',
477         },
478         'playlist_mincount': 11,
479     }, {
480         # 841 entries, multi page
481         'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201509',
482         'info_dict': {
483             'id': 'dagsnytt/201509',
484             'title': 'September 2015',
485         },
486         'playlist_mincount': 841,
487     }, {
488         # 180 entries, single page
489         'url': 'https://tv.nrk.no/serie/spangas/sesong/1',
490         'only_matching': True,
491     }, {
492         'url': 'https://radio.nrk.no/podkast/hele_historien/sesong/diagnose-kverulant',
493         'info_dict': {
494             'id': 'hele_historien/diagnose-kverulant',
495             'title': 'Diagnose kverulant',
496         },
497         'playlist_mincount': 3,
498     }, {
499         'url': 'https://radio.nrk.no/podkast/loerdagsraadet/sesong/202101',
500         'only_matching': True,
501     }]
502
503     @classmethod
504     def suitable(cls, url):
505         return (False if NRKTVIE.suitable(url) or NRKTVEpisodeIE.suitable(url) or NRKRadioPodkastIE.suitable(url)
506                 else super(NRKTVSeasonIE, cls).suitable(url))
507
508     def _real_extract(self, url):
509         mobj = re.match(self._VALID_URL, url)
510         domain = mobj.group('domain')
511         serie_kind = mobj.group('serie_kind')
512         serie = mobj.group('serie')
513         season_id = mobj.group('id') or mobj.group('id_2')
514         display_id = '%s/%s' % (serie, season_id)
515
516         data = self._call_api(
517             '%s/catalog/%s/%s/seasons/%s'
518             % (domain, self._catalog_name(serie_kind), serie, season_id),
519             display_id, 'season', query={'pageSize': 50})
520
521         title = try_get(data, lambda x: x['titles']['title'], compat_str) or display_id
522         return self.playlist_result(
523             self._entries(data, display_id),
524             display_id, title)
525
526
527 class NRKTVSeriesIE(NRKTVSerieBaseIE):
528     _VALID_URL = r'https?://(?P<domain>(?:tv|radio)\.nrk|(?:tv\.)?nrksuper)\.no/(?P<serie_kind>serie|pod[ck]ast)/(?P<id>[^/]+)'
529     _TESTS = [{
530         # new layout, instalments
531         'url': 'https://tv.nrk.no/serie/groenn-glede',
532         'info_dict': {
533             'id': 'groenn-glede',
534             'title': 'Grønn glede',
535             'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
536         },
537         'playlist_mincount': 90,
538     }, {
539         # new layout, instalments, more entries
540         'url': 'https://tv.nrk.no/serie/lindmo',
541         'only_matching': True,
542     }, {
543         'url': 'https://tv.nrk.no/serie/blank',
544         'info_dict': {
545             'id': 'blank',
546             'title': 'Blank',
547             'description': 'md5:7664b4e7e77dc6810cd3bca367c25b6e',
548         },
549         'playlist_mincount': 30,
550     }, {
551         # new layout, seasons
552         'url': 'https://tv.nrk.no/serie/backstage',
553         'info_dict': {
554             'id': 'backstage',
555             'title': 'Backstage',
556             'description': 'md5:63692ceb96813d9a207e9910483d948b',
557         },
558         'playlist_mincount': 60,
559     }, {
560         # old layout
561         'url': 'https://tv.nrksuper.no/serie/labyrint',
562         'info_dict': {
563             'id': 'labyrint',
564             'title': 'Labyrint',
565             'description': 'I Daidalos sin undersjøiske Labyrint venter spennende oppgaver, skumle robotskapninger og slim.',
566         },
567         'playlist_mincount': 3,
568     }, {
569         'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
570         'only_matching': True,
571     }, {
572         'url': 'https://tv.nrk.no/serie/saving-the-human-race',
573         'only_matching': True,
574     }, {
575         'url': 'https://tv.nrk.no/serie/postmann-pat',
576         'only_matching': True,
577     }, {
578         'url': 'https://radio.nrk.no/serie/dickie-dick-dickens',
579         'info_dict': {
580             'id': 'dickie-dick-dickens',
581             'title': 'Dickie Dick Dickens',
582             'description': 'md5:19e67411ffe57f7dce08a943d7a0b91f',
583         },
584         'playlist_mincount': 8,
585     }, {
586         'url': 'https://nrksuper.no/serie/labyrint',
587         'only_matching': True,
588     }, {
589         'url': 'https://radio.nrk.no/podkast/ulrikkes_univers',
590         'info_dict': {
591             'id': 'ulrikkes_univers',
592         },
593         'playlist_mincount': 10,
594     }, {
595         'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/nrkno-poddkast-26588-134079-05042018030000',
596         'only_matching': True,
597     }]
598
599     @classmethod
600     def suitable(cls, url):
601         return (
602             False if any(ie.suitable(url)
603                          for ie in (NRKTVIE, NRKTVEpisodeIE, NRKRadioPodkastIE, NRKTVSeasonIE))
604             else super(NRKTVSeriesIE, cls).suitable(url))
605
606     def _real_extract(self, url):
607         site, serie_kind, series_id = re.match(self._VALID_URL, url).groups()
608         is_radio = site == 'radio.nrk'
609         domain = 'radio' if is_radio else 'tv'
610
611         size_prefix = 'p' if is_radio else 'embeddedInstalmentsP'
612         series = self._call_api(
613             '%s/catalog/%s/%s'
614             % (domain, self._catalog_name(serie_kind), series_id),
615             series_id, 'serie', query={size_prefix + 'ageSize': 50})
616         titles = try_get(series, [
617             lambda x: x['titles'],
618             lambda x: x[x['type']]['titles'],
619             lambda x: x[x['seriesType']]['titles'],
620         ]) or {}
621
622         entries = []
623         entries.extend(self._entries(series, series_id))
624         embedded = series.get('_embedded') or {}
625         linked_seasons = try_get(series, lambda x: x['_links']['seasons']) or []
626         embedded_seasons = embedded.get('seasons') or []
627         if len(linked_seasons) > len(embedded_seasons):
628             for season in linked_seasons:
629                 season_url = urljoin(url, season.get('href'))
630                 if not season_url:
631                     season_name = season.get('name')
632                     if season_name and isinstance(season_name, compat_str):
633                         season_url = 'https://%s.nrk.no/serie/%s/sesong/%s' % (domain, series_id, season_name)
634                 if season_url:
635                     entries.append(self.url_result(
636                         season_url, ie=NRKTVSeasonIE.ie_key(),
637                         video_title=season.get('title')))
638         else:
639             for season in embedded_seasons:
640                 entries.extend(self._entries(season, series_id))
641         entries.extend(self._entries(
642             embedded.get('extraMaterial') or {}, series_id))
643
644         return self.playlist_result(
645             entries, series_id, titles.get('title'), titles.get('subtitle'))
646
647
648 class NRKTVDirekteIE(NRKTVIE):
649     IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
650     _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
651
652     _TESTS = [{
653         'url': 'https://tv.nrk.no/direkte/nrk1',
654         'only_matching': True,
655     }, {
656         'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
657         'only_matching': True,
658     }]
659
660
661 class NRKRadioPodkastIE(InfoExtractor):
662     _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})'
663
664     _TESTS = [{
665         'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
666         'md5': '8d40dab61cea8ab0114e090b029a0565',
667         'info_dict': {
668             'id': 'MUHH48000314AA',
669             'ext': 'mp4',
670             'title': '20 spørsmål 23.05.2014',
671             'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
672             'duration': 1741,
673             'series': '20 spørsmål',
674             'episode': '23.05.2014',
675         },
676     }, {
677         'url': 'https://radio.nrk.no/podcast/ulrikkes_univers/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
678         'only_matching': True,
679     }, {
680         'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/sesong/1/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
681         'only_matching': True,
682     }, {
683         'url': 'https://radio.nrk.no/podkast/hele_historien/sesong/bortfoert-i-bergen/l_774d1a2c-7aa7-4965-8d1a-2c7aa7d9652c',
684         'only_matching': True,
685     }]
686
687     def _real_extract(self, url):
688         video_id = self._match_id(url)
689         return self.url_result(
690             'nrk:%s' % video_id, ie=NRKIE.ie_key(), video_id=video_id)
691
692
693 class NRKPlaylistBaseIE(InfoExtractor):
694     def _extract_description(self, webpage):
695         pass
696
697     def _real_extract(self, url):
698         playlist_id = self._match_id(url)
699
700         webpage = self._download_webpage(url, playlist_id)
701
702         entries = [
703             self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
704             for video_id in re.findall(self._ITEM_RE, webpage)
705         ]
706
707         playlist_title = self. _extract_title(webpage)
708         playlist_description = self._extract_description(webpage)
709
710         return self.playlist_result(
711             entries, playlist_id, playlist_title, playlist_description)
712
713
714 class NRKPlaylistIE(NRKPlaylistBaseIE):
715     _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
716     _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
717     _TESTS = [{
718         'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
719         'info_dict': {
720             'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
721             'title': 'Gjenopplev den historiske solformørkelsen',
722             'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
723         },
724         'playlist_count': 2,
725     }, {
726         'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
727         'info_dict': {
728             'id': 'rivertonprisen-til-karin-fossum-1.12266449',
729             'title': 'Rivertonprisen til Karin Fossum',
730             'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
731         },
732         'playlist_count': 2,
733     }]
734
735     def _extract_title(self, webpage):
736         return self._og_search_title(webpage, fatal=False)
737
738     def _extract_description(self, webpage):
739         return self._og_search_description(webpage)
740
741
742 class NRKTVEpisodesIE(NRKPlaylistBaseIE):
743     _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
744     _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
745     _TESTS = [{
746         'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
747         'info_dict': {
748             'id': '69031',
749             'title': 'Nytt på nytt, sesong: 201210',
750         },
751         'playlist_count': 4,
752     }]
753
754     def _extract_title(self, webpage):
755         return self._html_search_regex(
756             r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
757
758
759 class NRKSkoleIE(InfoExtractor):
760     IE_DESC = 'NRK Skole'
761     _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
762
763     _TESTS = [{
764         'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
765         'md5': '18c12c3d071953c3bf8d54ef6b2587b7',
766         'info_dict': {
767             'id': '6021',
768             'ext': 'mp4',
769             'title': 'Genetikk og eneggede tvillinger',
770             'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
771             'duration': 399,
772         },
773     }, {
774         'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
775         'only_matching': True,
776     }]
777
778     def _real_extract(self, url):
779         video_id = self._match_id(url)
780
781         nrk_id = self._download_json(
782             'https://nrkno-skole-prod.kube.nrk.no/skole/api/media/%s' % video_id,
783             video_id)['psId']
784
785         return self.url_result('nrk:%s' % nrk_id)