]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/nrk.py
[NRKTV] Added NRKTVSeriesIE
[yt-dlp.git] / youtube_dl / extractor / nrk.py
CommitLineData
dcdb292f 1# coding: utf-8
d2176c80
S
2from __future__ import unicode_literals
3
754e6c83 4import random
d2176c80
S
5import re
6
7from .common import InfoExtractor
d8d540cf 8from ..compat import compat_urllib_parse_unquote
dfb2e1a3
S
9from ..utils import (
10 ExtractorError,
d8d540cf
S
11 int_or_none,
12 parse_age_limit,
76bfaf6d 13 parse_duration,
dfb2e1a3 14)
d2176c80
S
15
16
d8d540cf 17class NRKBaseIE(InfoExtractor):
754e6c83
S
18 _faked_ip = None
19
7e08e2ca 20 def _download_webpage_handle(self, *args, **kwargs):
754e6c83
S
21 # NRK checks X-Forwarded-For HTTP header in order to figure out the
22 # origin of the client behind proxy. This allows to bypass geo
23 # restriction by faking this header's value to some Norway IP.
24 # We will do so once we encounter any geo restriction error.
25 if self._faked_ip:
7e08e2ca
S
26 # NB: str is intentional
27 kwargs.setdefault(str('headers'), {})['X-Forwarded-For'] = self._faked_ip
28 return super(NRKBaseIE, self)._download_webpage_handle(*args, **kwargs)
754e6c83
S
29
30 def _fake_ip(self):
31 # Use fake IP from 37.191.128.0/17 in order to workaround geo
32 # restriction
33 def octet(lb=0, ub=255):
34 return random.randint(lb, ub)
35 self._faked_ip = '37.191.%d.%d' % (octet(128), octet())
36
d2176c80 37 def _real_extract(self, url):
4e6a2286 38 video_id = self._match_id(url)
d2176c80
S
39
40 data = self._download_json(
d8d540cf
S
41 'http://%s/mediaelement/%s' % (self._API_HOST, video_id),
42 video_id, 'Downloading mediaelement JSON')
43
44 title = data.get('fullTitle') or data.get('mainTitle') or data['title']
45 video_id = data.get('id') or video_id
46
7e08e2ca
S
47 http_headers = {'X-Forwarded-For': self._faked_ip} if self._faked_ip else {}
48
d8d540cf
S
49 entries = []
50
c80db5d3
S
51 conviva = data.get('convivaStatistics') or {}
52 live = (data.get('mediaElementType') == 'Live' or
53 data.get('isLive') is True or conviva.get('isLive'))
54
55 def make_title(t):
56 return self._live_title(t) if live else t
57
d8d540cf
S
58 media_assets = data.get('mediaAssets')
59 if media_assets and isinstance(media_assets, list):
60 def video_id_and_title(idx):
61 return ((video_id, title) if len(media_assets) == 1
62 else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
63 for num, asset in enumerate(media_assets, 1):
64 asset_url = asset.get('url')
65 if not asset_url:
66 continue
ad316425 67 formats = self._extract_akamai_formats(asset_url, video_id)
d8d540cf
S
68 if not formats:
69 continue
70 self._sort_formats(formats)
c80db5d3
S
71
72 # Some f4m streams may not work with hdcore in fragments' URLs
73 for f in formats:
74 extra_param = f.get('extra_param_to_segment_url')
75 if extra_param and 'hdcore' in extra_param:
76 del f['extra_param_to_segment_url']
77
d8d540cf
S
78 entry_id, entry_title = video_id_and_title(num)
79 duration = parse_duration(asset.get('duration'))
80 subtitles = {}
81 for subtitle in ('webVtt', 'timedText'):
82 subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
83 if subtitle_url:
c8602b2f
S
84 subtitles.setdefault('no', []).append({
85 'url': compat_urllib_parse_unquote(subtitle_url)
86 })
d8d540cf
S
87 entries.append({
88 'id': asset.get('carrierId') or entry_id,
c80db5d3 89 'title': make_title(entry_title),
d8d540cf
S
90 'duration': duration,
91 'subtitles': subtitles,
92 'formats': formats,
7e08e2ca 93 'http_headers': http_headers,
d8d540cf 94 })
d2176c80 95
d8d540cf
S
96 if not entries:
97 media_url = data.get('mediaUrl')
98 if media_url:
ad316425 99 formats = self._extract_akamai_formats(media_url, video_id)
d8d540cf
S
100 self._sort_formats(formats)
101 duration = parse_duration(data.get('duration'))
102 entries = [{
103 'id': video_id,
c80db5d3 104 'title': make_title(title),
d8d540cf
S
105 'duration': duration,
106 'formats': formats,
107 }]
d2176c80 108
d8d540cf 109 if not entries:
50913b82
S
110 message_type = data.get('messageType', '')
111 # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
112 if 'IsGeoBlocked' in message_type and not self._faked_ip:
754e6c83
S
113 self.report_warning(
114 'Video is geo restricted, trying to fake IP')
115 self._fake_ip()
116 return self._real_extract(url)
117
118 MESSAGES = {
119 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
120 'ProgramRightsHasExpired': 'Programmet har gått ut',
121 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
122 }
123 raise ExtractorError(
124 '%s said: %s' % (self.IE_NAME, MESSAGES.get(
125 message_type, message_type)),
126 expected=True)
874ae035 127
d8d540cf
S
128 series = conviva.get('seriesName') or data.get('seriesTitle')
129 episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
393d9fc6 130
8fd65fae
OS
131 season_number = None
132 episode_number = None
133 if data.get('mediaElementType') == 'Episode':
134 _season_episode = data.get('scoresStatistics', {}).get('springStreamStream') or \
135 data.get('relativeOriginUrl', '')
136 EPISODENUM_RE = [
137 r'/s(?P<season>\d+)e(?P<episode>\d+)\.',
138 r'/sesong-(?P<season>\d+)/episode-(?P<episode>\d+)',
139 ]
140 season_number = int_or_none(self._search_regex(EPISODENUM_RE, _season_episode, "S##E##", fatal=False, group='season'))
141 episode_number = int_or_none(self._search_regex(EPISODENUM_RE, _season_episode, "S##E##", fatal=False, group='episode'))
142
d8d540cf 143 thumbnails = None
d2176c80 144 images = data.get('images')
d8d540cf
S
145 if images and isinstance(images, dict):
146 web_images = images.get('webImages')
147 if isinstance(web_images, list):
148 thumbnails = [{
149 'url': image['imageUrl'],
150 'width': int_or_none(image.get('width')),
151 'height': int_or_none(image.get('height')),
152 } for image in web_images if image.get('imageUrl')]
153
154 description = data.get('description')
8fd65fae 155 category = data.get('mediaAnalytics', {}).get('category')
d8d540cf
S
156
157 common_info = {
158 'description': description,
159 'series': series,
160 'episode': episode,
8fd65fae
OS
161 'season_number': season_number,
162 'episode_number': episode_number,
163 'categories': [category] if category else None,
d8d540cf
S
164 'age_limit': parse_age_limit(data.get('legalAge')),
165 'thumbnails': thumbnails,
dfb2e1a3
S
166 }
167
d8d540cf
S
168 vcodec = 'none' if data.get('mediaType') == 'Audio' else None
169
170 # TODO: extract chapters when https://github.com/rg3/youtube-dl/pull/9409 is merged
171
172 for entry in entries:
173 entry.update(common_info)
174 for f in entry['formats']:
175 f['vcodec'] = vcodec
176
177 return self.playlist_result(entries, video_id, title, description)
178
179
180class NRKIE(NRKBaseIE):
853a71b6
S
181 _VALID_URL = r'''(?x)
182 (?:
183 nrk:|
184 https?://
185 (?:
186 (?:www\.)?nrk\.no/video/PS\*|
187 v8-psapi\.nrk\.no/mediaelement/
188 )
189 )
190 (?P<id>[^/?#&]+)
191 '''
d8d540cf
S
192 _API_HOST = 'v8.psapi.nrk.no'
193 _TESTS = [{
194 # video
195 'url': 'http://www.nrk.no/video/PS*150533',
18cf6381 196 'md5': '2f7f6eeb2aacdd99885f355428715cfa',
d8d540cf
S
197 'info_dict': {
198 'id': '150533',
18cf6381 199 'ext': 'mp4',
d8d540cf
S
200 'title': 'Dompap og andre fugler i Piip-Show',
201 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
202 'duration': 263,
203 }
204 }, {
205 # audio
206 'url': 'http://www.nrk.no/video/PS*154915',
207 # MD5 is unstable
208 'info_dict': {
209 'id': '154915',
210 'ext': 'flv',
211 'title': 'Slik høres internett ut når du er blind',
212 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
213 'duration': 20,
214 }
e2628fb6
S
215 }, {
216 'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
217 'only_matching': True,
853a71b6
S
218 }, {
219 'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
220 'only_matching': True,
d8d540cf
S
221 }]
222
223
224class NRKTVIE(NRKBaseIE):
225 IE_DESC = 'NRK TV and NRK Radio'
966815e1
S
226 _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
227 _VALID_URL = r'''(?x)
228 https?://
229 (?:tv|radio)\.nrk(?:super)?\.no/
230 (?:serie/[^/]+|program)/
231 (?![Ee]pisodes)%s
232 (?:/\d{2}-\d{2}-\d{4})?
233 (?:\#del=(?P<part_id>\d+))?
234 ''' % _EPISODE_RE
d8d540cf
S
235 _API_HOST = 'psapi-we.nrk.no'
236
237 _TESTS = [{
238 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
18cf6381 239 'md5': '4e9ca6629f09e588ed240fb11619922a',
d8d540cf 240 'info_dict': {
18cf6381 241 'id': 'MUHH48000314AA',
d8d540cf 242 'ext': 'mp4',
18cf6381 243 'title': '20 spørsmål 23.05.2014',
d8d540cf 244 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
4e790117 245 'duration': 1741,
d8d540cf 246 },
d8d540cf
S
247 }, {
248 'url': 'https://tv.nrk.no/program/mdfp15000514',
18cf6381 249 'md5': '43d0be26663d380603a9cf0c24366531',
d8d540cf 250 'info_dict': {
18cf6381 251 'id': 'MDFP15000514CA',
d8d540cf 252 'ext': 'mp4',
18cf6381 253 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
254 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
4e790117 255 'duration': 4605,
d8d540cf 256 },
d8d540cf
S
257 }, {
258 # single playlist video
259 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
260 'md5': 'adbd1dbd813edaf532b0a253780719c2',
261 'info_dict': {
262 'id': 'MSPO40010515-part2',
263 'ext': 'flv',
264 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
265 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
d8d540cf
S
266 },
267 'skip': 'Only works from Norway',
268 }, {
269 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
270 'playlist': [{
271 'md5': '9480285eff92d64f06e02a5367970a7a',
272 'info_dict': {
273 'id': 'MSPO40010515-part1',
274 'ext': 'flv',
275 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 1:2)',
276 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
d8d540cf
S
277 },
278 }, {
279 'md5': 'adbd1dbd813edaf532b0a253780719c2',
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',
d8d540cf
S
285 },
286 }],
287 'info_dict': {
288 'id': 'MSPO40010515',
289 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn',
290 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
d8d540cf
S
291 'duration': 6947.52,
292 },
293 'skip': 'Only works from Norway',
294 }, {
295 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
296 'only_matching': True,
297 }]
298
dfb2e1a3 299
c80db5d3
S
300class NRKTVDirekteIE(NRKTVIE):
301 IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
302 _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
303
304 _TESTS = [{
305 'url': 'https://tv.nrk.no/direkte/nrk1',
306 'only_matching': True,
307 }, {
308 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
309 'only_matching': True,
310 }]
311
312
966815e1
S
313class NRKPlaylistBaseIE(InfoExtractor):
314 def _extract_description(self, webpage):
315 pass
316
317 def _real_extract(self, url):
318 playlist_id = self._match_id(url)
319
320 webpage = self._download_webpage(url, playlist_id)
321
322 entries = [
323 self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
324 for video_id in re.findall(self._ITEM_RE, webpage)
325 ]
326
327 playlist_title = self. _extract_title(webpage)
328 playlist_description = self._extract_description(webpage)
329
330 return self.playlist_result(
331 entries, playlist_id, playlist_title, playlist_description)
faa1b5c2 332
966815e1
S
333
334class NRKPlaylistIE(NRKPlaylistBaseIE):
335 _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
336 _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
a0914154 337 _TESTS = [{
faa1b5c2
S
338 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
339 'info_dict': {
340 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
341 'title': 'Gjenopplev den historiske solformørkelsen',
342 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
343 },
a0914154
S
344 'playlist_count': 2,
345 }, {
346 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
347 'info_dict': {
348 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
349 'title': 'Rivertonprisen til Karin Fossum',
350 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
351 },
352 'playlist_count': 5,
353 }]
faa1b5c2 354
966815e1
S
355 def _extract_title(self, webpage):
356 return self._og_search_title(webpage, fatal=False)
faa1b5c2 357
966815e1
S
358 def _extract_description(self, webpage):
359 return self._og_search_description(webpage)
faa1b5c2 360
faa1b5c2 361
966815e1
S
362class NRKTVEpisodesIE(NRKPlaylistBaseIE):
363 _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
364 _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
365 _TESTS = [{
366 'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
367 'info_dict': {
368 'id': '69031',
369 'title': 'Nytt på nytt, sesong: 201210',
370 },
371 'playlist_count': 4,
372 }]
faa1b5c2 373
966815e1
S
374 def _extract_title(self, webpage):
375 return self._html_search_regex(
376 r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
faa1b5c2
S
377
378
8fd65fae
OS
379class NRKTVSeriesIE(InfoExtractor):
380 _VALID_URL = r'https?://tv\.nrk\.no/serie/(?P<id>[^/]+)/?'
381 _ITEM_RE = r'data-season=["\'](?P<id>\d+)["\']'
382 _TESTS = [{
383 'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
384 'playlist_count': 1,
385 }, {
386 'url': 'https://tv.nrk.no/serie/saving-the-human-race',
387 'playlist_count': 1,
388 }, {
389 'url': 'https://tv.nrk.no/serie/postmann-pat',
390 'playlist_count': 3,
391 }, {
392 'url': 'https://tv.nrk.no/serie/groenn-glede',
393 'playlist_count': 9,
394 }]
395
396 def _real_extract(self, url):
397 series_id = self._match_id(url)
398
399 webpage = self._download_webpage(url, series_id)
400
401 entries = [
402 self.url_result('https://tv.nrk.no/program/Episodes/{series}/{season}'.format(
403 series=series_id,
404 season=season_id
405 ))
406 for season_id in re.findall(self._ITEM_RE, webpage)
407 ]
408
409 return self.playlist_result(entries)
410
411
3099b312
S
412class NRKSkoleIE(InfoExtractor):
413 IE_DESC = 'NRK Skole'
971e3b75 414 _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
3099b312
S
415
416 _TESTS = [{
971e3b75
S
417 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
418 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
3099b312
S
419 'info_dict': {
420 'id': '6021',
971e3b75 421 'ext': 'mp4',
3099b312
S
422 'title': 'Genetikk og eneggede tvillinger',
423 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
424 'duration': 399,
425 },
426 }, {
971e3b75 427 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
61140904 428 'only_matching': True,
3099b312
S
429 }]
430
431 def _real_extract(self, url):
971e3b75
S
432 video_id = self._match_id(url)
433
434 webpage = self._download_webpage(
435 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
436 video_id)
3099b312 437
971e3b75
S
438 nrk_id = self._parse_json(
439 self._search_regex(
440 r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
441 webpage, 'application json'),
442 video_id)['activeMedia']['psId']
3099b312 443
3099b312 444 return self.url_result('nrk:%s' % nrk_id)