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