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