[srgssr] handle all play urls only in SRGSSRIE and keep RTSIE for articles
[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|srgssr):(?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 get_media_data(self, bu, media_type, media_id):
27         media_data = self._download_json(
28             'http://il.srgssr.ch/integrationlayer/1.0/ue/%s/%s/play/%s.json' % (bu, media_type, media_id),
29             media_id)[media_type.capitalize()]
30
31         if media_data.get('block') and media_data['block'] in self._ERRORS:
32             raise ExtractorError('%s said: %s' % (self.IE_NAME, self._ERRORS[media_data['block']]), expected=True)
33
34         return media_data
35
36     def _real_extract(self, url):
37         bu, media_type, media_id = re.match(self._VALID_URL, url).groups()
38
39         if bu == 'rts':
40             return self.url_result('rts:%s' % media_id, 'RTS')
41
42         media_data = self.get_media_data(bu, media_type, media_id)
43
44         metadata = media_data['AssetMetadatas']['AssetMetadata'][0]
45         title = metadata['title']
46         description = metadata.get('description')
47         created_date = media_data.get('createdDate') or metadata.get('createdDate')
48         timestamp = parse_iso8601(created_date)
49
50         thumbnails = []
51         if 'Image' in media_data:
52             for image in media_data['Image']['ImageRepresentations']['ImageRepresentation']:
53                 thumbnails.append({
54                     'id': image.get('id'),
55                     'url': image['url'],
56                 })
57
58         preference = qualities(['LQ', 'MQ', 'SD', 'HQ', 'HD'])
59         formats = []
60         for source in media_data['Playlists']['Playlist']:
61             assets = {}
62             protocol = source.get('@protocol')
63             if protocol in ('HTTP-HDS', 'HTTP-HLS'):
64                 for quality in source['url']:
65                     assets[quality['@quality']] = quality['text']
66                 asset_url = assets.get('HD') or assets.get('HQ') or assets.get('SD') or assets.get('MQ') or assets.get('LQ')
67                 if '.f4m' in asset_url:
68                     f4m_formats = formats.extend(self._extract_f4m_formats(asset_url + '?hdcore=3.4.0', media_id, f4m_id='hds', fatal=False))
69                     if f4m_formats:
70                         formats.extend(f4m_formats)
71                 elif '.m3u8' in asset_url:
72                     m3u8_formats = formats.extend(self._extract_m3u8_formats(asset_url, media_id, m3u8_id='hls', fatal=False))
73                     if m3u8_formats:
74                         formats.extend(m3u8_formats)
75             else:
76                 for asset in source['url']:
77                     asset_url = asset['text']
78                     ext = None
79                     if asset_url.startswith('rtmp'):
80                         ext = self._search_regex(r'([a-z0-9]+):[^/]+', asset_url, 'ext')
81                     formats.append({
82                         'format_id': asset['@quality'],
83                         'url': asset_url,
84                         'preference': preference(asset['@quality']),
85                         'ext': ext,
86                     })
87
88         if 'Downloads' in media_data:
89             for source in media_data['Downloads']['Download']:
90                 for asset in source['url']:
91                     formats.append({
92                         'format_id': asset['@quality'],
93                         'url': asset['text'],
94                         'preference': preference(asset['@quality'])
95                     })
96         self._sort_formats(formats)
97
98         return {
99             'id': media_id,
100             'title': title,
101             'description': description,
102             'timestamp': timestamp,
103             'thumbnails': thumbnails,
104             'formats': formats,
105         }
106
107
108 class SRGSSRPlayIE(InfoExtractor):
109     _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+)'
110
111     _TESTS = [{
112         'url': 'http://www.srf.ch/play/tv/10vor10/video/snowden-beantragt-asyl-in-russland?id=28e1a57d-5b76-4399-8ab3-9097f071e6c5',
113         'md5': '4cd93523723beff51bb4bee974ee238d',
114         'info_dict': {
115             'id': '28e1a57d-5b76-4399-8ab3-9097f071e6c5',
116             'ext': 'm4v',
117             'upload_date': '20130701',
118             'title': 'Snowden beantragt Asyl in Russland',
119             'timestamp': 1372713995,
120         }
121     }, {
122         # No Speichern (Save) button
123         'url': 'http://www.srf.ch/play/tv/top-gear/video/jaguar-xk120-shadow-und-tornado-dampflokomotive?id=677f5829-e473-4823-ac83-a1087fe97faa',
124         'md5': '0a274ce38fda48c53c01890651985bc6',
125         'info_dict': {
126             'id': '677f5829-e473-4823-ac83-a1087fe97faa',
127             'ext': 'flv',
128             'upload_date': '20130710',
129             'title': 'Jaguar XK120, Shadow und Tornado-Dampflokomotive',
130             'description': 'md5:88604432b60d5a38787f152dec89cd56',
131             'timestamp': 1373493600,
132         },
133     }, {
134         'url': 'http://www.rtr.ch/play/radio/actualitad/audio/saira-tujetsch-tuttina-cuntinuar-cun-sedrun-muster-turissem?id=63cb0778-27f8-49af-9284-8c7a8c6d15fc',
135         'info_dict': {
136             'id': '63cb0778-27f8-49af-9284-8c7a8c6d15fc',
137             'ext': 'mp3',
138             'upload_date': '20151013',
139             'title': 'Saira: Tujetsch - tuttina cuntinuar cun Sedrun Mustér Turissem',
140             'timestamp': 1444750398,
141         },
142         'params': {
143             # rtmp download
144             'skip_download': True,
145         },
146     }, {
147         'url': 'http://www.rts.ch/play/tv/-/video/le-19h30?id=6348260',
148         'md5': '67a2a9ae4e8e62a68d0e9820cc9782df',
149         'info_dict': {
150             'id': '6348260',
151             'display_id': '6348260',
152             'ext': 'flv',
153             'duration': 1796,
154             'title': 'Le 19h30',
155             'description': '',
156             'uploader': '19h30',
157             'upload_date': '20141201',
158             'timestamp': 1417458600,
159             'thumbnail': 're:^https?://.*\.image',
160             'view_count': int,
161         },
162     }]
163
164     def _real_extract(self, url):
165         bu, media_type, media_id = re.match(self._VALID_URL, url).groups()
166         # other info can be extracted from url + '&layout=json'
167         return self.url_result('srgssr:%s:%s:%s' % (bu[:3], media_type, media_id), 'SRGSSR')