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