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