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