]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/nrk.py
[pbs] fix extraction for geo restricted videos(#7095)
[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
51 media_assets = data.get('mediaAssets')
52 if media_assets and isinstance(media_assets, list):
53 def video_id_and_title(idx):
54 return ((video_id, title) if len(media_assets) == 1
55 else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
56 for num, asset in enumerate(media_assets, 1):
57 asset_url = asset.get('url')
58 if not asset_url:
59 continue
ad316425 60 formats = self._extract_akamai_formats(asset_url, video_id)
d8d540cf
S
61 if not formats:
62 continue
63 self._sort_formats(formats)
64 entry_id, entry_title = video_id_and_title(num)
65 duration = parse_duration(asset.get('duration'))
66 subtitles = {}
67 for subtitle in ('webVtt', 'timedText'):
68 subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
69 if subtitle_url:
c8602b2f
S
70 subtitles.setdefault('no', []).append({
71 'url': compat_urllib_parse_unquote(subtitle_url)
72 })
d8d540cf
S
73 entries.append({
74 'id': asset.get('carrierId') or entry_id,
75 'title': entry_title,
76 'duration': duration,
77 'subtitles': subtitles,
78 'formats': formats,
7e08e2ca 79 'http_headers': http_headers,
d8d540cf 80 })
d2176c80 81
d8d540cf
S
82 if not entries:
83 media_url = data.get('mediaUrl')
84 if media_url:
ad316425 85 formats = self._extract_akamai_formats(media_url, video_id)
d8d540cf
S
86 self._sort_formats(formats)
87 duration = parse_duration(data.get('duration'))
88 entries = [{
89 'id': video_id,
90 'title': title,
91 'duration': duration,
92 'formats': formats,
93 }]
d2176c80 94
d8d540cf 95 if not entries:
50913b82
S
96 message_type = data.get('messageType', '')
97 # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
98 if 'IsGeoBlocked' in message_type and not self._faked_ip:
754e6c83
S
99 self.report_warning(
100 'Video is geo restricted, trying to fake IP')
101 self._fake_ip()
102 return self._real_extract(url)
103
104 MESSAGES = {
105 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
106 'ProgramRightsHasExpired': 'Programmet har gått ut',
107 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
108 }
109 raise ExtractorError(
110 '%s said: %s' % (self.IE_NAME, MESSAGES.get(
111 message_type, message_type)),
112 expected=True)
874ae035 113
d8d540cf
S
114 conviva = data.get('convivaStatistics') or {}
115 series = conviva.get('seriesName') or data.get('seriesTitle')
116 episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
393d9fc6 117
d8d540cf 118 thumbnails = None
d2176c80 119 images = data.get('images')
d8d540cf
S
120 if images and isinstance(images, dict):
121 web_images = images.get('webImages')
122 if isinstance(web_images, list):
123 thumbnails = [{
124 'url': image['imageUrl'],
125 'width': int_or_none(image.get('width')),
126 'height': int_or_none(image.get('height')),
127 } for image in web_images if image.get('imageUrl')]
128
129 description = data.get('description')
130
131 common_info = {
132 'description': description,
133 'series': series,
134 'episode': episode,
135 'age_limit': parse_age_limit(data.get('legalAge')),
136 'thumbnails': thumbnails,
dfb2e1a3
S
137 }
138
d8d540cf
S
139 vcodec = 'none' if data.get('mediaType') == 'Audio' else None
140
141 # TODO: extract chapters when https://github.com/rg3/youtube-dl/pull/9409 is merged
142
143 for entry in entries:
144 entry.update(common_info)
145 for f in entry['formats']:
146 f['vcodec'] = vcodec
147
148 return self.playlist_result(entries, video_id, title, description)
149
150
151class NRKIE(NRKBaseIE):
853a71b6
S
152 _VALID_URL = r'''(?x)
153 (?:
154 nrk:|
155 https?://
156 (?:
157 (?:www\.)?nrk\.no/video/PS\*|
158 v8-psapi\.nrk\.no/mediaelement/
159 )
160 )
161 (?P<id>[^/?#&]+)
162 '''
d8d540cf
S
163 _API_HOST = 'v8.psapi.nrk.no'
164 _TESTS = [{
165 # video
166 'url': 'http://www.nrk.no/video/PS*150533',
18cf6381 167 'md5': '2f7f6eeb2aacdd99885f355428715cfa',
d8d540cf
S
168 'info_dict': {
169 'id': '150533',
18cf6381 170 'ext': 'mp4',
d8d540cf
S
171 'title': 'Dompap og andre fugler i Piip-Show',
172 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
173 'duration': 263,
174 }
175 }, {
176 # audio
177 'url': 'http://www.nrk.no/video/PS*154915',
178 # MD5 is unstable
179 'info_dict': {
180 'id': '154915',
181 'ext': 'flv',
182 'title': 'Slik høres internett ut når du er blind',
183 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
184 'duration': 20,
185 }
e2628fb6
S
186 }, {
187 'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
188 'only_matching': True,
853a71b6
S
189 }, {
190 'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
191 'only_matching': True,
d8d540cf
S
192 }]
193
194
195class NRKTVIE(NRKBaseIE):
196 IE_DESC = 'NRK TV and NRK Radio'
197 _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/(?:serie/[^/]+|program)/(?P<id>[a-zA-Z]{4}\d{8})(?:/\d{2}-\d{2}-\d{4})?(?:#del=(?P<part_id>\d+))?'
198 _API_HOST = 'psapi-we.nrk.no'
199
200 _TESTS = [{
201 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
18cf6381 202 'md5': '4e9ca6629f09e588ed240fb11619922a',
d8d540cf 203 'info_dict': {
18cf6381 204 'id': 'MUHH48000314AA',
d8d540cf 205 'ext': 'mp4',
18cf6381 206 'title': '20 spørsmål 23.05.2014',
d8d540cf 207 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
4e790117 208 'duration': 1741,
d8d540cf 209 },
d8d540cf
S
210 }, {
211 'url': 'https://tv.nrk.no/program/mdfp15000514',
18cf6381 212 'md5': '43d0be26663d380603a9cf0c24366531',
d8d540cf 213 'info_dict': {
18cf6381 214 'id': 'MDFP15000514CA',
d8d540cf 215 'ext': 'mp4',
18cf6381 216 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
217 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
4e790117 218 'duration': 4605,
d8d540cf 219 },
d8d540cf
S
220 }, {
221 # single playlist video
222 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
223 'md5': 'adbd1dbd813edaf532b0a253780719c2',
224 'info_dict': {
225 'id': 'MSPO40010515-part2',
226 'ext': 'flv',
227 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
228 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
d8d540cf
S
229 },
230 'skip': 'Only works from Norway',
231 }, {
232 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
233 'playlist': [{
234 'md5': '9480285eff92d64f06e02a5367970a7a',
235 'info_dict': {
236 'id': 'MSPO40010515-part1',
237 'ext': 'flv',
238 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 1:2)',
239 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
d8d540cf
S
240 },
241 }, {
242 'md5': 'adbd1dbd813edaf532b0a253780719c2',
243 'info_dict': {
244 'id': 'MSPO40010515-part2',
245 'ext': 'flv',
246 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
247 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
d8d540cf
S
248 },
249 }],
250 'info_dict': {
251 'id': 'MSPO40010515',
252 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn',
253 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
d8d540cf
S
254 'duration': 6947.52,
255 },
256 'skip': 'Only works from Norway',
257 }, {
258 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
259 'only_matching': True,
260 }]
261
dfb2e1a3 262
faa1b5c2 263class NRKPlaylistIE(InfoExtractor):
3099b312 264 _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
faa1b5c2 265
a0914154 266 _TESTS = [{
faa1b5c2
S
267 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
268 'info_dict': {
269 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
270 'title': 'Gjenopplev den historiske solformørkelsen',
271 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
272 },
a0914154
S
273 'playlist_count': 2,
274 }, {
275 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
276 'info_dict': {
277 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
278 'title': 'Rivertonprisen til Karin Fossum',
279 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
280 },
281 'playlist_count': 5,
282 }]
faa1b5c2
S
283
284 def _real_extract(self, url):
285 playlist_id = self._match_id(url)
286
287 webpage = self._download_webpage(url, playlist_id)
288
289 entries = [
290 self.url_result('nrk:%s' % video_id, 'NRK')
291 for video_id in re.findall(
a0914154
S
292 r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"',
293 webpage)
faa1b5c2
S
294 ]
295
296 playlist_title = self._og_search_title(webpage)
297 playlist_description = self._og_search_description(webpage)
298
299 return self.playlist_result(
300 entries, playlist_id, playlist_title, playlist_description)
301
302
3099b312
S
303class NRKSkoleIE(InfoExtractor):
304 IE_DESC = 'NRK Skole'
971e3b75 305 _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
3099b312
S
306
307 _TESTS = [{
971e3b75
S
308 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
309 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
3099b312
S
310 'info_dict': {
311 'id': '6021',
971e3b75 312 'ext': 'mp4',
3099b312
S
313 'title': 'Genetikk og eneggede tvillinger',
314 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
315 'duration': 399,
316 },
317 }, {
971e3b75 318 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
61140904 319 'only_matching': True,
3099b312
S
320 }]
321
322 def _real_extract(self, url):
971e3b75
S
323 video_id = self._match_id(url)
324
325 webpage = self._download_webpage(
326 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
327 video_id)
3099b312 328
971e3b75
S
329 nrk_id = self._parse_json(
330 self._search_regex(
331 r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
332 webpage, 'application json'),
333 video_id)['activeMedia']['psId']
3099b312 334
3099b312 335 return self.url_result('nrk:%s' % nrk_id)