[nrk] Rework extractor (Closes #9470)
[youtube-dl] / youtube_dl / extractor / nrk.py
1 # encoding: 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     def _extract_formats(self, manifest_url, video_id, fatal=True):
18         return self._extract_f4m_formats(
19             manifest_url + '?hdcore=3.5.0&plugin=aasp-3.5.0.151.81',
20             video_id, f4m_id='hds', fatal=fatal)
21
22     def _real_extract(self, url):
23         video_id = self._match_id(url)
24
25         data = self._download_json(
26             'http://%s/mediaelement/%s' % (self._API_HOST, video_id),
27             video_id, 'Downloading mediaelement JSON')
28
29         title = data.get('fullTitle') or data.get('mainTitle') or data['title']
30         video_id = data.get('id') or video_id
31
32         entries = []
33
34         media_assets = data.get('mediaAssets')
35         if media_assets and isinstance(media_assets, list):
36             def video_id_and_title(idx):
37                 return ((video_id, title) if len(media_assets) == 1
38                         else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
39             for num, asset in enumerate(media_assets, 1):
40                 asset_url = asset.get('url')
41                 if not asset_url:
42                     continue
43                 formats = self._extract_formats(asset_url, video_id, fatal=False)
44                 if not formats:
45                     continue
46                 self._sort_formats(formats)
47                 entry_id, entry_title = video_id_and_title(num)
48                 duration = parse_duration(asset.get('duration'))
49                 subtitles = {}
50                 for subtitle in ('webVtt', 'timedText'):
51                     subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
52                     if subtitle_url:
53                         subtitles.setdefault('no', []).append({'url': subtitle_url})
54                 entries.append({
55                     'id': asset.get('carrierId') or entry_id,
56                     'title': entry_title,
57                     'duration': duration,
58                     'subtitles': subtitles,
59                     'formats': formats,
60                 })
61
62         if not entries:
63             media_url = data.get('mediaUrl')
64             if media_url:
65                 formats = self._extract_formats(media_url, video_id)
66                 self._sort_formats(formats)
67                 duration = parse_duration(data.get('duration'))
68                 entries = [{
69                     'id': video_id,
70                     'title': title,
71                     'duration': duration,
72                     'formats': formats,
73                 }]
74
75         if not entries:
76             if data.get('usageRights', {}).get('isGeoBlocked'):
77                 raise ExtractorError(
78                     'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
79                     expected=True)
80
81         conviva = data.get('convivaStatistics') or {}
82         series = conviva.get('seriesName') or data.get('seriesTitle')
83         episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
84
85         thumbnails = None
86         images = data.get('images')
87         if images and isinstance(images, dict):
88             web_images = images.get('webImages')
89             if isinstance(web_images, list):
90                 thumbnails = [{
91                     'url': image['imageUrl'],
92                     'width': int_or_none(image.get('width')),
93                     'height': int_or_none(image.get('height')),
94                 } for image in web_images if image.get('imageUrl')]
95
96         description = data.get('description')
97
98         common_info = {
99             'description': description,
100             'series': series,
101             'episode': episode,
102             'age_limit': parse_age_limit(data.get('legalAge')),
103             'thumbnails': thumbnails,
104         }
105
106         vcodec = 'none' if data.get('mediaType') == 'Audio' else None
107
108         # TODO: extract chapters when https://github.com/rg3/youtube-dl/pull/9409 is merged
109
110         for entry in entries:
111             entry.update(common_info)
112             for f in entry['formats']:
113                 f['vcodec'] = vcodec
114
115         return self.playlist_result(entries, video_id, title, description)
116
117
118 class NRKIE(NRKBaseIE):
119     _VALID_URL = r'(?:nrk:|https?://(?:www\.)?nrk\.no/video/PS\*)(?P<id>\d+)'
120     _API_HOST = 'v8.psapi.nrk.no'
121     _TESTS = [{
122         # video
123         'url': 'http://www.nrk.no/video/PS*150533',
124         # MD5 is unstable
125         'info_dict': {
126             'id': '150533',
127             'ext': 'flv',
128             'title': 'Dompap og andre fugler i Piip-Show',
129             'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
130             'duration': 263,
131         }
132     }, {
133         # audio
134         'url': 'http://www.nrk.no/video/PS*154915',
135         # MD5 is unstable
136         'info_dict': {
137             'id': '154915',
138             'ext': 'flv',
139             'title': 'Slik høres internett ut når du er blind',
140             'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
141             'duration': 20,
142         }
143     }]
144
145
146 class NRKTVIE(NRKBaseIE):
147     IE_DESC = 'NRK TV and NRK Radio'
148     _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+))?'
149     _API_HOST = 'psapi-we.nrk.no'
150
151     _TESTS = [{
152         'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
153         'info_dict': {
154             'id': 'MUHH48000314',
155             'ext': 'mp4',
156             'title': '20 spørsmål',
157             'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
158             'upload_date': '20140523',
159             'duration': 1741.52,
160         },
161         'params': {
162             # m3u8 download
163             'skip_download': True,
164         },
165     }, {
166         'url': 'https://tv.nrk.no/program/mdfp15000514',
167         'info_dict': {
168             'id': 'mdfp15000514',
169             'ext': 'mp4',
170             'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting',
171             'description': 'md5:654c12511f035aed1e42bdf5db3b206a',
172             'upload_date': '20140524',
173             'duration': 4605.08,
174         },
175         'params': {
176             # m3u8 download
177             'skip_download': True,
178         },
179     }, {
180         # single playlist video
181         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
182         'md5': 'adbd1dbd813edaf532b0a253780719c2',
183         'info_dict': {
184             'id': 'MSPO40010515-part2',
185             'ext': 'flv',
186             'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
187             'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
188             'upload_date': '20150106',
189         },
190         'skip': 'Only works from Norway',
191     }, {
192         'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
193         'playlist': [{
194             'md5': '9480285eff92d64f06e02a5367970a7a',
195             'info_dict': {
196                 'id': 'MSPO40010515-part1',
197                 'ext': 'flv',
198                 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 1:2)',
199                 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
200                 'upload_date': '20150106',
201             },
202         }, {
203             'md5': 'adbd1dbd813edaf532b0a253780719c2',
204             'info_dict': {
205                 'id': 'MSPO40010515-part2',
206                 'ext': 'flv',
207                 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
208                 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
209                 'upload_date': '20150106',
210             },
211         }],
212         'info_dict': {
213             'id': 'MSPO40010515',
214             'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn',
215             'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
216             'upload_date': '20150106',
217             'duration': 6947.52,
218         },
219         'skip': 'Only works from Norway',
220     }, {
221         'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
222         'only_matching': True,
223     }]
224
225
226 class NRKPlaylistIE(InfoExtractor):
227     _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
228
229     _TESTS = [{
230         'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
231         'info_dict': {
232             'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
233             'title': 'Gjenopplev den historiske solformørkelsen',
234             'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
235         },
236         'playlist_count': 2,
237     }, {
238         'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
239         'info_dict': {
240             'id': 'rivertonprisen-til-karin-fossum-1.12266449',
241             'title': 'Rivertonprisen til Karin Fossum',
242             'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
243         },
244         'playlist_count': 5,
245     }]
246
247     def _real_extract(self, url):
248         playlist_id = self._match_id(url)
249
250         webpage = self._download_webpage(url, playlist_id)
251
252         entries = [
253             self.url_result('nrk:%s' % video_id, 'NRK')
254             for video_id in re.findall(
255                 r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"',
256                 webpage)
257         ]
258
259         playlist_title = self._og_search_title(webpage)
260         playlist_description = self._og_search_description(webpage)
261
262         return self.playlist_result(
263             entries, playlist_id, playlist_title, playlist_description)
264
265
266 class NRKSkoleIE(InfoExtractor):
267     IE_DESC = 'NRK Skole'
268     _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/klippdetalj?.*\btopic=(?P<id>[^/?#&]+)'
269
270     _TESTS = [{
271         'url': 'http://nrk.no/skole/klippdetalj?topic=nrk:klipp/616532',
272         'md5': '04cd85877cc1913bce73c5d28a47e00f',
273         'info_dict': {
274             'id': '6021',
275             'ext': 'flv',
276             'title': 'Genetikk og eneggede tvillinger',
277             'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
278             'duration': 399,
279         },
280     }, {
281         'url': 'http://www.nrk.no/skole/klippdetalj?topic=nrk%3Aklipp%2F616532#embed',
282         'only_matching': True,
283     }, {
284         'url': 'http://www.nrk.no/skole/klippdetalj?topic=urn:x-mediadb:21379',
285         'only_matching': True,
286     }]
287
288     def _real_extract(self, url):
289         video_id = compat_urllib_parse_unquote(self._match_id(url))
290
291         webpage = self._download_webpage(url, video_id)
292
293         nrk_id = self._search_regex(r'data-nrk-id=["\'](\d+)', webpage, 'nrk id')
294         return self.url_result('nrk:%s' % nrk_id)