[srgssr] Add generic extractor for SRGSSR Group sites
[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 ..utils import (
8     ExtractorError,
9     parse_iso8601,
10     qualities,
11 )
12
13
14 class SRGSSRIE(InfoExtractor):
15     _VALID_URL = r'(?:https?://tp\.srgssr\.ch/p(?:/[^/]+)+\?urn=)?urn:(?P<bu>srf|rts|rsi|rtr|swi):(?:[^:]+:)?(?P<type>video|audio):(?P<id>[0-9a-f\-]{36}|\d+)'
16
17     _ERRORS = {
18         'AGERATING12': 'To protect children under the age of 12, this video is only available between 8 p.m. and 6 a.m.',
19         'AGERATING18': 'To protect children under the age of 18, this video is only available between 11 p.m. and 5 a.m.',
20 #        'ENDDATE': 'For legal reasons, this video was only available for a specified period of time.',
21         'GEOBLOCK': 'For legal reasons, this video is only available in Switzerland.',
22         'LEGAL': 'The video cannot be transmitted for legal reasons.',
23         'STARTDATE': 'This video is not yet available. Please try again later.',
24     }
25
26     def _real_extract(self, url):
27         bu, media_type, media_id = re.match(self._VALID_URL, url).groups()
28
29         media_data = self._download_json(
30             'http://il.srgssr.ch/integrationlayer/1.0/ue/%s/%s/play/%s.json' % (bu, media_type, media_id),
31             media_id)[media_type.capitalize()]
32
33         if media_data.get('block') and media_data['block'] in self._ERRORS:
34             raise ExtractorError(
35                     '%s said: %s' % (
36                         self.IE_NAME,
37                         self._ERRORS[media_data['block']]),
38                     expected=True)
39
40         metadata = media_data['AssetMetadatas']['AssetMetadata'][0]
41         title = metadata['title']
42         description = metadata.get('description')
43         created_date = media_data.get('createdDate') or metadata.get('createdDate')
44         timestamp = parse_iso8601(created_date)
45
46         thumbnails = []
47         for image in media_data['Image']['ImageRepresentations']['ImageRepresentation']:
48             thumbnails.append({
49                 'id': image.get('id'),
50                 'url': image['url'],
51             })
52
53         preference = qualities(['LQ', 'MQ', 'SD', 'HQ', 'HD'])
54         formats = []
55         for source in media_data['Playlists']['Playlist']:
56             assets = {}
57             protocol = source.get('@protocol')
58             if protocol in ('HTTP-HDS', 'HTTP-HLS'):
59                 for quality in source['url']:
60                     assets[quality['@quality']] = quality['text']
61                 asset_url = assets.get('HD') or assets.get('HQ') or assets.get('SD') or assets.get('MQ') or assets.get('LQ')
62                 if '.f4m' in asset_url:
63                     formats.extend(self._extract_f4m_formats(asset_url + '?hdcore=3.4.0', media_id, f4m_id='hds'))
64                 elif '.m3u8' in asset_url:
65                     formats.extend(self._extract_m3u8_formats(asset_url, media_id, m3u8_id='hls'))
66             else:
67                 for asset in source['url']:
68                     asset_url = asset['text']
69                     ext = None
70                     if asset_url.startswith('rtmp'):
71                         ext = self._search_regex(r'([a-z0-9]+):[^/]+', asset_url, 'ext')
72                     formats.append({
73                         'url': asset_url,
74                         'preference': preference(asset['@quality']),
75                         'ext': ext,
76                     })
77
78         downloads = media_data.get('Downloads')
79         if downloads:
80             for source in downloads['Download']:
81                 for asset in source['url']:
82                     formats.append({
83                         'url': asset['text'],
84                         'preference': preference(asset['@quality'])
85                     })
86         self._sort_formats(formats)
87
88         return {
89             'id': media_id,
90             'title': title,
91             'description': description,
92             'timestamp': timestamp,
93             'thumbnails': thumbnails,
94             'formats': formats,
95         }
96
97
98 class SRGSSRPlayIE(InfoExtractor):
99     _VALID_URL = r'https?://(?:(?:www|play)\.)?(?P<bu>srf|rts|rsi|rtr|swi)\.ch/play/(?:tv|radio)/[^/]+/(?P<type>video|audio)/[^?]+\?id=(?P<id>[0-9a-f\-]{36}|\d+)'
100
101     _TESTS = [{
102         'url': 'http://www.srf.ch/play/tv/10vor10/video/snowden-beantragt-asyl-in-russland?id=28e1a57d-5b76-4399-8ab3-9097f071e6c5',
103         'md5': '4cd93523723beff51bb4bee974ee238d',
104         'info_dict': {
105             'id': '28e1a57d-5b76-4399-8ab3-9097f071e6c5',
106             'ext': 'm4v',
107             'upload_date': '20130701',
108             'title': 'Snowden beantragt Asyl in Russland',
109             'timestamp': 1372713995,
110         }
111     }, {
112         # No Speichern (Save) button
113         'url': 'http://www.srf.ch/play/tv/top-gear/video/jaguar-xk120-shadow-und-tornado-dampflokomotive?id=677f5829-e473-4823-ac83-a1087fe97faa',
114         'md5': '0a274ce38fda48c53c01890651985bc6',
115         'info_dict': {
116             'id': '677f5829-e473-4823-ac83-a1087fe97faa',
117             'ext': 'flv',
118             'upload_date': '20130710',
119             'title': 'Jaguar XK120, Shadow und Tornado-Dampflokomotive',
120             'description': 'md5:88604432b60d5a38787f152dec89cd56',
121             'timestamp': 1373493600,
122         },
123     }, {
124         'url': 'http://www.srf.ch/player/tv/10vor10/video/snowden-beantragt-asyl-in-russland?id=28e1a57d-5b76-4399-8ab3-9097f071e6c5',
125         'only_matching': True,
126     }]
127
128     def _real_extract(self, url):
129         bu, media_type, media_id = re.match(self._VALID_URL, url).groups()
130         return self.url_result('urn:%s:%s:%s' % (bu, media_type, media_id), 'SRGSSR')