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