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