Fix "invalid escape sequences" error on Python 3.6
[youtube-dl] / youtube_dl / extractor / srgssr.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_urllib_parse_urlparse
8 from ..utils import (
9     ExtractorError,
10     parse_iso8601,
11     qualities,
12 )
13
14
15 class SRGSSRIE(InfoExtractor):
16     _VALID_URL = r'(?:https?://tp\.srgssr\.ch/p(?:/[^/]+)+\?urn=urn|srgssr):(?P<bu>srf|rts|rsi|rtr|swi):(?:[^:]+:)?(?P<type>video|audio):(?P<id>[0-9a-f\-]{36}|\d+)'
17
18     _ERRORS = {
19         'AGERATING12': 'To protect children under the age of 12, this video is only available between 8 p.m. and 6 a.m.',
20         'AGERATING18': 'To protect children under the age of 18, this video is only available between 11 p.m. and 5 a.m.',
21         # 'ENDDATE': 'For legal reasons, this video was only available for a specified period of time.',
22         'GEOBLOCK': 'For legal reasons, this video is only available in Switzerland.',
23         'LEGAL': 'The video cannot be transmitted for legal reasons.',
24         'STARTDATE': 'This video is not yet available. Please try again later.',
25     }
26
27     def _get_tokenized_src(self, url, video_id, format_id):
28         sp = compat_urllib_parse_urlparse(url).path.split('/')
29         token = self._download_json(
30             'http://tp.srgssr.ch/akahd/token?acl=/%s/%s/*' % (sp[1], sp[2]),
31             video_id, 'Downloading %s token' % format_id, fatal=False) or {}
32         auth_params = token.get('token', {}).get('authparams')
33         if auth_params:
34             url += '?' + auth_params
35         return url
36
37     def get_media_data(self, bu, media_type, media_id):
38         media_data = self._download_json(
39             'http://il.srgssr.ch/integrationlayer/1.0/ue/%s/%s/play/%s.json' % (bu, media_type, media_id),
40             media_id)[media_type.capitalize()]
41
42         if media_data.get('block') and media_data['block'] in self._ERRORS:
43             raise ExtractorError('%s said: %s' % (
44                 self.IE_NAME, self._ERRORS[media_data['block']]), expected=True)
45
46         return media_data
47
48     def _real_extract(self, url):
49         bu, media_type, media_id = re.match(self._VALID_URL, url).groups()
50
51         if bu == 'rts':
52             return self.url_result('rts:%s' % media_id, 'RTS')
53
54         media_data = self.get_media_data(bu, media_type, media_id)
55
56         metadata = media_data['AssetMetadatas']['AssetMetadata'][0]
57         title = metadata['title']
58         description = metadata.get('description')
59         created_date = media_data.get('createdDate') or metadata.get('createdDate')
60         timestamp = parse_iso8601(created_date)
61
62         thumbnails = [{
63             'id': image.get('id'),
64             'url': image['url'],
65         } for image in media_data.get('Image', {}).get('ImageRepresentations', {}).get('ImageRepresentation', [])]
66
67         preference = qualities(['LQ', 'MQ', 'SD', 'HQ', 'HD'])
68         formats = []
69         for source in media_data.get('Playlists', {}).get('Playlist', []) + media_data.get('Downloads', {}).get('Download', []):
70             protocol = source.get('@protocol')
71             for asset in source['url']:
72                 asset_url = asset['text']
73                 quality = asset['@quality']
74                 format_id = '%s-%s' % (protocol, quality)
75                 if protocol.startswith('HTTP-HDS') or protocol.startswith('HTTP-HLS'):
76                     asset_url = self._get_tokenized_src(asset_url, media_id, format_id)
77                     if protocol.startswith('HTTP-HDS'):
78                         formats.extend(self._extract_f4m_formats(
79                             asset_url + ('?' if '?' not in asset_url else '&') + 'hdcore=3.4.0',
80                             media_id, f4m_id=format_id, fatal=False))
81                     elif protocol.startswith('HTTP-HLS'):
82                         formats.extend(self._extract_m3u8_formats(
83                             asset_url, media_id, 'mp4', 'm3u8_native',
84                             m3u8_id=format_id, fatal=False))
85                 else:
86                     formats.append({
87                         'format_id': format_id,
88                         'url': asset_url,
89                         'preference': preference(quality),
90                         'ext': 'flv' if protocol == 'RTMP' else None,
91                     })
92         self._sort_formats(formats)
93
94         return {
95             'id': media_id,
96             'title': title,
97             'description': description,
98             'timestamp': timestamp,
99             'thumbnails': thumbnails,
100             'formats': formats,
101         }
102
103
104 class SRGSSRPlayIE(InfoExtractor):
105     IE_DESC = 'srf.ch, rts.ch, rsi.ch, rtr.ch and swissinfo.ch play sites'
106     _VALID_URL = r'https?://(?:(?:www|play)\.)?(?P<bu>srf|rts|rsi|rtr|swissinfo)\.ch/play/(?:tv|radio)/[^/]+/(?P<type>video|audio)/[^?]+\?id=(?P<id>[0-9a-f\-]{36}|\d+)'
107
108     _TESTS = [{
109         'url': 'http://www.srf.ch/play/tv/10vor10/video/snowden-beantragt-asyl-in-russland?id=28e1a57d-5b76-4399-8ab3-9097f071e6c5',
110         'md5': 'da6b5b3ac9fa4761a942331cef20fcb3',
111         'info_dict': {
112             'id': '28e1a57d-5b76-4399-8ab3-9097f071e6c5',
113             'ext': 'mp4',
114             'upload_date': '20130701',
115             'title': 'Snowden beantragt Asyl in Russland',
116             'timestamp': 1372713995,
117         }
118     }, {
119         # No Speichern (Save) button
120         'url': 'http://www.srf.ch/play/tv/top-gear/video/jaguar-xk120-shadow-und-tornado-dampflokomotive?id=677f5829-e473-4823-ac83-a1087fe97faa',
121         'md5': '0a274ce38fda48c53c01890651985bc6',
122         'info_dict': {
123             'id': '677f5829-e473-4823-ac83-a1087fe97faa',
124             'ext': 'flv',
125             'upload_date': '20130710',
126             'title': 'Jaguar XK120, Shadow und Tornado-Dampflokomotive',
127             'description': 'md5:88604432b60d5a38787f152dec89cd56',
128             'timestamp': 1373493600,
129         },
130     }, {
131         'url': 'http://www.rtr.ch/play/radio/actualitad/audio/saira-tujetsch-tuttina-cuntinuar-cun-sedrun-muster-turissem?id=63cb0778-27f8-49af-9284-8c7a8c6d15fc',
132         'info_dict': {
133             'id': '63cb0778-27f8-49af-9284-8c7a8c6d15fc',
134             'ext': 'mp3',
135             'upload_date': '20151013',
136             'title': 'Saira: Tujetsch - tuttina cuntinuar cun Sedrun Mustér Turissem',
137             'timestamp': 1444750398,
138         },
139         'params': {
140             # rtmp download
141             'skip_download': True,
142         },
143     }, {
144         'url': 'http://www.rts.ch/play/tv/-/video/le-19h30?id=6348260',
145         'md5': '67a2a9ae4e8e62a68d0e9820cc9782df',
146         'info_dict': {
147             'id': '6348260',
148             'display_id': '6348260',
149             'ext': 'mp4',
150             'duration': 1796,
151             'title': 'Le 19h30',
152             'description': '',
153             'uploader': '19h30',
154             'upload_date': '20141201',
155             'timestamp': 1417458600,
156             'thumbnail': r're:^https?://.*\.image',
157             'view_count': int,
158         },
159         'params': {
160             # m3u8 download
161             'skip_download': True,
162         }
163     }]
164
165     def _real_extract(self, url):
166         bu, media_type, media_id = re.match(self._VALID_URL, url).groups()
167         # other info can be extracted from url + '&layout=json'
168         return self.url_result('srgssr:%s:%s:%s' % (bu[:3], media_type, media_id), 'SRGSSR')