]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/orf.py
Merge pull request #8130 from dyn888/master
[youtube-dl.git] / youtube_dl / extractor / orf.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6 import calendar
7 import datetime
8
9 from .common import InfoExtractor
10 from ..utils import (
11     HEADRequest,
12     unified_strdate,
13     ExtractorError,
14     strip_jsonp,
15     int_or_none,
16     float_or_none,
17     determine_ext,
18     remove_end,
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/(?:programs/.+?/episodes|topics?/.+?|program/[^/]+)/(?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         'playlist': [{
44             'md5': '68f543909aea49d621dfc7703a11cfaf',
45             'info_dict': {
46                 'id': '7982259',
47                 'ext': 'mp4',
48                 'title': 'Best of Ingrid Thurnher',
49                 'upload_date': '20140527',
50                 '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".',
51             }
52         }],
53         '_skip': 'Blocked outside of Austria / Germany',
54     }]
55
56     def _real_extract(self, url):
57         playlist_id = self._match_id(url)
58         webpage = self._download_webpage(url, playlist_id)
59
60         data_json = self._search_regex(
61             r'initializeAdworx\((.+?)\);\n', webpage, 'video info')
62         all_data = json.loads(data_json)
63
64         def get_segments(all_data):
65             for data in all_data:
66                 if data['name'] in (
67                         'Tracker::EPISODE_DETAIL_PAGE_OVER_PROGRAM',
68                         'Tracker::EPISODE_DETAIL_PAGE_OVER_TOPIC'):
69                     return data['values']['segments']
70
71         sdata = get_segments(all_data)
72         if not sdata:
73             raise ExtractorError('Unable to extract segments')
74
75         def quality_to_int(s):
76             m = re.search('([0-9]+)', s)
77             if m is None:
78                 return -1
79             return int(m.group(1))
80
81         entries = []
82         for sd in sdata:
83             video_id = sd['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['playlist_item_array']['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._sort_formats(formats)
116
117             upload_date = unified_strdate(sd['created_date'])
118             entries.append({
119                 '_type': 'video',
120                 'id': video_id,
121                 'title': sd['header'],
122                 'formats': formats,
123                 'description': sd.get('description'),
124                 'duration': int(sd['duration_in_seconds']),
125                 'upload_date': upload_date,
126                 'thumbnail': sd.get('image_full_url'),
127             })
128
129         return {
130             '_type': 'playlist',
131             'entries': entries,
132             'id': playlist_id,
133         }
134
135
136 class ORFOE1IE(InfoExtractor):
137     IE_NAME = 'orf:oe1'
138     IE_DESC = 'Radio Österreich 1'
139     _VALID_URL = r'http://oe1\.orf\.at/(?:programm/|konsole.*?#\?track_id=)(?P<id>[0-9]+)'
140
141     # Audios on ORF radio are only available for 7 days, so we can't add tests.
142     _TEST = {
143         'url': 'http://oe1.orf.at/konsole?show=on_demand#?track_id=394211',
144         'only_matching': True,
145     }
146
147     def _real_extract(self, url):
148         show_id = self._match_id(url)
149         data = self._download_json(
150             'http://oe1.orf.at/programm/%s/konsole' % show_id,
151             show_id
152         )
153
154         timestamp = datetime.datetime.strptime('%s %s' % (
155             data['item']['day_label'],
156             data['item']['time']
157         ), '%d.%m.%Y %H:%M')
158         unix_timestamp = calendar.timegm(timestamp.utctimetuple())
159
160         return {
161             'id': show_id,
162             'title': data['item']['title'],
163             'url': data['item']['url_stream'],
164             'ext': 'mp3',
165             'description': data['item'].get('info'),
166             'timestamp': unix_timestamp
167         }
168
169
170 class ORFFM4IE(InfoExtractor):
171     IE_NAME = 'orf:fm4'
172     IE_DESC = 'radio FM4'
173     _VALID_URL = r'http://fm4\.orf\.at/(?:7tage/?#|player/)(?P<date>[0-9]+)/(?P<show>\w+)'
174
175     _TEST = {
176         'url': 'http://fm4.orf.at/player/20160110/IS/',
177         'md5': '01e736e8f1cef7e13246e880a59ad298',
178         'info_dict': {
179             'id': '2016-01-10_2100_tl_54_7DaysSun13_11244',
180             'ext': 'mp3',
181             'title': 'Im Sumpf',
182             'description': 'md5:384c543f866c4e422a55f66a62d669cd',
183             'duration': 7173,
184             'timestamp': 1452456073,
185             'upload_date': '20160110',
186         },
187     }
188
189     def _real_extract(self, url):
190         mobj = re.match(self._VALID_URL, url)
191         show_date = mobj.group('date')
192         show_id = mobj.group('show')
193
194         data = self._download_json(
195             'http://audioapi.orf.at/fm4/json/2.0/broadcasts/%s/4%s' % (show_date, show_id),
196             show_id
197         )
198
199         def extract_entry_dict(info, title, subtitle):
200             return {
201                 'id': info['loopStreamId'].replace('.mp3', ''),
202                 'url': 'http://loopstream01.apa.at/?channel=fm4&id=%s' % info['loopStreamId'],
203                 'title': title,
204                 'description': subtitle,
205                 'duration': (info['end'] - info['start']) / 1000,
206                 'timestamp': info['start'] / 1000,
207                 'ext': 'mp3'
208             }
209
210         entries = [extract_entry_dict(t, data['title'], data['subtitle']) for t in data['streams']]
211
212         return {
213             '_type': 'playlist',
214             'id': show_id,
215             'title': data['title'],
216             'description': data['subtitle'],
217             'entries': entries
218         }
219
220
221 class ORFIPTVIE(InfoExtractor):
222     IE_NAME = 'orf:iptv'
223     IE_DESC = 'iptv.ORF.at'
224     _VALID_URL = r'http://iptv\.orf\.at/(?:#/)?stories/(?P<id>\d+)'
225
226     _TEST = {
227         'url': 'http://iptv.orf.at/stories/2275236/',
228         'md5': 'c8b22af4718a4b4af58342529453e3e5',
229         'info_dict': {
230             'id': '350612',
231             'ext': 'flv',
232             'title': 'Weitere Evakuierungen um Vulkan Calbuco',
233             'description': 'md5:d689c959bdbcf04efeddedbf2299d633',
234             'duration': 68.197,
235             'thumbnail': 're:^https?://.*\.jpg$',
236             'upload_date': '20150425',
237         },
238     }
239
240     def _real_extract(self, url):
241         story_id = self._match_id(url)
242
243         webpage = self._download_webpage(
244             'http://iptv.orf.at/stories/%s' % story_id, story_id)
245
246         video_id = self._search_regex(
247             r'data-video(?:id)?="(\d+)"', webpage, 'video id')
248
249         data = self._download_json(
250             'http://bits.orf.at/filehandler/static-api/json/current/data.json?file=%s' % video_id,
251             video_id)[0]
252
253         duration = float_or_none(data['duration'], 1000)
254
255         video = data['sources']['default']
256         load_balancer_url = video['loadBalancerUrl']
257         abr = int_or_none(video.get('audioBitrate'))
258         vbr = int_or_none(video.get('bitrate'))
259         fps = int_or_none(video.get('videoFps'))
260         width = int_or_none(video.get('videoWidth'))
261         height = int_or_none(video.get('videoHeight'))
262         thumbnail = video.get('preview')
263
264         rendition = self._download_json(
265             load_balancer_url, video_id, transform_source=strip_jsonp)
266
267         f = {
268             'abr': abr,
269             'vbr': vbr,
270             'fps': fps,
271             'width': width,
272             'height': height,
273         }
274
275         formats = []
276         for format_id, format_url in rendition['redirect'].items():
277             if format_id == 'rtmp':
278                 ff = f.copy()
279                 ff.update({
280                     'url': format_url,
281                     'format_id': format_id,
282                 })
283                 formats.append(ff)
284             elif determine_ext(format_url) == 'f4m':
285                 formats.extend(self._extract_f4m_formats(
286                     format_url, video_id, f4m_id=format_id))
287             elif determine_ext(format_url) == 'm3u8':
288                 formats.extend(self._extract_m3u8_formats(
289                     format_url, video_id, 'mp4', m3u8_id=format_id))
290             else:
291                 continue
292         self._sort_formats(formats)
293
294         title = remove_end(self._og_search_title(webpage), ' - iptv.ORF.at')
295         description = self._og_search_description(webpage)
296         upload_date = unified_strdate(self._html_search_meta(
297             'dc.date', webpage, 'upload date'))
298
299         return {
300             'id': video_id,
301             'title': title,
302             'description': description,
303             'duration': duration,
304             'thumbnail': thumbnail,
305             'upload_date': upload_date,
306             'formats': formats,
307         }