Add extractor for rtve.es/television (fixes #10076)
[youtube-dl] / youtube_dl / extractor / rtve.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import re
6 import time
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_struct_unpack,
11 )
12 from ..utils import (
13     ExtractorError,
14     float_or_none,
15     remove_end,
16     remove_start,
17     sanitized_Request,
18     std_headers,
19 )
20
21
22 def _decrypt_url(png):
23     encrypted_data = base64.b64decode(png.encode('utf-8'))
24     text_index = encrypted_data.find(b'tEXt')
25     text_chunk = encrypted_data[text_index - 4:]
26     length = compat_struct_unpack('!I', text_chunk[:4])[0]
27     # Use bytearray to get integers when iterating in both python 2.x and 3.x
28     data = bytearray(text_chunk[8:8 + length])
29     data = [chr(b) for b in data if b != 0]
30     hash_index = data.index('#')
31     alphabet_data = data[:hash_index]
32     url_data = data[hash_index + 1:]
33
34     alphabet = []
35     e = 0
36     d = 0
37     for l in alphabet_data:
38         if d == 0:
39             alphabet.append(l)
40             d = e = (e + 1) % 4
41         else:
42             d -= 1
43     url = ''
44     f = 0
45     e = 3
46     b = 1
47     for letter in url_data:
48         if f == 0:
49             l = int(letter) * 10
50             f = 1
51         else:
52             if e == 0:
53                 l += int(letter)
54                 url += alphabet[l]
55                 e = (b + 3) % 4
56                 f = 0
57                 b += 1
58             else:
59                 e -= 1
60
61     return url
62
63
64 class RTVEALaCartaIE(InfoExtractor):
65     IE_NAME = 'rtve.es:alacarta'
66     IE_DESC = 'RTVE a la carta'
67     _VALID_URL = r'https?://www\.rtve\.es/(m/)?(alacarta/videos|filmoteca)/[^/]+/[^/]+/(?P<id>\d+)'
68
69     _TESTS = [{
70         'url': 'http://www.rtve.es/alacarta/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
71         'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
72         'info_dict': {
73             'id': '2491869',
74             'ext': 'mp4',
75             'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
76             'duration': 5024.566,
77         },
78     }, {
79         'note': 'Live stream',
80         'url': 'http://www.rtve.es/alacarta/videos/television/24h-live/1694255/',
81         'info_dict': {
82             'id': '1694255',
83             'ext': 'flv',
84             'title': 'TODO',
85         },
86         'skip': 'The f4m manifest can\'t be used yet',
87     }, {
88         'url': 'http://www.rtve.es/m/alacarta/videos/cuentame-como-paso/cuentame-como-paso-t16-ultimo-minuto-nuestra-vida-capitulo-276/2969138/?media=tve',
89         'only_matching': True,
90     }, {
91         'url': 'http://www.rtve.es/filmoteca/no-do/not-1-introduccion-primer-noticiario-espanol/1465256/',
92         'only_matching': True,
93     }]
94
95     def _real_initialize(self):
96         user_agent_b64 = base64.b64encode(std_headers['User-Agent'].encode('utf-8')).decode('utf-8')
97         manager_info = self._download_json(
98             'http://www.rtve.es/odin/loki/' + user_agent_b64,
99             None, 'Fetching manager info')
100         self._manager = manager_info['manager']
101
102     def _real_extract(self, url):
103         mobj = re.match(self._VALID_URL, url)
104         video_id = mobj.group('id')
105         info = self._download_json(
106             'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
107             video_id)['page']['items'][0]
108         if info['state'] == 'DESPU':
109             raise ExtractorError('The video is no longer available', expected=True)
110         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/%s/videos/%s.png' % (self._manager, video_id)
111         png_request = sanitized_Request(png_url)
112         png_request.add_header('Referer', url)
113         png = self._download_webpage(png_request, video_id, 'Downloading url information')
114         video_url = _decrypt_url(png)
115         if not video_url.endswith('.f4m'):
116             video_url = video_url.replace('.net.rtve', '.multimedia.cdn.rtve')
117
118         subtitles = None
119         if info.get('sbtFile') is not None:
120             subtitles = self.extract_subtitles(video_id, info['sbtFile'])
121
122         return {
123             'id': video_id,
124             'title': info['title'],
125             'url': video_url,
126             'thumbnail': info.get('image'),
127             'page_url': url,
128             'subtitles': subtitles,
129             'duration': float_or_none(info.get('duration'), scale=1000),
130         }
131
132     def _get_subtitles(self, video_id, sub_file):
133         subs = self._download_json(
134             sub_file + '.json', video_id,
135             'Downloading subtitles info')['page']['items']
136         return dict(
137             (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
138             for s in subs)
139
140
141 class RTVEInfantilIE(InfoExtractor):
142     IE_NAME = 'rtve.es:infantil'
143     IE_DESC = 'RTVE infantil'
144     _VALID_URL = r'https?://(?:www\.)?rtve\.es/infantil/serie/(?P<show>[^/]*)/video/(?P<short_title>[^/]*)/(?P<id>[0-9]+)/'
145
146     _TESTS = [{
147         'url': 'http://www.rtve.es/infantil/serie/cleo/video/maneras-vivir/3040283/',
148         'md5': '915319587b33720b8e0357caaa6617e6',
149         'info_dict': {
150             'id': '3040283',
151             'ext': 'mp4',
152             'title': 'Maneras de vivir',
153             'thumbnail': 'http://www.rtve.es/resources/jpg/6/5/1426182947956.JPG',
154             'duration': 357.958,
155         },
156     }]
157
158     def _real_extract(self, url):
159         video_id = self._match_id(url)
160         info = self._download_json(
161             'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
162             video_id)['page']['items'][0]
163
164         webpage = self._download_webpage(url, video_id)
165         vidplayer_id = self._search_regex(
166             r' id="vidplayer([0-9]+)"', webpage, 'internal video ID')
167
168         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/default/videos/%s.png' % vidplayer_id
169         png = self._download_webpage(png_url, video_id, 'Downloading url information')
170         video_url = _decrypt_url(png)
171
172         return {
173             'id': video_id,
174             'ext': 'mp4',
175             'title': info['title'],
176             'url': video_url,
177             'thumbnail': info.get('image'),
178             'duration': float_or_none(info.get('duration'), scale=1000),
179         }
180
181
182 class RTVELiveIE(InfoExtractor):
183     IE_NAME = 'rtve.es:live'
184     IE_DESC = 'RTVE.es live streams'
185     _VALID_URL = r'https?://www\.rtve\.es/directo/(?P<id>[a-zA-Z0-9-]+)'
186
187     _TESTS = [{
188         'url': 'http://www.rtve.es/directo/la-1/',
189         'info_dict': {
190             'id': 'la-1',
191             'ext': 'mp4',
192             'title': 're:^La 1 [0-9]{4}-[0-9]{2}-[0-9]{2}Z[0-9]{6}$',
193         },
194         'params': {
195             'skip_download': 'live stream',
196         }
197     }]
198
199     def _real_extract(self, url):
200         mobj = re.match(self._VALID_URL, url)
201         start_time = time.gmtime()
202         video_id = mobj.group('id')
203
204         webpage = self._download_webpage(url, video_id)
205         title = remove_end(self._og_search_title(webpage), ' en directo en RTVE.es')
206         title = remove_start(title, 'Estoy viendo ')
207         title += ' ' + time.strftime('%Y-%m-%dZ%H%M%S', start_time)
208
209         vidplayer_id = self._search_regex(
210             r'playerId=player([0-9]+)', webpage, 'internal video ID')
211         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/amonet/videos/%s.png' % vidplayer_id
212         png = self._download_webpage(png_url, video_id, 'Downloading url information')
213         m3u8_url = _decrypt_url(png)
214         formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4')
215         self._sort_formats(formats)
216
217         return {
218             'id': video_id,
219             'title': title,
220             'formats': formats,
221             'is_live': True,
222         }
223
224
225 class RTVETelevisionIE(InfoExtractor):
226     IE_NAME = 'rtve.es:television'
227     _VALID_URL = r'https?://www\.rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
228
229     _TEST = {
230         'url': 'http://www.rtve.es/television/20160628/revolucion-del-movil/1364141.shtml',
231         'info_dict': {
232             'id': '3069778',
233             'ext': 'mp4',
234             'title': 'Documentos TV - La revolución del móvil',
235             'duration': 3496.948,
236         },
237         'params': {
238             'skip_download': True,
239         },
240     }
241
242     def _real_extract(self, url):
243         page_id = self._match_id(url)
244         webpage = self._download_webpage(url, page_id)
245
246         alacarta_url = self._search_regex(
247             r'data-location="alacarta_videos"[^<]+url&quot;:&quot;(http://www\.rtve\.es/alacarta.+?)&',
248             webpage, 'alacarta url', default=None)
249         if alacarta_url is None:
250             raise ExtractorError(
251                 'The webpage doesn\'t contain any video', expected=True)
252
253         return self.url_result(alacarta_url, ie=RTVEALaCartaIE.ie_key())