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