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