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