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