]> asedeno.scripts.mit.edu Git - youtube-dl.git/blob - youtube_dl/extractor/nrk.py
[nrktv] Relax _VALID_URL (closes #27299, closes #26185)
[youtube-dl.git] / youtube_dl / extractor / nrk.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_str,
9     compat_urllib_parse_unquote,
10 )
11 from ..utils import (
12     determine_ext,
13     ExtractorError,
14     int_or_none,
15     js_to_json,
16     NO_DEFAULT,
17     parse_age_limit,
18     parse_duration,
19     try_get,
20     url_or_none,
21 )
22
23
24 class NRKBaseIE(InfoExtractor):
25     _GEO_COUNTRIES = ['NO']
26
27
28 class NRKIE(NRKBaseIE):
29     _VALID_URL = r'''(?x)
30                         (?:
31                             nrk:|
32                             https?://
33                                 (?:
34                                     (?:www\.)?nrk\.no/video/(?:PS\*|[^_]+_)|
35                                     v8[-.]psapi\.nrk\.no/mediaelement/
36                                 )
37                             )
38                             (?P<id>[^?\#&]+)
39                         '''
40
41     _TESTS = [{
42         # video
43         'url': 'http://www.nrk.no/video/PS*150533',
44         'md5': '706f34cdf1322577589e369e522b50ef',
45         'info_dict': {
46             'id': '150533',
47             'ext': 'mp4',
48             'title': 'Dompap og andre fugler i Piip-Show',
49             'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
50             'duration': 262,
51         }
52     }, {
53         # audio
54         'url': 'http://www.nrk.no/video/PS*154915',
55         # MD5 is unstable
56         'info_dict': {
57             'id': '154915',
58             'ext': 'flv',
59             'title': 'Slik høres internett ut når du er blind',
60             'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
61             'duration': 20,
62         }
63     }, {
64         'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
65         'only_matching': True,
66     }, {
67         'url': 'nrk:clip/7707d5a3-ebe7-434a-87d5-a3ebe7a34a70',
68         'only_matching': True,
69     }, {
70         'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
71         'only_matching': True,
72     }, {
73         'url': 'https://www.nrk.no/video/dompap-og-andre-fugler-i-piip-show_150533',
74         'only_matching': True,
75     }, {
76         'url': 'https://www.nrk.no/video/humor/kommentatorboksen-reiser-til-sjos_d1fda11f-a4ad-437a-a374-0398bc84e999',
77         'only_matching': True,
78     }]
79
80     def _extract_from_playback(self, video_id):
81         manifest = self._download_json(
82             'http://psapi.nrk.no/playback/manifest/%s' % video_id,
83             video_id, 'Downloading manifest JSON')
84
85         playable = manifest['playable']
86
87         formats = []
88         for asset in playable['assets']:
89             if not isinstance(asset, dict):
90                 continue
91             if asset.get('encrypted'):
92                 continue
93             format_url = url_or_none(asset.get('url'))
94             if not format_url:
95                 continue
96             if asset.get('format') == 'HLS' or determine_ext(format_url) == 'm3u8':
97                 formats.extend(self._extract_m3u8_formats(
98                     format_url, video_id, 'mp4', entry_protocol='m3u8_native',
99                     m3u8_id='hls', fatal=False))
100         self._sort_formats(formats)
101
102         data = self._download_json(
103             'http://psapi.nrk.no/playback/metadata/%s' % video_id,
104             video_id, 'Downloading metadata JSON')
105
106         preplay = data['preplay']
107         titles = preplay['titles']
108         title = titles['title']
109         alt_title = titles.get('subtitle')
110
111         description = preplay.get('description')
112         duration = parse_duration(playable.get('duration')) or parse_duration(data.get('duration'))
113
114         thumbnails = []
115         for image in try_get(
116                 preplay, lambda x: x['poster']['images'], list) or []:
117             if not isinstance(image, dict):
118                 continue
119             image_url = url_or_none(image.get('url'))
120             if not image_url:
121                 continue
122             thumbnails.append({
123                 'url': image_url,
124                 'width': int_or_none(image.get('pixelWidth')),
125                 'height': int_or_none(image.get('pixelHeight')),
126             })
127
128         return {
129             'id': video_id,
130             'title': title,
131             'alt_title': alt_title,
132             'description': description,
133             'duration': duration,
134             'thumbnails': thumbnails,
135             'formats': formats,
136         }
137
138     def _real_extract(self, url):
139         video_id = self._match_id(url)
140         return self._extract_from_playback(video_id)
141
142
143 class NRKTVIE(NRKBaseIE):
144     IE_DESC = 'NRK TV and NRK Radio'
145     _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
146     _VALID_URL = r'''(?x)
147                         https?://
148                             (?:tv|radio)\.nrk(?:super)?\.no/
149                             (?:serie(?:/[^/]+){1,}|program)/
150                             (?![Ee]pisodes)%s
151                             (?:/\d{2}-\d{2}-\d{4})?
152                             (?:\#del=(?P<part_id>\d+))?
153                     ''' % _EPISODE_RE
154     _API_HOSTS = ('psapi-ne.nrk.no', 'psapi-we.nrk.no')
155     _TESTS = [{
156         'url': 'https://tv.nrk.no/program/MDDP12000117',
157         'md5': '8270824df46ec629b66aeaa5796b36fb',
158         'info_dict': {
159             'id': 'MDDP12000117AA',
160             'ext': 'mp4',
161             'title': 'Alarm Trolltunga',
162             'description': 'md5:46923a6e6510eefcce23d5ef2a58f2ce',
163             'duration': 2223,
164             'age_limit': 6,
165         },
166     }, {
167         'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
168         'md5': '9a167e54d04671eb6317a37b7bc8a280',
169         'info_dict': {
170             'id': 'MUHH48000314AA',
171             'ext': 'mp4',
172             'title': '20 spørsmål 23.05.2014',
173             'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
174             'duration': 1741,
175             'series': '20 spørsmål',
176             'episode': '23.05.2014',
177         },
178         'skip': 'NoProgramRights',
179     }, {
180         'url': 'https://tv.nrk.no/program/mdfp15000514',
181         'info_dict': {
182             'id': 'MDFP15000514CA',
183             'ext': 'mp4',
184             'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
185             'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
186             'duration': 4605,
187             'series': 'Kunnskapskanalen',
188             'episode': '24.05.2014',
189         },
190         'params': {
191             'skip_download': True,
192         },
193     }, {
194         # single playlist video
195         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
196         'info_dict': {
197             'id': 'MSPO40010515-part2',
198             'ext': 'flv',
199             'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
200             'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
201         },
202         'params': {
203             'skip_download': True,
204         },
205         'expected_warnings': ['Video is geo restricted'],
206         'skip': 'particular part is not supported currently',
207     }, {
208         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
209         'playlist': [{
210             'info_dict': {
211                 'id': 'MSPO40010515AH',
212                 'ext': 'mp4',
213                 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 1)',
214                 'description': 'md5:1f97a41f05a9486ee00c56f35f82993d',
215                 'duration': 772,
216                 'series': 'Tour de Ski',
217                 'episode': '06.01.2015',
218             },
219             'params': {
220                 'skip_download': True,
221             },
222         }, {
223             'info_dict': {
224                 'id': 'MSPO40010515BH',
225                 'ext': 'mp4',
226                 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 2)',
227                 'description': 'md5:1f97a41f05a9486ee00c56f35f82993d',
228                 'duration': 6175,
229                 'series': 'Tour de Ski',
230                 'episode': '06.01.2015',
231             },
232             'params': {
233                 'skip_download': True,
234             },
235         }],
236         'info_dict': {
237             'id': 'MSPO40010515',
238             'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
239             'description': 'md5:1f97a41f05a9486ee00c56f35f82993d',
240         },
241         'expected_warnings': ['Video is geo restricted'],
242     }, {
243         'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
244         'info_dict': {
245             'id': 'KMTE50001317AA',
246             'ext': 'mp4',
247             'title': 'Anno 13:30',
248             'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
249             'duration': 2340,
250             'series': 'Anno',
251             'episode': '13:30',
252             'season_number': 3,
253             'episode_number': 13,
254         },
255         'params': {
256             'skip_download': True,
257         },
258     }, {
259         'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
260         'info_dict': {
261             'id': 'MUHH46000317AA',
262             'ext': 'mp4',
263             'title': 'Nytt på Nytt 27.01.2017',
264             'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
265             'duration': 1796,
266             'series': 'Nytt på nytt',
267             'episode': '27.01.2017',
268         },
269         'params': {
270             'skip_download': True,
271         },
272     }, {
273         'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
274         'only_matching': True,
275     }, {
276         'url': 'https://tv.nrk.no/serie/lindmo/2018/MUHU11006318/avspiller',
277         'only_matching': True,
278     }, {
279         'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201507/NPUB21019315',
280         'only_matching': True,
281     }]
282
283     _api_host = None
284
285     def _extract_from_mediaelement(self, video_id):
286         api_hosts = (self._api_host, ) if self._api_host else self._API_HOSTS
287
288         for api_host in api_hosts:
289             data = self._download_json(
290                 'http://%s/mediaelement/%s' % (api_host, video_id),
291                 video_id, 'Downloading mediaelement JSON',
292                 fatal=api_host == api_hosts[-1])
293             if not data:
294                 continue
295             self._api_host = api_host
296             break
297
298         title = data.get('fullTitle') or data.get('mainTitle') or data['title']
299         video_id = data.get('id') or video_id
300
301         entries = []
302
303         conviva = data.get('convivaStatistics') or {}
304         live = (data.get('mediaElementType') == 'Live'
305                 or data.get('isLive') is True or conviva.get('isLive'))
306
307         def make_title(t):
308             return self._live_title(t) if live else t
309
310         media_assets = data.get('mediaAssets')
311         if media_assets and isinstance(media_assets, list):
312             def video_id_and_title(idx):
313                 return ((video_id, title) if len(media_assets) == 1
314                         else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
315             for num, asset in enumerate(media_assets, 1):
316                 asset_url = asset.get('url')
317                 if not asset_url:
318                     continue
319                 formats = self._extract_akamai_formats(asset_url, video_id)
320                 if not formats:
321                     continue
322                 self._sort_formats(formats)
323
324                 # Some f4m streams may not work with hdcore in fragments' URLs
325                 for f in formats:
326                     extra_param = f.get('extra_param_to_segment_url')
327                     if extra_param and 'hdcore' in extra_param:
328                         del f['extra_param_to_segment_url']
329
330                 entry_id, entry_title = video_id_and_title(num)
331                 duration = parse_duration(asset.get('duration'))
332                 subtitles = {}
333                 for subtitle in ('webVtt', 'timedText'):
334                     subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
335                     if subtitle_url:
336                         subtitles.setdefault('no', []).append({
337                             'url': compat_urllib_parse_unquote(subtitle_url)
338                         })
339                 entries.append({
340                     'id': asset.get('carrierId') or entry_id,
341                     'title': make_title(entry_title),
342                     'duration': duration,
343                     'subtitles': subtitles,
344                     'formats': formats,
345                 })
346
347         if not entries:
348             media_url = data.get('mediaUrl')
349             if media_url:
350                 formats = self._extract_akamai_formats(media_url, video_id)
351                 self._sort_formats(formats)
352                 duration = parse_duration(data.get('duration'))
353                 entries = [{
354                     'id': video_id,
355                     'title': make_title(title),
356                     'duration': duration,
357                     'formats': formats,
358                 }]
359
360         if not entries:
361             MESSAGES = {
362                 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
363                 'ProgramRightsHasExpired': 'Programmet har gått ut',
364                 'NoProgramRights': 'Ikke tilgjengelig',
365                 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
366             }
367             message_type = data.get('messageType', '')
368             # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
369             if 'IsGeoBlocked' in message_type:
370                 self.raise_geo_restricted(
371                     msg=MESSAGES.get('ProgramIsGeoBlocked'),
372                     countries=self._GEO_COUNTRIES)
373             raise ExtractorError(
374                 '%s said: %s' % (self.IE_NAME, MESSAGES.get(
375                     message_type, message_type)),
376                 expected=True)
377
378         series = conviva.get('seriesName') or data.get('seriesTitle')
379         episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
380
381         season_number = None
382         episode_number = None
383         if data.get('mediaElementType') == 'Episode':
384             _season_episode = data.get('scoresStatistics', {}).get('springStreamStream') or \
385                 data.get('relativeOriginUrl', '')
386             EPISODENUM_RE = [
387                 r'/s(?P<season>\d{,2})e(?P<episode>\d{,2})\.',
388                 r'/sesong-(?P<season>\d{,2})/episode-(?P<episode>\d{,2})',
389             ]
390             season_number = int_or_none(self._search_regex(
391                 EPISODENUM_RE, _season_episode, 'season number',
392                 default=None, group='season'))
393             episode_number = int_or_none(self._search_regex(
394                 EPISODENUM_RE, _season_episode, 'episode number',
395                 default=None, group='episode'))
396
397         thumbnails = None
398         images = data.get('images')
399         if images and isinstance(images, dict):
400             web_images = images.get('webImages')
401             if isinstance(web_images, list):
402                 thumbnails = [{
403                     'url': image['imageUrl'],
404                     'width': int_or_none(image.get('width')),
405                     'height': int_or_none(image.get('height')),
406                 } for image in web_images if image.get('imageUrl')]
407
408         description = data.get('description')
409         category = data.get('mediaAnalytics', {}).get('category')
410
411         common_info = {
412             'description': description,
413             'series': series,
414             'episode': episode,
415             'season_number': season_number,
416             'episode_number': episode_number,
417             'categories': [category] if category else None,
418             'age_limit': parse_age_limit(data.get('legalAge')),
419             'thumbnails': thumbnails,
420         }
421
422         vcodec = 'none' if data.get('mediaType') == 'Audio' else None
423
424         for entry in entries:
425             entry.update(common_info)
426             for f in entry['formats']:
427                 f['vcodec'] = vcodec
428
429         points = data.get('shortIndexPoints')
430         if isinstance(points, list):
431             chapters = []
432             for next_num, point in enumerate(points, start=1):
433                 if not isinstance(point, dict):
434                     continue
435                 start_time = parse_duration(point.get('startPoint'))
436                 if start_time is None:
437                     continue
438                 end_time = parse_duration(
439                     data.get('duration')
440                     if next_num == len(points)
441                     else points[next_num].get('startPoint'))
442                 if end_time is None:
443                     continue
444                 chapters.append({
445                     'start_time': start_time,
446                     'end_time': end_time,
447                     'title': point.get('title'),
448                 })
449             if chapters and len(entries) == 1:
450                 entries[0]['chapters'] = chapters
451
452         return self.playlist_result(entries, video_id, title, description)
453
454     def _real_extract(self, url):
455         video_id = self._match_id(url)
456         return self._extract_from_mediaelement(video_id)
457
458
459 class NRKTVEpisodeIE(InfoExtractor):
460     _VALID_URL = r'https?://tv\.nrk\.no/serie/(?P<id>[^/]+/sesong/\d+/episode/\d+)'
461     _TESTS = [{
462         'url': 'https://tv.nrk.no/serie/hellums-kro/sesong/1/episode/2',
463         'info_dict': {
464             'id': 'MUHH36005220BA',
465             'ext': 'mp4',
466             'title': 'Kro, krig og kjærlighet 2:6',
467             'description': 'md5:b32a7dc0b1ed27c8064f58b97bda4350',
468             'duration': 1563,
469             'series': 'Hellums kro',
470             'season_number': 1,
471             'episode_number': 2,
472             'episode': '2:6',
473             'age_limit': 6,
474         },
475         'params': {
476             'skip_download': True,
477         },
478     }, {
479         'url': 'https://tv.nrk.no/serie/backstage/sesong/1/episode/8',
480         'info_dict': {
481             'id': 'MSUI14000816AA',
482             'ext': 'mp4',
483             'title': 'Backstage 8:30',
484             'description': 'md5:de6ca5d5a2d56849e4021f2bf2850df4',
485             'duration': 1320,
486             'series': 'Backstage',
487             'season_number': 1,
488             'episode_number': 8,
489             'episode': '8:30',
490         },
491         'params': {
492             'skip_download': True,
493         },
494         'skip': 'ProgramRightsHasExpired',
495     }]
496
497     def _real_extract(self, url):
498         display_id = self._match_id(url)
499
500         webpage = self._download_webpage(url, display_id)
501
502         info = self._search_json_ld(webpage, display_id, default={})
503         nrk_id = info.get('@id') or self._html_search_meta(
504             'nrk:program-id', webpage, default=None) or self._search_regex(
505             r'data-program-id=["\'](%s)' % NRKTVIE._EPISODE_RE, webpage,
506             'nrk id')
507         assert re.match(NRKTVIE._EPISODE_RE, nrk_id)
508
509         info.update({
510             '_type': 'url_transparent',
511             'id': nrk_id,
512             'url': 'nrk:%s' % nrk_id,
513             'ie_key': NRKIE.ie_key(),
514         })
515         return info
516
517
518 class NRKTVSerieBaseIE(InfoExtractor):
519     def _extract_series(self, webpage, display_id, fatal=True):
520         config = self._parse_json(
521             self._search_regex(
522                 (r'INITIAL_DATA(?:_V\d)?_*\s*=\s*({.+?})\s*;',
523                  r'({.+?})\s*,\s*"[^"]+"\s*\)\s*</script>'),
524                 webpage, 'config', default='{}' if not fatal else NO_DEFAULT),
525             display_id, fatal=False, transform_source=js_to_json)
526         if not config:
527             return
528         return try_get(
529             config,
530             (lambda x: x['initialState']['series'], lambda x: x['series']),
531             dict)
532
533     def _extract_seasons(self, seasons):
534         if not isinstance(seasons, list):
535             return []
536         entries = []
537         for season in seasons:
538             entries.extend(self._extract_episodes(season))
539         return entries
540
541     def _extract_episodes(self, season):
542         if not isinstance(season, dict):
543             return []
544         return self._extract_entries(season.get('episodes'))
545
546     def _extract_entries(self, entry_list):
547         if not isinstance(entry_list, list):
548             return []
549         entries = []
550         for episode in entry_list:
551             nrk_id = episode.get('prfId')
552             if not nrk_id or not isinstance(nrk_id, compat_str):
553                 continue
554             entries.append(self.url_result(
555                 'nrk:%s' % nrk_id, ie=NRKIE.ie_key(), video_id=nrk_id))
556         return entries
557
558
559 class NRKTVSeasonIE(NRKTVSerieBaseIE):
560     _VALID_URL = r'https?://tv\.nrk\.no/serie/[^/]+/sesong/(?P<id>\d+)'
561     _TEST = {
562         'url': 'https://tv.nrk.no/serie/backstage/sesong/1',
563         'info_dict': {
564             'id': '1',
565             'title': 'Sesong 1',
566         },
567         'playlist_mincount': 30,
568     }
569
570     @classmethod
571     def suitable(cls, url):
572         return (False if NRKTVIE.suitable(url) or NRKTVEpisodeIE.suitable(url)
573                 else super(NRKTVSeasonIE, cls).suitable(url))
574
575     def _real_extract(self, url):
576         display_id = self._match_id(url)
577
578         webpage = self._download_webpage(url, display_id)
579
580         series = self._extract_series(webpage, display_id)
581
582         season = next(
583             s for s in series['seasons']
584             if int(display_id) == s.get('seasonNumber'))
585
586         title = try_get(season, lambda x: x['titles']['title'], compat_str)
587         return self.playlist_result(
588             self._extract_episodes(season), display_id, title)
589
590
591 class NRKTVSeriesIE(NRKTVSerieBaseIE):
592     _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/serie/(?P<id>[^/]+)'
593     _ITEM_RE = r'(?:data-season=["\']|id=["\']season-)(?P<id>\d+)'
594     _TESTS = [{
595         'url': 'https://tv.nrk.no/serie/blank',
596         'info_dict': {
597             'id': 'blank',
598             'title': 'Blank',
599             'description': 'md5:7664b4e7e77dc6810cd3bca367c25b6e',
600         },
601         'playlist_mincount': 30,
602     }, {
603         # new layout, seasons
604         'url': 'https://tv.nrk.no/serie/backstage',
605         'info_dict': {
606             'id': 'backstage',
607             'title': 'Backstage',
608             'description': 'md5:c3ec3a35736fca0f9e1207b5511143d3',
609         },
610         'playlist_mincount': 60,
611     }, {
612         # new layout, instalments
613         'url': 'https://tv.nrk.no/serie/groenn-glede',
614         'info_dict': {
615             'id': 'groenn-glede',
616             'title': 'Grønn glede',
617             'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
618         },
619         'playlist_mincount': 10,
620     }, {
621         # old layout
622         'url': 'https://tv.nrksuper.no/serie/labyrint',
623         'info_dict': {
624             'id': 'labyrint',
625             'title': 'Labyrint',
626             'description': 'md5:318b597330fdac5959247c9b69fdb1ec',
627         },
628         'playlist_mincount': 3,
629     }, {
630         'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
631         'only_matching': True,
632     }, {
633         'url': 'https://tv.nrk.no/serie/saving-the-human-race',
634         'only_matching': True,
635     }, {
636         'url': 'https://tv.nrk.no/serie/postmann-pat',
637         'only_matching': True,
638     }]
639
640     @classmethod
641     def suitable(cls, url):
642         return (
643             False if any(ie.suitable(url)
644                          for ie in (NRKTVIE, NRKTVEpisodeIE, NRKTVSeasonIE))
645             else super(NRKTVSeriesIE, cls).suitable(url))
646
647     def _real_extract(self, url):
648         series_id = self._match_id(url)
649
650         webpage = self._download_webpage(url, series_id)
651
652         # New layout (e.g. https://tv.nrk.no/serie/backstage)
653         series = self._extract_series(webpage, series_id, fatal=False)
654         if series:
655             title = try_get(series, lambda x: x['titles']['title'], compat_str)
656             description = try_get(
657                 series, lambda x: x['titles']['subtitle'], compat_str)
658             entries = []
659             entries.extend(self._extract_seasons(series.get('seasons')))
660             entries.extend(self._extract_entries(series.get('instalments')))
661             entries.extend(self._extract_episodes(series.get('extraMaterial')))
662             return self.playlist_result(entries, series_id, title, description)
663
664         # Old layout (e.g. https://tv.nrksuper.no/serie/labyrint)
665         entries = [
666             self.url_result(
667                 'https://tv.nrk.no/program/Episodes/{series}/{season}'.format(
668                     series=series_id, season=season_id))
669             for season_id in re.findall(self._ITEM_RE, webpage)
670         ]
671
672         title = self._html_search_meta(
673             'seriestitle', webpage,
674             'title', default=None) or self._og_search_title(
675             webpage, fatal=False)
676         if title:
677             title = self._search_regex(
678                 r'NRK (?:Super )?TV\s*[-–]\s*(.+)', title, 'title', default=title)
679
680         description = self._html_search_meta(
681             'series_description', webpage,
682             'description', default=None) or self._og_search_description(webpage)
683
684         return self.playlist_result(entries, series_id, title, description)
685
686
687 class NRKTVDirekteIE(NRKTVIE):
688     IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
689     _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
690
691     _TESTS = [{
692         'url': 'https://tv.nrk.no/direkte/nrk1',
693         'only_matching': True,
694     }, {
695         'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
696         'only_matching': True,
697     }]
698
699
700 class NRKPlaylistBaseIE(InfoExtractor):
701     def _extract_description(self, webpage):
702         pass
703
704     def _real_extract(self, url):
705         playlist_id = self._match_id(url)
706
707         webpage = self._download_webpage(url, playlist_id)
708
709         entries = [
710             self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
711             for video_id in re.findall(self._ITEM_RE, webpage)
712         ]
713
714         playlist_title = self. _extract_title(webpage)
715         playlist_description = self._extract_description(webpage)
716
717         return self.playlist_result(
718             entries, playlist_id, playlist_title, playlist_description)
719
720
721 class NRKPlaylistIE(NRKPlaylistBaseIE):
722     _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
723     _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
724     _TESTS = [{
725         'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
726         'info_dict': {
727             'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
728             'title': 'Gjenopplev den historiske solformørkelsen',
729             'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
730         },
731         'playlist_count': 2,
732     }, {
733         'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
734         'info_dict': {
735             'id': 'rivertonprisen-til-karin-fossum-1.12266449',
736             'title': 'Rivertonprisen til Karin Fossum',
737             'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
738         },
739         'playlist_count': 2,
740     }]
741
742     def _extract_title(self, webpage):
743         return self._og_search_title(webpage, fatal=False)
744
745     def _extract_description(self, webpage):
746         return self._og_search_description(webpage)
747
748
749 class NRKTVEpisodesIE(NRKPlaylistBaseIE):
750     _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
751     _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
752     _TESTS = [{
753         'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
754         'info_dict': {
755             'id': '69031',
756             'title': 'Nytt på nytt, sesong: 201210',
757         },
758         'playlist_count': 4,
759     }]
760
761     def _extract_title(self, webpage):
762         return self._html_search_regex(
763             r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
764
765
766 class NRKSkoleIE(InfoExtractor):
767     IE_DESC = 'NRK Skole'
768     _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
769
770     _TESTS = [{
771         'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
772         'md5': '18c12c3d071953c3bf8d54ef6b2587b7',
773         'info_dict': {
774             'id': '6021',
775             'ext': 'mp4',
776             'title': 'Genetikk og eneggede tvillinger',
777             'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
778             'duration': 399,
779         },
780     }, {
781         'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
782         'only_matching': True,
783     }]
784
785     def _real_extract(self, url):
786         video_id = self._match_id(url)
787
788         webpage = self._download_webpage(
789             'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
790             video_id)
791
792         nrk_id = self._parse_json(
793             self._search_regex(
794                 r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
795                 webpage, 'application json'),
796             video_id)['activeMedia']['psId']
797
798         return self.url_result('nrk:%s' % nrk_id)