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