[nrktv] Add support for new episode URL schema (closes #16909)
[youtube-dl] / youtube_dl / extractor / nrk.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import compat_urllib_parse_unquote
8 from ..utils import (
9     ExtractorError,
10     int_or_none,
11     JSON_LD_RE,
12     parse_age_limit,
13     parse_duration,
14 )
15
16
17 class NRKBaseIE(InfoExtractor):
18     _GEO_COUNTRIES = ['NO']
19
20     _api_host = None
21
22     def _real_extract(self, url):
23         video_id = self._match_id(url)
24
25         api_hosts = (self._api_host, ) if self._api_host else self._API_HOSTS
26
27         for api_host in api_hosts:
28             data = self._download_json(
29                 'http://%s/mediaelement/%s' % (api_host, video_id),
30                 video_id, 'Downloading mediaelement JSON',
31                 fatal=api_host == api_hosts[-1])
32             if not data:
33                 continue
34             self._api_host = api_host
35             break
36
37         title = data.get('fullTitle') or data.get('mainTitle') or data['title']
38         video_id = data.get('id') or video_id
39
40         entries = []
41
42         conviva = data.get('convivaStatistics') or {}
43         live = (data.get('mediaElementType') == 'Live' or
44                 data.get('isLive') is True or conviva.get('isLive'))
45
46         def make_title(t):
47             return self._live_title(t) if live else t
48
49         media_assets = data.get('mediaAssets')
50         if media_assets and isinstance(media_assets, list):
51             def video_id_and_title(idx):
52                 return ((video_id, title) if len(media_assets) == 1
53                         else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
54             for num, asset in enumerate(media_assets, 1):
55                 asset_url = asset.get('url')
56                 if not asset_url:
57                     continue
58                 formats = self._extract_akamai_formats(asset_url, video_id)
59                 if not formats:
60                     continue
61                 self._sort_formats(formats)
62
63                 # Some f4m streams may not work with hdcore in fragments' URLs
64                 for f in formats:
65                     extra_param = f.get('extra_param_to_segment_url')
66                     if extra_param and 'hdcore' in extra_param:
67                         del f['extra_param_to_segment_url']
68
69                 entry_id, entry_title = video_id_and_title(num)
70                 duration = parse_duration(asset.get('duration'))
71                 subtitles = {}
72                 for subtitle in ('webVtt', 'timedText'):
73                     subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
74                     if subtitle_url:
75                         subtitles.setdefault('no', []).append({
76                             'url': compat_urllib_parse_unquote(subtitle_url)
77                         })
78                 entries.append({
79                     'id': asset.get('carrierId') or entry_id,
80                     'title': make_title(entry_title),
81                     'duration': duration,
82                     'subtitles': subtitles,
83                     'formats': formats,
84                 })
85
86         if not entries:
87             media_url = data.get('mediaUrl')
88             if media_url:
89                 formats = self._extract_akamai_formats(media_url, video_id)
90                 self._sort_formats(formats)
91                 duration = parse_duration(data.get('duration'))
92                 entries = [{
93                     'id': video_id,
94                     'title': make_title(title),
95                     'duration': duration,
96                     'formats': formats,
97                 }]
98
99         if not entries:
100             MESSAGES = {
101                 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
102                 'ProgramRightsHasExpired': 'Programmet har gått ut',
103                 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
104             }
105             message_type = data.get('messageType', '')
106             # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
107             if 'IsGeoBlocked' in message_type:
108                 self.raise_geo_restricted(
109                     msg=MESSAGES.get('ProgramIsGeoBlocked'),
110                     countries=self._GEO_COUNTRIES)
111             raise ExtractorError(
112                 '%s said: %s' % (self.IE_NAME, MESSAGES.get(
113                     message_type, message_type)),
114                 expected=True)
115
116         series = conviva.get('seriesName') or data.get('seriesTitle')
117         episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
118
119         season_number = None
120         episode_number = None
121         if data.get('mediaElementType') == 'Episode':
122             _season_episode = data.get('scoresStatistics', {}).get('springStreamStream') or \
123                 data.get('relativeOriginUrl', '')
124             EPISODENUM_RE = [
125                 r'/s(?P<season>\d{,2})e(?P<episode>\d{,2})\.',
126                 r'/sesong-(?P<season>\d{,2})/episode-(?P<episode>\d{,2})',
127             ]
128             season_number = int_or_none(self._search_regex(
129                 EPISODENUM_RE, _season_episode, 'season number',
130                 default=None, group='season'))
131             episode_number = int_or_none(self._search_regex(
132                 EPISODENUM_RE, _season_episode, 'episode number',
133                 default=None, group='episode'))
134
135         thumbnails = None
136         images = data.get('images')
137         if images and isinstance(images, dict):
138             web_images = images.get('webImages')
139             if isinstance(web_images, list):
140                 thumbnails = [{
141                     'url': image['imageUrl'],
142                     'width': int_or_none(image.get('width')),
143                     'height': int_or_none(image.get('height')),
144                 } for image in web_images if image.get('imageUrl')]
145
146         description = data.get('description')
147         category = data.get('mediaAnalytics', {}).get('category')
148
149         common_info = {
150             'description': description,
151             'series': series,
152             'episode': episode,
153             'season_number': season_number,
154             'episode_number': episode_number,
155             'categories': [category] if category else None,
156             'age_limit': parse_age_limit(data.get('legalAge')),
157             'thumbnails': thumbnails,
158         }
159
160         vcodec = 'none' if data.get('mediaType') == 'Audio' else None
161
162         for entry in entries:
163             entry.update(common_info)
164             for f in entry['formats']:
165                 f['vcodec'] = vcodec
166
167         points = data.get('shortIndexPoints')
168         if isinstance(points, list):
169             chapters = []
170             for next_num, point in enumerate(points, start=1):
171                 if not isinstance(point, dict):
172                     continue
173                 start_time = parse_duration(point.get('startPoint'))
174                 if start_time is None:
175                     continue
176                 end_time = parse_duration(
177                     data.get('duration')
178                     if next_num == len(points)
179                     else points[next_num].get('startPoint'))
180                 if end_time is None:
181                     continue
182                 chapters.append({
183                     'start_time': start_time,
184                     'end_time': end_time,
185                     'title': point.get('title'),
186                 })
187             if chapters and len(entries) == 1:
188                 entries[0]['chapters'] = chapters
189
190         return self.playlist_result(entries, video_id, title, description)
191
192
193 class NRKIE(NRKBaseIE):
194     _VALID_URL = r'''(?x)
195                         (?:
196                             nrk:|
197                             https?://
198                                 (?:
199                                     (?:www\.)?nrk\.no/video/PS\*|
200                                     v8[-.]psapi\.nrk\.no/mediaelement/
201                                 )
202                             )
203                             (?P<id>[^?#&]+)
204                         '''
205     _API_HOSTS = ('psapi.nrk.no', 'v8-psapi.nrk.no')
206     _TESTS = [{
207         # video
208         'url': 'http://www.nrk.no/video/PS*150533',
209         'md5': '2f7f6eeb2aacdd99885f355428715cfa',
210         'info_dict': {
211             'id': '150533',
212             'ext': 'mp4',
213             'title': 'Dompap og andre fugler i Piip-Show',
214             'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
215             'duration': 263,
216         }
217     }, {
218         # audio
219         'url': 'http://www.nrk.no/video/PS*154915',
220         # MD5 is unstable
221         'info_dict': {
222             'id': '154915',
223             'ext': 'flv',
224             'title': 'Slik høres internett ut når du er blind',
225             'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
226             'duration': 20,
227         }
228     }, {
229         'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
230         'only_matching': True,
231     }, {
232         'url': 'nrk:clip/7707d5a3-ebe7-434a-87d5-a3ebe7a34a70',
233         'only_matching': True,
234     }, {
235         'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
236         'only_matching': True,
237     }]
238
239
240 class NRKTVIE(NRKBaseIE):
241     IE_DESC = 'NRK TV and NRK Radio'
242     _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
243     _VALID_URL = r'''(?x)
244                         https?://
245                             (?:tv|radio)\.nrk(?:super)?\.no/
246                             (?:serie/[^/]+|program)/
247                             (?![Ee]pisodes)%s
248                             (?:/\d{2}-\d{2}-\d{4})?
249                             (?:\#del=(?P<part_id>\d+))?
250                     ''' % _EPISODE_RE
251     _API_HOSTS = ('psapi-ne.nrk.no', 'psapi-we.nrk.no')
252     _TESTS = [{
253         'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
254         'md5': '4e9ca6629f09e588ed240fb11619922a',
255         'info_dict': {
256             'id': 'MUHH48000314AA',
257             'ext': 'mp4',
258             'title': '20 spørsmål 23.05.2014',
259             'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
260             'duration': 1741,
261             'series': '20 spørsmål - TV',
262             'episode': '23.05.2014',
263         },
264     }, {
265         'url': 'https://tv.nrk.no/program/mdfp15000514',
266         'info_dict': {
267             'id': 'MDFP15000514CA',
268             'ext': 'mp4',
269             'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
270             'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
271             'duration': 4605,
272             'series': 'Kunnskapskanalen',
273             'episode': '24.05.2014',
274         },
275         'params': {
276             'skip_download': True,
277         },
278     }, {
279         # single playlist video
280         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
281         'info_dict': {
282             'id': 'MSPO40010515-part2',
283             'ext': 'flv',
284             'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
285             'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
286         },
287         'params': {
288             'skip_download': True,
289         },
290         'expected_warnings': ['Video is geo restricted'],
291         'skip': 'particular part is not supported currently',
292     }, {
293         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
294         'playlist': [{
295             'info_dict': {
296                 'id': 'MSPO40010515AH',
297                 'ext': 'mp4',
298                 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 1)',
299                 'description': 'md5:c03aba1e917561eface5214020551b7a',
300                 'duration': 772,
301                 'series': 'Tour de Ski',
302                 'episode': '06.01.2015',
303             },
304             'params': {
305                 'skip_download': True,
306             },
307         }, {
308             'info_dict': {
309                 'id': 'MSPO40010515BH',
310                 'ext': 'mp4',
311                 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 2)',
312                 'description': 'md5:c03aba1e917561eface5214020551b7a',
313                 'duration': 6175,
314                 'series': 'Tour de Ski',
315                 'episode': '06.01.2015',
316             },
317             'params': {
318                 'skip_download': True,
319             },
320         }],
321         'info_dict': {
322             'id': 'MSPO40010515',
323             'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
324             'description': 'md5:c03aba1e917561eface5214020551b7a',
325         },
326         'expected_warnings': ['Video is geo restricted'],
327     }, {
328         'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
329         'info_dict': {
330             'id': 'KMTE50001317AA',
331             'ext': 'mp4',
332             'title': 'Anno 13:30',
333             'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
334             'duration': 2340,
335             'series': 'Anno',
336             'episode': '13:30',
337             'season_number': 3,
338             'episode_number': 13,
339         },
340         'params': {
341             'skip_download': True,
342         },
343     }, {
344         'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
345         'info_dict': {
346             'id': 'MUHH46000317AA',
347             'ext': 'mp4',
348             'title': 'Nytt på Nytt 27.01.2017',
349             'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
350             'duration': 1796,
351             'series': 'Nytt på nytt',
352             'episode': '27.01.2017',
353         },
354         'params': {
355             'skip_download': True,
356         },
357     }, {
358         'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
359         'only_matching': True,
360     }]
361
362
363 class NRKTVEpisodeIE(InfoExtractor):
364     _VALID_URL = r'https?://tv\.nrk\.no/serie/(?P<id>[^/]+/sesong/\d+/episode/\d+)'
365     _TEST = {
366         'url': 'https://tv.nrk.no/serie/backstage/sesong/1/episode/8',
367         'info_dict': {
368             'id': 'MSUI14000816AA',
369             'ext': 'mp4',
370             'title': 'Backstage 8:30',
371             'description': 'md5:de6ca5d5a2d56849e4021f2bf2850df4',
372             'duration': 1320,
373             'series': 'Backstage',
374             'season_number': 1,
375             'episode_number': 8,
376             'episode': '8:30',
377         },
378         'params': {
379             'skip_download': True,
380         },
381     }
382
383     def _real_extract(self, url):
384         display_id = self._match_id(url)
385
386         webpage = self._download_webpage(url, display_id)
387
388         nrk_id = self._parse_json(
389             self._search_regex(JSON_LD_RE, webpage, 'JSON-LD', group='json_ld'),
390             display_id)['@id']
391
392         assert re.match(NRKTVIE._EPISODE_RE, nrk_id)
393         return self.url_result(
394             'nrk:%s' % nrk_id, ie=NRKIE.ie_key(), video_id=nrk_id)
395
396
397 class NRKTVDirekteIE(NRKTVIE):
398     IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
399     _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
400
401     _TESTS = [{
402         'url': 'https://tv.nrk.no/direkte/nrk1',
403         'only_matching': True,
404     }, {
405         'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
406         'only_matching': True,
407     }]
408
409
410 class NRKPlaylistBaseIE(InfoExtractor):
411     def _extract_description(self, webpage):
412         pass
413
414     def _real_extract(self, url):
415         playlist_id = self._match_id(url)
416
417         webpage = self._download_webpage(url, playlist_id)
418
419         entries = [
420             self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
421             for video_id in re.findall(self._ITEM_RE, webpage)
422         ]
423
424         playlist_title = self. _extract_title(webpage)
425         playlist_description = self._extract_description(webpage)
426
427         return self.playlist_result(
428             entries, playlist_id, playlist_title, playlist_description)
429
430
431 class NRKPlaylistIE(NRKPlaylistBaseIE):
432     _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
433     _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
434     _TESTS = [{
435         'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
436         'info_dict': {
437             'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
438             'title': 'Gjenopplev den historiske solformørkelsen',
439             'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
440         },
441         'playlist_count': 2,
442     }, {
443         'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
444         'info_dict': {
445             'id': 'rivertonprisen-til-karin-fossum-1.12266449',
446             'title': 'Rivertonprisen til Karin Fossum',
447             'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
448         },
449         'playlist_count': 5,
450     }]
451
452     def _extract_title(self, webpage):
453         return self._og_search_title(webpage, fatal=False)
454
455     def _extract_description(self, webpage):
456         return self._og_search_description(webpage)
457
458
459 class NRKTVEpisodesIE(NRKPlaylistBaseIE):
460     _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
461     _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
462     _TESTS = [{
463         'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
464         'info_dict': {
465             'id': '69031',
466             'title': 'Nytt på nytt, sesong: 201210',
467         },
468         'playlist_count': 4,
469     }]
470
471     def _extract_title(self, webpage):
472         return self._html_search_regex(
473             r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
474
475
476 class NRKTVSeriesIE(InfoExtractor):
477     _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/serie/(?P<id>[^/]+)'
478     _ITEM_RE = r'(?:data-season=["\']|id=["\']season-)(?P<id>\d+)'
479     _TESTS = [{
480         'url': 'https://tv.nrk.no/serie/groenn-glede',
481         'info_dict': {
482             'id': 'groenn-glede',
483             'title': 'Grønn glede',
484             'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
485         },
486         'playlist_mincount': 9,
487     }, {
488         'url': 'http://tv.nrksuper.no/serie/labyrint',
489         'info_dict': {
490             'id': 'labyrint',
491             'title': 'Labyrint',
492             'description': 'md5:58afd450974c89e27d5a19212eee7115',
493         },
494         'playlist_mincount': 3,
495     }, {
496         'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
497         'only_matching': True,
498     }, {
499         'url': 'https://tv.nrk.no/serie/saving-the-human-race',
500         'only_matching': True,
501     }, {
502         'url': 'https://tv.nrk.no/serie/postmann-pat',
503         'only_matching': True,
504     }]
505
506     @classmethod
507     def suitable(cls, url):
508         return (False if NRKTVIE.suitable(url) or NRKTVEpisodeIE.suitable(url)
509                 else super(NRKTVSeriesIE, cls).suitable(url))
510
511     def _real_extract(self, url):
512         series_id = self._match_id(url)
513
514         webpage = self._download_webpage(url, series_id)
515
516         entries = [
517             self.url_result(
518                 'https://tv.nrk.no/program/Episodes/{series}/{season}'.format(
519                     series=series_id, season=season_id))
520             for season_id in re.findall(self._ITEM_RE, webpage)
521         ]
522
523         title = self._html_search_meta(
524             'seriestitle', webpage,
525             'title', default=None) or self._og_search_title(
526             webpage, fatal=False)
527
528         description = self._html_search_meta(
529             'series_description', webpage,
530             'description', default=None) or self._og_search_description(webpage)
531
532         return self.playlist_result(entries, series_id, title, description)
533
534
535 class NRKSkoleIE(InfoExtractor):
536     IE_DESC = 'NRK Skole'
537     _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
538
539     _TESTS = [{
540         'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
541         'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
542         'info_dict': {
543             'id': '6021',
544             'ext': 'mp4',
545             'title': 'Genetikk og eneggede tvillinger',
546             'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
547             'duration': 399,
548         },
549     }, {
550         'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
551         'only_matching': True,
552     }]
553
554     def _real_extract(self, url):
555         video_id = self._match_id(url)
556
557         webpage = self._download_webpage(
558             'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
559             video_id)
560
561         nrk_id = self._parse_json(
562             self._search_regex(
563                 r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
564                 webpage, 'application json'),
565             video_id)['activeMedia']['psId']
566
567         return self.url_result('nrk:%s' % nrk_id)