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