Merge branch 'subtitles-rework'
[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 ..utils import (
8     ExtractorError,
9     float_or_none,
10     parse_duration,
11     unified_strdate,
12 )
13
14
15 class NRKIE(InfoExtractor):
16     _VALID_URL = r'http://(?:www\.)?nrk\.no/(?:video|lyd)/[^/]+/(?P<id>[\dA-F]{16})'
17
18     _TESTS = [
19         {
20             'url': 'http://www.nrk.no/video/dompap_og_andre_fugler_i_piip_show/D0FA54B5C8B6CE59/emne/piipshow/',
21             'md5': 'a6eac35052f3b242bb6bb7f43aed5886',
22             'info_dict': {
23                 'id': '150533',
24                 'ext': 'flv',
25                 'title': 'Dompap og andre fugler i Piip-Show',
26                 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f'
27             }
28         },
29         {
30             'url': 'http://www.nrk.no/lyd/lyd_av_oppleser_for_blinde/AEFDDD5473BA0198/',
31             'md5': '3471f2a51718195164e88f46bf427668',
32             'info_dict': {
33                 'id': '154915',
34                 'ext': 'flv',
35                 'title': 'Slik høres internett ut når du er blind',
36                 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
37             }
38         },
39     ]
40
41     def _real_extract(self, url):
42         mobj = re.match(self._VALID_URL, url)
43         video_id = mobj.group('id')
44
45         page = self._download_webpage(url, video_id)
46
47         video_id = self._html_search_regex(r'<div class="nrk-video" data-nrk-id="(\d+)">', page, 'video id')
48
49         data = self._download_json(
50             'http://v7.psapi.nrk.no/mediaelement/%s' % video_id, video_id, 'Downloading media JSON')
51
52         if data['usageRights']['isGeoBlocked']:
53             raise ExtractorError('NRK har ikke rettig-heter til å vise dette programmet utenfor Norge', expected=True)
54
55         video_url = data['mediaUrl'] + '?hdcore=3.1.1&plugin=aasp-3.1.1.69.124'
56
57         images = data.get('images')
58         if images:
59             thumbnails = images['webImages']
60             thumbnails.sort(key=lambda image: image['pixelWidth'])
61             thumbnail = thumbnails[-1]['imageUrl']
62         else:
63             thumbnail = None
64
65         return {
66             'id': video_id,
67             'url': video_url,
68             'ext': 'flv',
69             'title': data['title'],
70             'description': data['description'],
71             'thumbnail': thumbnail,
72         }
73
74
75 class NRKTVIE(InfoExtractor):
76     _VALID_URL = r'(?P<baseurl>http://tv\.nrk(?:super)?\.no/)(?:serie/[^/]+|program)/(?P<id>[a-zA-Z]{4}\d{8})(?:/\d{2}-\d{2}-\d{4})?(?:#del=(?P<part_id>\d+))?'
77
78     _TESTS = [
79         {
80             'url': 'http://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
81             'md5': 'adf2c5454fa2bf032f47a9f8fb351342',
82             'info_dict': {
83                 'id': 'MUHH48000314',
84                 'ext': 'flv',
85                 'title': '20 spørsmål',
86                 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
87                 'upload_date': '20140523',
88                 'duration': 1741.52,
89             },
90         },
91         {
92             'url': 'http://tv.nrk.no/program/mdfp15000514',
93             'md5': '383650ece2b25ecec996ad7b5bb2a384',
94             'info_dict': {
95                 'id': 'mdfp15000514',
96                 'ext': 'flv',
97                 'title': 'Kunnskapskanalen: Grunnlovsjubiléet - Stor ståhei for ingenting',
98                 'description': 'md5:654c12511f035aed1e42bdf5db3b206a',
99                 'upload_date': '20140524',
100                 'duration': 4605.0,
101             },
102         },
103         {
104             # single playlist video
105             'url': 'http://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
106             'md5': 'adbd1dbd813edaf532b0a253780719c2',
107             'info_dict': {
108                 'id': 'MSPO40010515-part2',
109                 'ext': 'flv',
110                 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
111                 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
112                 'upload_date': '20150106',
113             },
114             'skip': 'Only works from Norway',
115         },
116         {
117             'url': 'http://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
118             'playlist': [
119                 {
120                     'md5': '9480285eff92d64f06e02a5367970a7a',
121                     'info_dict': {
122                         'id': 'MSPO40010515-part1',
123                         'ext': 'flv',
124                         'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 1:2)',
125                         'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
126                         'upload_date': '20150106',
127                     },
128                 },
129                 {
130                     'md5': 'adbd1dbd813edaf532b0a253780719c2',
131                     'info_dict': {
132                         'id': 'MSPO40010515-part2',
133                         'ext': 'flv',
134                         'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
135                         'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
136                         'upload_date': '20150106',
137                     },
138                 },
139             ],
140             'info_dict': {
141                 'id': 'MSPO40010515',
142                 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn',
143                 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
144                 'upload_date': '20150106',
145                 'duration': 6947.5199999999995,
146             },
147             'skip': 'Only works from Norway',
148         }
149     ]
150
151     def _seconds2str(self, s):
152         return '%02d:%02d:%02d.%03d' % (s / 3600, (s % 3600) / 60, s % 60, (s % 1) * 1000)
153
154     def _debug_print(self, txt):
155         if self._downloader.params.get('verbose', False):
156             self.to_screen('[debug] %s' % txt)
157
158     def _get_subtitles(self, subtitlesurl, video_id, baseurl):
159         url = "%s%s" % (baseurl, subtitlesurl)
160         self._debug_print('%s: Subtitle url: %s' % (video_id, url))
161         captions = self._download_xml(url, video_id, 'Downloading subtitles')
162         lang = captions.get('lang', 'no')
163         ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/ns/ttml}'))
164         srt = ''
165         for pos, p in enumerate(ps):
166             begin = parse_duration(p.get('begin'))
167             duration = parse_duration(p.get('dur'))
168             starttime = self._seconds2str(begin)
169             endtime = self._seconds2str(begin + duration)
170             text = '\n'.join(p.itertext())
171             srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), starttime, endtime, text)
172         return {lang: [
173             {'ext': 'ttml', 'url': url},
174             {'ext': 'srt', 'data': srt},
175         ]}
176
177     def _extract_f4m(self, manifest_url, video_id):
178         return self._extract_f4m_formats(manifest_url + '?hdcore=3.1.1&plugin=aasp-3.1.1.69.124', video_id)
179
180     def _real_extract(self, url):
181         mobj = re.match(self._VALID_URL, url)
182         video_id = mobj.group('id')
183         part_id = mobj.group('part_id')
184         baseurl = mobj.group('baseurl')
185
186         webpage = self._download_webpage(url, video_id)
187
188         title = self._html_search_meta(
189             'title', webpage, 'title')
190         description = self._html_search_meta(
191             'description', webpage, 'description')
192
193         thumbnail = self._html_search_regex(
194             r'data-posterimage="([^"]+)"',
195             webpage, 'thumbnail', fatal=False)
196         upload_date = unified_strdate(self._html_search_meta(
197             'rightsfrom', webpage, 'upload date', fatal=False))
198         duration = float_or_none(self._html_search_regex(
199             r'data-duration="([^"]+)"',
200             webpage, 'duration', fatal=False))
201
202         # playlist
203         parts = re.findall(
204             r'<a href="#del=(\d+)"[^>]+data-argument="([^"]+)">([^<]+)</a>', webpage)
205         if parts:
206             entries = []
207             for current_part_id, stream_url, part_title in parts:
208                 if part_id and current_part_id != part_id:
209                     continue
210                 video_part_id = '%s-part%s' % (video_id, current_part_id)
211                 formats = self._extract_f4m(stream_url, video_part_id)
212                 entries.append({
213                     'id': video_part_id,
214                     'title': part_title,
215                     'description': description,
216                     'thumbnail': thumbnail,
217                     'upload_date': upload_date,
218                     'formats': formats,
219                 })
220             if part_id:
221                 if entries:
222                     return entries[0]
223             else:
224                 playlist = self.playlist_result(entries, video_id, title, description)
225                 playlist.update({
226                     'thumbnail': thumbnail,
227                     'upload_date': upload_date,
228                     'duration': duration,
229                 })
230                 return playlist
231
232         formats = []
233
234         f4m_url = re.search(r'data-media="([^"]+)"', webpage)
235         if f4m_url:
236             formats.extend(self._extract_f4m(f4m_url.group(1), video_id))
237
238         m3u8_url = re.search(r'data-hls-media="([^"]+)"', webpage)
239         if m3u8_url:
240             formats.extend(self._extract_m3u8_formats(m3u8_url.group(1), video_id, 'mp4'))
241         self._sort_formats(formats)
242
243         subtitles_url = self._html_search_regex(
244             r'data-subtitlesurl[ ]*=[ ]*"([^"]+)"',
245             webpage, 'subtitle URL', default=None)
246         subtitles = None
247         if subtitles_url:
248             subtitles = self.extract_subtitles(subtitles_url, video_id, baseurl)
249
250         return {
251             'id': video_id,
252             'title': title,
253             'description': description,
254             'thumbnail': thumbnail,
255             'upload_date': upload_date,
256             'duration': duration,
257             'formats': formats,
258             'subtitles': subtitles,
259         }