youtube-dl

Another place where youtube-dl lives on
git clone git://git.oshgnacknak.de/youtube-dl.git
Log | Files | Refs | README | LICENSE

nrk.py (31884B)


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