[orf:tvthek] Fix extraction (closes #17737)
[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     determine_ext,
10     float_or_none,
11     HEADRequest,
12     int_or_none,
13     orderedSet,
14     remove_end,
15     strip_jsonp,
16     unescapeHTML,
17     unified_strdate,
18 )
19
20
21 class ORFTVthekIE(InfoExtractor):
22     IE_NAME = 'orf:tvthek'
23     IE_DESC = 'ORF TVthek'
24     _VALID_URL = r'https?://tvthek\.orf\.at/(?:[^/]+/)+(?P<id>\d+)'
25
26     _TESTS = [{
27         'url': 'http://tvthek.orf.at/program/Aufgetischt/2745173/Aufgetischt-Mit-der-Steirischen-Tafelrunde/8891389',
28         'playlist': [{
29             'md5': '2942210346ed779588f428a92db88712',
30             'info_dict': {
31                 'id': '8896777',
32                 'ext': 'mp4',
33                 'title': 'Aufgetischt: Mit der Steirischen Tafelrunde',
34                 'description': 'md5:c1272f0245537812d4e36419c207b67d',
35                 'duration': 2668,
36                 'upload_date': '20141208',
37             },
38         }],
39         'skip': 'Blocked outside of Austria / Germany',
40     }, {
41         'url': 'http://tvthek.orf.at/topic/Im-Wandel-der-Zeit/8002126/Best-of-Ingrid-Thurnher/7982256',
42         'info_dict': {
43             'id': '7982259',
44             'ext': 'mp4',
45             'title': 'Best of Ingrid Thurnher',
46             'upload_date': '20140527',
47             '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".',
48         },
49         'params': {
50             'skip_download': True,  # rtsp downloads
51         },
52         'skip': 'Blocked outside of Austria / Germany',
53     }, {
54         'url': 'http://tvthek.orf.at/topic/Fluechtlingskrise/10463081/Heimat-Fremde-Heimat/13879132/Senioren-betreuen-Migrantenkinder/13879141',
55         'only_matching': True,
56     }, {
57         'url': 'http://tvthek.orf.at/profile/Universum/35429',
58         'only_matching': True,
59     }]
60
61     def _real_extract(self, url):
62         playlist_id = self._match_id(url)
63         webpage = self._download_webpage(url, playlist_id)
64
65         data_jsb = self._parse_json(
66             self._search_regex(
67                 r'<div[^>]+class=(["\']).*?VideoPlaylist.*?\1[^>]+data-jsb=(["\'])(?P<json>.+?)\2',
68                 webpage, 'playlist', group='json'),
69             playlist_id, transform_source=unescapeHTML)['playlist']['videos']
70
71         def quality_to_int(s):
72             m = re.search('([0-9]+)', s)
73             if m is None:
74                 return -1
75             return int(m.group(1))
76
77         entries = []
78         for sd in data_jsb:
79             video_id, title = sd.get('id'), sd.get('title')
80             if not video_id or not title:
81                 continue
82             video_id = compat_str(video_id)
83             formats = []
84             for fd in sd['sources']:
85                 format_id = '%s-%s-%s' % (
86                     fd['delivery'], fd['quality'], fd['quality_string'])
87                 if determine_ext(fd['src']) == 'm3u8':
88                     formats.extend(self._extract_m3u8_formats(
89                         fd['src'], video_id, 'mp4', m3u8_id=format_id))
90                 elif determine_ext(fd['src']) == 'f4m':
91                     formats.extend(self._extract_f4m_formats(
92                         fd['src'], video_id, f4m_id=format_id))
93
94             # Check for geoblocking.
95             # There is a property is_geoprotection, but that's always false
96             geo_str = sd.get('geoprotection_string')
97             if geo_str:
98                 try:
99                     http_url = next(
100                         f['url']
101                         for f in formats
102                         if re.match(r'^https?://.*\.mp4$', f['url']))
103                 except StopIteration:
104                     pass
105                 else:
106                     req = HEADRequest(http_url)
107                     self._request_webpage(
108                         req, video_id,
109                         note='Testing for geoblocking',
110                         errnote=((
111                             'This video seems to be blocked outside of %s. '
112                             'You may want to try the streaming-* formats.')
113                             % geo_str),
114                         fatal=False)
115
116             self._check_formats(formats, video_id)
117             self._sort_formats(formats)
118
119             subtitles = {}
120             for sub in sd.get('subtitles', []):
121                 sub_src = sub.get('src')
122                 if not sub_src:
123                     continue
124                 subtitles.setdefault(sub.get('lang', 'de-AT'), []).append({
125                     'url': sub_src,
126                 })
127
128             upload_date = unified_strdate(sd.get('created_date'))
129             entries.append({
130                 '_type': 'video',
131                 'id': video_id,
132                 'title': title,
133                 'formats': formats,
134                 'subtitles': subtitles,
135                 'description': sd.get('description'),
136                 'duration': int_or_none(sd.get('duration_in_seconds')),
137                 'upload_date': upload_date,
138                 'thumbnail': sd.get('image_full_url'),
139             })
140
141         return {
142             '_type': 'playlist',
143             'entries': entries,
144             'id': playlist_id,
145         }
146
147
148 class ORFRadioIE(InfoExtractor):
149     def _real_extract(self, url):
150         mobj = re.match(self._VALID_URL, url)
151         station = mobj.group('station')
152         show_date = mobj.group('date')
153         show_id = mobj.group('show')
154
155         if station == 'fm4':
156             show_id = '4%s' % show_id
157
158         data = self._download_json(
159             'http://audioapi.orf.at/%s/api/json/current/broadcast/%s/%s' % (station, show_id, show_date),
160             show_id
161         )
162
163         def extract_entry_dict(info, title, subtitle):
164             return {
165                 'id': info['loopStreamId'].replace('.mp3', ''),
166                 'url': 'http://loopstream01.apa.at/?channel=%s&id=%s' % (station, info['loopStreamId']),
167                 'title': title,
168                 'description': subtitle,
169                 'duration': (info['end'] - info['start']) / 1000,
170                 'timestamp': info['start'] / 1000,
171                 'ext': 'mp3'
172             }
173
174         entries = [extract_entry_dict(t, data['title'], data['subtitle']) for t in data['streams']]
175
176         return {
177             '_type': 'playlist',
178             'id': show_id,
179             'title': data['title'],
180             'description': data['subtitle'],
181             'entries': entries
182         }
183
184
185 class ORFFM4IE(ORFRadioIE):
186     IE_NAME = 'orf:fm4'
187     IE_DESC = 'radio FM4'
188     _VALID_URL = r'https?://(?P<station>fm4)\.orf\.at/player/(?P<date>[0-9]+)/(?P<show>\w+)'
189
190     _TEST = {
191         'url': 'http://fm4.orf.at/player/20170107/CC',
192         'md5': '2b0be47375432a7ef104453432a19212',
193         'info_dict': {
194             'id': '2017-01-07_2100_tl_54_7DaysSat18_31295',
195             'ext': 'mp3',
196             'title': 'Solid Steel Radioshow',
197             'description': 'Die Mixshow von Coldcut und Ninja Tune.',
198             'duration': 3599,
199             'timestamp': 1483819257,
200             'upload_date': '20170107',
201         },
202         'skip': 'Shows from ORF radios are only available for 7 days.'
203     }
204
205
206 class ORFOE1IE(ORFRadioIE):
207     IE_NAME = 'orf:oe1'
208     IE_DESC = 'Radio Österreich 1'
209     _VALID_URL = r'https?://(?P<station>oe1)\.orf\.at/player/(?P<date>[0-9]+)/(?P<show>\w+)'
210
211     _TEST = {
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 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': r'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         }
313
314
315 class ORFFM4StoryIE(InfoExtractor):
316     IE_NAME = 'orf:fm4:story'
317     IE_DESC = 'fm4.orf.at stories'
318     _VALID_URL = r'https?://fm4\.orf\.at/stories/(?P<id>\d+)'
319
320     _TEST = {
321         'url': 'http://fm4.orf.at/stories/2865738/',
322         'playlist': [{
323             'md5': 'e1c2c706c45c7b34cf478bbf409907ca',
324             'info_dict': {
325                 'id': '547792',
326                 'ext': 'flv',
327                 'title': 'Manu Delago und Inner Tongue live',
328                 'description': 'Manu Delago und Inner Tongue haben bei der FM4 Soundpark Session live alles gegeben. Hier gibt es Fotos und die gesamte Session als Video.',
329                 'duration': 1748.52,
330                 'thumbnail': r're:^https?://.*\.jpg$',
331                 'upload_date': '20170913',
332             },
333         }, {
334             'md5': 'c6dd2179731f86f4f55a7b49899d515f',
335             'info_dict': {
336                 'id': '547798',
337                 'ext': 'flv',
338                 'title': 'Manu Delago und Inner Tongue live (2)',
339                 'duration': 1504.08,
340                 'thumbnail': r're:^https?://.*\.jpg$',
341                 'upload_date': '20170913',
342                 'description': 'Manu Delago und Inner Tongue haben bei der FM4 Soundpark Session live alles gegeben. Hier gibt es Fotos und die gesamte Session als Video.',
343             },
344         }],
345     }
346
347     def _real_extract(self, url):
348         story_id = self._match_id(url)
349         webpage = self._download_webpage(url, story_id)
350
351         entries = []
352         all_ids = orderedSet(re.findall(r'data-video(?:id)?="(\d+)"', webpage))
353         for idx, video_id in enumerate(all_ids):
354             data = self._download_json(
355                 'http://bits.orf.at/filehandler/static-api/json/current/data.json?file=%s' % video_id,
356                 video_id)[0]
357
358             duration = float_or_none(data['duration'], 1000)
359
360             video = data['sources']['q8c']
361             load_balancer_url = video['loadBalancerUrl']
362             abr = int_or_none(video.get('audioBitrate'))
363             vbr = int_or_none(video.get('bitrate'))
364             fps = int_or_none(video.get('videoFps'))
365             width = int_or_none(video.get('videoWidth'))
366             height = int_or_none(video.get('videoHeight'))
367             thumbnail = video.get('preview')
368
369             rendition = self._download_json(
370                 load_balancer_url, video_id, transform_source=strip_jsonp)
371
372             f = {
373                 'abr': abr,
374                 'vbr': vbr,
375                 'fps': fps,
376                 'width': width,
377                 'height': height,
378             }
379
380             formats = []
381             for format_id, format_url in rendition['redirect'].items():
382                 if format_id == 'rtmp':
383                     ff = f.copy()
384                     ff.update({
385                         'url': format_url,
386                         'format_id': format_id,
387                     })
388                     formats.append(ff)
389                 elif determine_ext(format_url) == 'f4m':
390                     formats.extend(self._extract_f4m_formats(
391                         format_url, video_id, f4m_id=format_id))
392                 elif determine_ext(format_url) == 'm3u8':
393                     formats.extend(self._extract_m3u8_formats(
394                         format_url, video_id, 'mp4', m3u8_id=format_id))
395                 else:
396                     continue
397             self._sort_formats(formats)
398
399             title = remove_end(self._og_search_title(webpage), ' - fm4.ORF.at')
400             if idx >= 1:
401                 # Titles are duplicates, make them unique
402                 title += ' (' + str(idx + 1) + ')'
403             description = self._og_search_description(webpage)
404             upload_date = unified_strdate(self._html_search_meta(
405                 'dc.date', webpage, 'upload date'))
406
407             entries.append({
408                 'id': video_id,
409                 'title': title,
410                 'description': description,
411                 'duration': duration,
412                 'thumbnail': thumbnail,
413                 'upload_date': upload_date,
414                 'formats': formats,
415             })
416
417         return self.playlist_result(entries)