Fix "invalid escape sequences" error on Python 3.6
[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             subtitles = {}
119             for sub in sd.get('subtitles', []):
120                 sub_src = sub.get('src')
121                 if not sub_src:
122                     continue
123                 subtitles.setdefault(sub.get('lang', 'de-AT'), []).append({
124                     'url': sub_src,
125                 })
126
127             upload_date = unified_strdate(sd.get('created_date'))
128             entries.append({
129                 '_type': 'video',
130                 'id': video_id,
131                 'title': title,
132                 'formats': formats,
133                 'subtitles': subtitles,
134                 'description': sd.get('description'),
135                 'duration': int_or_none(sd.get('duration_in_seconds')),
136                 'upload_date': upload_date,
137                 'thumbnail': sd.get('image_full_url'),
138             })
139
140         return {
141             '_type': 'playlist',
142             'entries': entries,
143             'id': playlist_id,
144         }
145
146
147 class ORFOE1IE(InfoExtractor):
148     IE_NAME = 'orf:oe1'
149     IE_DESC = 'Radio Österreich 1'
150     _VALID_URL = r'https?://oe1\.orf\.at/(?:programm/|konsole\?.*?\btrack_id=)(?P<id>[0-9]+)'
151
152     # Audios on ORF radio are only available for 7 days, so we can't add tests.
153     _TESTS = [{
154         'url': 'http://oe1.orf.at/konsole?show=on_demand#?track_id=394211',
155         'only_matching': True,
156     }, {
157         'url': 'http://oe1.orf.at/konsole?show=ondemand&track_id=443608&load_day=/programm/konsole/tag/20160726',
158         'only_matching': True,
159     }]
160
161     def _real_extract(self, url):
162         show_id = self._match_id(url)
163         data = self._download_json(
164             'http://oe1.orf.at/programm/%s/konsole' % show_id,
165             show_id
166         )
167
168         timestamp = datetime.datetime.strptime('%s %s' % (
169             data['item']['day_label'],
170             data['item']['time']
171         ), '%d.%m.%Y %H:%M')
172         unix_timestamp = calendar.timegm(timestamp.utctimetuple())
173
174         return {
175             'id': show_id,
176             'title': data['item']['title'],
177             'url': data['item']['url_stream'],
178             'ext': 'mp3',
179             'description': data['item'].get('info'),
180             'timestamp': unix_timestamp
181         }
182
183
184 class ORFFM4IE(InfoExtractor):
185     IE_NAME = 'orf:fm4'
186     IE_DESC = 'radio FM4'
187     _VALID_URL = r'https?://fm4\.orf\.at/(?:7tage/?#|player/)(?P<date>[0-9]+)/(?P<show>\w+)'
188
189     _TEST = {
190         'url': 'http://fm4.orf.at/player/20160110/IS/',
191         'md5': '01e736e8f1cef7e13246e880a59ad298',
192         'info_dict': {
193             'id': '2016-01-10_2100_tl_54_7DaysSun13_11244',
194             'ext': 'mp3',
195             'title': 'Im Sumpf',
196             'description': 'md5:384c543f866c4e422a55f66a62d669cd',
197             'duration': 7173,
198             'timestamp': 1452456073,
199             'upload_date': '20160110',
200         },
201         'skip': 'Live streams on FM4 got deleted soon',
202     }
203
204     def _real_extract(self, url):
205         mobj = re.match(self._VALID_URL, url)
206         show_date = mobj.group('date')
207         show_id = mobj.group('show')
208
209         data = self._download_json(
210             'http://audioapi.orf.at/fm4/json/2.0/broadcasts/%s/4%s' % (show_date, show_id),
211             show_id
212         )
213
214         def extract_entry_dict(info, title, subtitle):
215             return {
216                 'id': info['loopStreamId'].replace('.mp3', ''),
217                 'url': 'http://loopstream01.apa.at/?channel=fm4&id=%s' % info['loopStreamId'],
218                 'title': title,
219                 'description': subtitle,
220                 'duration': (info['end'] - info['start']) / 1000,
221                 'timestamp': info['start'] / 1000,
222                 'ext': 'mp3'
223             }
224
225         entries = [extract_entry_dict(t, data['title'], data['subtitle']) for t in data['streams']]
226
227         return {
228             '_type': 'playlist',
229             'id': show_id,
230             'title': data['title'],
231             'description': data['subtitle'],
232             'entries': entries
233         }
234
235
236 class ORFIPTVIE(InfoExtractor):
237     IE_NAME = 'orf:iptv'
238     IE_DESC = 'iptv.ORF.at'
239     _VALID_URL = r'https?://iptv\.orf\.at/(?:#/)?stories/(?P<id>\d+)'
240
241     _TEST = {
242         'url': 'http://iptv.orf.at/stories/2275236/',
243         'md5': 'c8b22af4718a4b4af58342529453e3e5',
244         'info_dict': {
245             'id': '350612',
246             'ext': 'flv',
247             'title': 'Weitere Evakuierungen um Vulkan Calbuco',
248             'description': 'md5:d689c959bdbcf04efeddedbf2299d633',
249             'duration': 68.197,
250             'thumbnail': r're:^https?://.*\.jpg$',
251             'upload_date': '20150425',
252         },
253     }
254
255     def _real_extract(self, url):
256         story_id = self._match_id(url)
257
258         webpage = self._download_webpage(
259             'http://iptv.orf.at/stories/%s' % story_id, story_id)
260
261         video_id = self._search_regex(
262             r'data-video(?:id)?="(\d+)"', webpage, 'video id')
263
264         data = self._download_json(
265             'http://bits.orf.at/filehandler/static-api/json/current/data.json?file=%s' % video_id,
266             video_id)[0]
267
268         duration = float_or_none(data['duration'], 1000)
269
270         video = data['sources']['default']
271         load_balancer_url = video['loadBalancerUrl']
272         abr = int_or_none(video.get('audioBitrate'))
273         vbr = int_or_none(video.get('bitrate'))
274         fps = int_or_none(video.get('videoFps'))
275         width = int_or_none(video.get('videoWidth'))
276         height = int_or_none(video.get('videoHeight'))
277         thumbnail = video.get('preview')
278
279         rendition = self._download_json(
280             load_balancer_url, video_id, transform_source=strip_jsonp)
281
282         f = {
283             'abr': abr,
284             'vbr': vbr,
285             'fps': fps,
286             'width': width,
287             'height': height,
288         }
289
290         formats = []
291         for format_id, format_url in rendition['redirect'].items():
292             if format_id == 'rtmp':
293                 ff = f.copy()
294                 ff.update({
295                     'url': format_url,
296                     'format_id': format_id,
297                 })
298                 formats.append(ff)
299             elif determine_ext(format_url) == 'f4m':
300                 formats.extend(self._extract_f4m_formats(
301                     format_url, video_id, f4m_id=format_id))
302             elif determine_ext(format_url) == 'm3u8':
303                 formats.extend(self._extract_m3u8_formats(
304                     format_url, video_id, 'mp4', m3u8_id=format_id))
305             else:
306                 continue
307         self._sort_formats(formats)
308
309         title = remove_end(self._og_search_title(webpage), ' - iptv.ORF.at')
310         description = self._og_search_description(webpage)
311         upload_date = unified_strdate(self._html_search_meta(
312             'dc.date', webpage, 'upload date'))
313
314         return {
315             'id': video_id,
316             'title': title,
317             'description': description,
318             'duration': duration,
319             'thumbnail': thumbnail,
320             'upload_date': upload_date,
321             'formats': formats,
322         }