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