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