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