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