[orf:radio] Fix extraction
[youtube-dl] / youtube_dl / extractor / orf.py
1 # coding: 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     HEADRequest,
10     unified_strdate,
11     strip_jsonp,
12     int_or_none,
13     float_or_none,
14     determine_ext,
15     remove_end,
16     unescapeHTML,
17 )
18
19
20 class ORFTVthekIE(InfoExtractor):
21     IE_NAME = 'orf:tvthek'
22     IE_DESC = 'ORF TVthek'
23     _VALID_URL = r'https?://tvthek\.orf\.at/(?:[^/]+/)+(?P<id>\d+)'
24
25     _TESTS = [{
26         'url': 'http://tvthek.orf.at/program/Aufgetischt/2745173/Aufgetischt-Mit-der-Steirischen-Tafelrunde/8891389',
27         'playlist': [{
28             'md5': '2942210346ed779588f428a92db88712',
29             'info_dict': {
30                 'id': '8896777',
31                 'ext': 'mp4',
32                 'title': 'Aufgetischt: Mit der Steirischen Tafelrunde',
33                 'description': 'md5:c1272f0245537812d4e36419c207b67d',
34                 'duration': 2668,
35                 'upload_date': '20141208',
36             },
37         }],
38         'skip': 'Blocked outside of Austria / Germany',
39     }, {
40         'url': 'http://tvthek.orf.at/topic/Im-Wandel-der-Zeit/8002126/Best-of-Ingrid-Thurnher/7982256',
41         'info_dict': {
42             'id': '7982259',
43             'ext': 'mp4',
44             'title': 'Best of Ingrid Thurnher',
45             'upload_date': '20140527',
46             'description': 'Viele Jahre war Ingrid Thurnher das "Gesicht" der ZIB 2. Vor ihrem Wechsel zur ZIB 2 im Jahr 1995 moderierte sie unter anderem "Land und Leute", "Österreich-Bild" und "Niederösterreich heute".',
47         },
48         'params': {
49             'skip_download': True,  # rtsp downloads
50         },
51         '_skip': 'Blocked outside of Austria / Germany',
52     }, {
53         'url': 'http://tvthek.orf.at/topic/Fluechtlingskrise/10463081/Heimat-Fremde-Heimat/13879132/Senioren-betreuen-Migrantenkinder/13879141',
54         'skip_download': True,
55     }, {
56         'url': 'http://tvthek.orf.at/profile/Universum/35429',
57         'skip_download': True,
58     }]
59
60     def _real_extract(self, url):
61         playlist_id = self._match_id(url)
62         webpage = self._download_webpage(url, playlist_id)
63
64         data_jsb = self._parse_json(
65             self._search_regex(
66                 r'<div[^>]+class=(["\']).*?VideoPlaylist.*?\1[^>]+data-jsb=(["\'])(?P<json>.+?)\2',
67                 webpage, 'playlist', group='json'),
68             playlist_id, transform_source=unescapeHTML)['playlist']['videos']
69
70         def quality_to_int(s):
71             m = re.search('([0-9]+)', s)
72             if m is None:
73                 return -1
74             return int(m.group(1))
75
76         entries = []
77         for sd in data_jsb:
78             video_id, title = sd.get('id'), sd.get('title')
79             if not video_id or not title:
80                 continue
81             video_id = compat_str(video_id)
82             formats = [{
83                 'preference': -10 if fd['delivery'] == 'hls' else None,
84                 'format_id': '%s-%s-%s' % (
85                     fd['delivery'], fd['quality'], fd['quality_string']),
86                 'url': fd['src'],
87                 'protocol': fd['protocol'],
88                 'quality': quality_to_int(fd['quality']),
89             } for fd in sd['sources']]
90
91             # Check for geoblocking.
92             # There is a property is_geoprotection, but that's always false
93             geo_str = sd.get('geoprotection_string')
94             if geo_str:
95                 try:
96                     http_url = next(
97                         f['url']
98                         for f in formats
99                         if re.match(r'^https?://.*\.mp4$', f['url']))
100                 except StopIteration:
101                     pass
102                 else:
103                     req = HEADRequest(http_url)
104                     self._request_webpage(
105                         req, video_id,
106                         note='Testing for geoblocking',
107                         errnote=((
108                             'This video seems to be blocked outside of %s. '
109                             'You may want to try the streaming-* formats.')
110                             % geo_str),
111                         fatal=False)
112
113             self._check_formats(formats, video_id)
114             self._sort_formats(formats)
115
116             subtitles = {}
117             for sub in sd.get('subtitles', []):
118                 sub_src = sub.get('src')
119                 if not sub_src:
120                     continue
121                 subtitles.setdefault(sub.get('lang', 'de-AT'), []).append({
122                     'url': sub_src,
123                 })
124
125             upload_date = unified_strdate(sd.get('created_date'))
126             entries.append({
127                 '_type': 'video',
128                 'id': video_id,
129                 'title': title,
130                 'formats': formats,
131                 'subtitles': subtitles,
132                 'description': sd.get('description'),
133                 'duration': int_or_none(sd.get('duration_in_seconds')),
134                 'upload_date': upload_date,
135                 'thumbnail': sd.get('image_full_url'),
136             })
137
138         return {
139             '_type': 'playlist',
140             'entries': entries,
141             'id': playlist_id,
142         }
143
144
145 class ORFRadioIE(InfoExtractor):
146     def _real_extract(self, url):
147         mobj = re.match(self._VALID_URL, url)
148         station = mobj.group('station')
149         show_date = mobj.group('date')
150         show_id = mobj.group('show')
151
152         if station == 'fm4':
153             show_id = '4%s' % show_id
154
155         data = self._download_json(
156             'http://audioapi.orf.at/%s/api/json/current/broadcast/%s/%s' % (station, show_id, show_date),
157             show_id
158         )
159
160         def extract_entry_dict(info, title, subtitle):
161             return {
162                 'id': info['loopStreamId'].replace('.mp3', ''),
163                 'url': 'http://loopstream01.apa.at/?channel=%s&id=%s' % (station, info['loopStreamId']),
164                 'title': title,
165                 'description': subtitle,
166                 'duration': (info['end'] - info['start']) / 1000,
167                 'timestamp': info['start'] / 1000,
168                 'ext': 'mp3'
169             }
170
171         entries = [extract_entry_dict(t, data['title'], data['subtitle']) for t in data['streams']]
172
173         return {
174             '_type': 'playlist',
175             'id': show_id,
176             'title': data['title'],
177             'description': data['subtitle'],
178             'entries': entries
179         }
180
181
182 class ORFFM4IE(ORFRadioIE):
183     IE_NAME = 'orf:fm4'
184     IE_DESC = 'radio FM4'
185     _VALID_URL = r'https?://(?P<station>fm4)\.orf\.at/(?:7tage/?#|player/)(?P<date>[0-9]+)/(?P<show>\w+)'
186
187     _TESTS = [
188         {
189             'url': 'http://fm4.orf.at/player/20170107/CC',
190             'md5': '2b0be47375432a7ef104453432a19212',
191             'info_dict': {
192                 'id': '2017-01-07_2100_tl_54_7DaysSat18_31295',
193                 'ext': 'mp3',
194                 'title': 'Solid Steel Radioshow',
195                 'description': 'Die Mixshow von Coldcut und Ninja Tune.',
196                 'duration': 3599,
197                 'timestamp': 1483819257,
198                 'upload_date': '20170107',
199             },
200             'skip': 'Shows from ORF radios are only available for 7 days.'
201         }
202     ]
203
204
205 class ORFOE1IE(ORFRadioIE):
206     IE_NAME = 'orf:oe1'
207     IE_DESC = 'Radio Österreich 1'
208     _VALID_URL = r'https?://(?P<station>oe1)\.orf\.at/(?:7tage/?#|player/)(?P<date>[0-9]+)/(?P<show>\w+)'
209
210     _TESTS = [
211        {
212             'url': 'http://oe1.orf.at/player/20170108/456544',
213             'md5': '34d8a6e67ea888293741c86a099b745b',
214             'info_dict': {
215                 'id': '2017-01-08_0759_tl_51_7DaysSun6_256141',
216                 'ext': 'mp3',
217                 'title': 'Morgenjournal',
218                 'duration': 609,
219                 'timestamp': 1483858796,
220                 'upload_date': '20170108',
221             },
222             'skip': 'Shows from ORF radios are only available for 7 days.'
223         }
224     ]
225
226
227 class ORFIPTVIE(InfoExtractor):
228     IE_NAME = 'orf:iptv'
229     IE_DESC = 'iptv.ORF.at'
230     _VALID_URL = r'https?://iptv\.orf\.at/(?:#/)?stories/(?P<id>\d+)'
231
232     _TEST = {
233         'url': 'http://iptv.orf.at/stories/2275236/',
234         'md5': 'c8b22af4718a4b4af58342529453e3e5',
235         'info_dict': {
236             'id': '350612',
237             'ext': 'flv',
238             'title': 'Weitere Evakuierungen um Vulkan Calbuco',
239             'description': 'md5:d689c959bdbcf04efeddedbf2299d633',
240             'duration': 68.197,
241             'thumbnail': r're:^https?://.*\.jpg$',
242             'upload_date': '20150425',
243         },
244     }
245
246     def _real_extract(self, url):
247         story_id = self._match_id(url)
248
249         webpage = self._download_webpage(
250             'http://iptv.orf.at/stories/%s' % story_id, story_id)
251
252         video_id = self._search_regex(
253             r'data-video(?:id)?="(\d+)"', webpage, 'video id')
254
255         data = self._download_json(
256             'http://bits.orf.at/filehandler/static-api/json/current/data.json?file=%s' % video_id,
257             video_id)[0]
258
259         duration = float_or_none(data['duration'], 1000)
260
261         video = data['sources']['default']
262         load_balancer_url = video['loadBalancerUrl']
263         abr = int_or_none(video.get('audioBitrate'))
264         vbr = int_or_none(video.get('bitrate'))
265         fps = int_or_none(video.get('videoFps'))
266         width = int_or_none(video.get('videoWidth'))
267         height = int_or_none(video.get('videoHeight'))
268         thumbnail = video.get('preview')
269
270         rendition = self._download_json(
271             load_balancer_url, video_id, transform_source=strip_jsonp)
272
273         f = {
274             'abr': abr,
275             'vbr': vbr,
276             'fps': fps,
277             'width': width,
278             'height': height,
279         }
280
281         formats = []
282         for format_id, format_url in rendition['redirect'].items():
283             if format_id == 'rtmp':
284                 ff = f.copy()
285                 ff.update({
286                     'url': format_url,
287                     'format_id': format_id,
288                 })
289                 formats.append(ff)
290             elif determine_ext(format_url) == 'f4m':
291                 formats.extend(self._extract_f4m_formats(
292                     format_url, video_id, f4m_id=format_id))
293             elif determine_ext(format_url) == 'm3u8':
294                 formats.extend(self._extract_m3u8_formats(
295                     format_url, video_id, 'mp4', m3u8_id=format_id))
296             else:
297                 continue
298         self._sort_formats(formats)
299
300         title = remove_end(self._og_search_title(webpage), ' - iptv.ORF.at')
301         description = self._og_search_description(webpage)
302         upload_date = unified_strdate(self._html_search_meta(
303             'dc.date', webpage, 'upload date'))
304
305         return {
306             'id': video_id,
307             'title': title,
308             'description': description,
309             'duration': duration,
310             'thumbnail': thumbnail,
311             'upload_date': upload_date,
312             'formats': formats,
313         }