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