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