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