]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/rtve.py
[compat] Remove more functions
[yt-dlp.git] / yt_dlp / extractor / rtve.py
1 import base64
2 import io
3 import struct
4
5 from .common import InfoExtractor
6 from ..compat import compat_b64decode
7 from ..utils import (
8 ExtractorError,
9 determine_ext,
10 float_or_none,
11 qualities,
12 remove_end,
13 remove_start,
14 try_get,
15 )
16
17
18 class RTVEALaCartaIE(InfoExtractor):
19 IE_NAME = 'rtve.es:alacarta'
20 IE_DESC = 'RTVE a la carta'
21 _VALID_URL = r'https?://(?:www\.)?rtve\.es/(m/)?(alacarta/videos|filmoteca)/[^/]+/[^/]+/(?P<id>\d+)'
22
23 _TESTS = [{
24 'url': 'http://www.rtve.es/alacarta/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
25 'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
26 'info_dict': {
27 'id': '2491869',
28 'ext': 'mp4',
29 'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
30 'duration': 5024.566,
31 'series': 'Balonmano',
32 },
33 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
34 }, {
35 'note': 'Live stream',
36 'url': 'http://www.rtve.es/alacarta/videos/television/24h-live/1694255/',
37 'info_dict': {
38 'id': '1694255',
39 'ext': 'mp4',
40 'title': 're:^24H LIVE [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
41 'is_live': True,
42 },
43 'params': {
44 'skip_download': 'live stream',
45 },
46 }, {
47 'url': 'http://www.rtve.es/alacarta/videos/servir-y-proteger/servir-proteger-capitulo-104/4236788/',
48 'md5': 'd850f3c8731ea53952ebab489cf81cbf',
49 'info_dict': {
50 'id': '4236788',
51 'ext': 'mp4',
52 'title': 'Servir y proteger - Capítulo 104',
53 'duration': 3222.0,
54 },
55 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
56 }, {
57 'url': 'http://www.rtve.es/m/alacarta/videos/cuentame-como-paso/cuentame-como-paso-t16-ultimo-minuto-nuestra-vida-capitulo-276/2969138/?media=tve',
58 'only_matching': True,
59 }, {
60 'url': 'http://www.rtve.es/filmoteca/no-do/not-1-introduccion-primer-noticiario-espanol/1465256/',
61 'only_matching': True,
62 }]
63
64 def _real_initialize(self):
65 user_agent_b64 = base64.b64encode(self.get_param('http_headers')['User-Agent'].encode('utf-8')).decode('utf-8')
66 self._manager = self._download_json(
67 'http://www.rtve.es/odin/loki/' + user_agent_b64,
68 None, 'Fetching manager info')['manager']
69
70 @staticmethod
71 def _decrypt_url(png):
72 encrypted_data = io.BytesIO(compat_b64decode(png)[8:])
73 while True:
74 length = struct.unpack('!I', encrypted_data.read(4))[0]
75 chunk_type = encrypted_data.read(4)
76 if chunk_type == b'IEND':
77 break
78 data = encrypted_data.read(length)
79 if chunk_type == b'tEXt':
80 alphabet_data, text = data.split(b'\0')
81 quality, url_data = text.split(b'%%')
82 alphabet = []
83 e = 0
84 d = 0
85 for l in alphabet_data.decode('iso-8859-1'):
86 if d == 0:
87 alphabet.append(l)
88 d = e = (e + 1) % 4
89 else:
90 d -= 1
91 url = ''
92 f = 0
93 e = 3
94 b = 1
95 for letter in url_data.decode('iso-8859-1'):
96 if f == 0:
97 l = int(letter) * 10
98 f = 1
99 else:
100 if e == 0:
101 l += int(letter)
102 url += alphabet[l]
103 e = (b + 3) % 4
104 f = 0
105 b += 1
106 else:
107 e -= 1
108
109 yield quality.decode(), url
110 encrypted_data.read(4) # CRC
111
112 def _extract_png_formats(self, video_id):
113 png = self._download_webpage(
114 'http://www.rtve.es/ztnr/movil/thumbnail/%s/videos/%s.png' % (self._manager, video_id),
115 video_id, 'Downloading url information', query={'q': 'v2'})
116 q = qualities(['Media', 'Alta', 'HQ', 'HD_READY', 'HD_FULL'])
117 formats = []
118 for quality, video_url in self._decrypt_url(png):
119 ext = determine_ext(video_url)
120 if ext == 'm3u8':
121 formats.extend(self._extract_m3u8_formats(
122 video_url, video_id, 'mp4', 'm3u8_native',
123 m3u8_id='hls', fatal=False))
124 elif ext == 'mpd':
125 formats.extend(self._extract_mpd_formats(
126 video_url, video_id, 'dash', fatal=False))
127 else:
128 formats.append({
129 'format_id': quality,
130 'quality': q(quality),
131 'url': video_url,
132 })
133 self._sort_formats(formats)
134 return formats
135
136 def _real_extract(self, url):
137 video_id = self._match_id(url)
138 info = self._download_json(
139 'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
140 video_id)['page']['items'][0]
141 if info['state'] == 'DESPU':
142 raise ExtractorError('The video is no longer available', expected=True)
143 title = info['title'].strip()
144 formats = self._extract_png_formats(video_id)
145
146 subtitles = None
147 sbt_file = info.get('sbtFile')
148 if sbt_file:
149 subtitles = self.extract_subtitles(video_id, sbt_file)
150
151 is_live = info.get('live') is True
152
153 return {
154 'id': video_id,
155 'title': title,
156 'formats': formats,
157 'thumbnail': info.get('image'),
158 'subtitles': subtitles,
159 'duration': float_or_none(info.get('duration'), 1000),
160 'is_live': is_live,
161 'series': info.get('programTitle'),
162 }
163
164 def _get_subtitles(self, video_id, sub_file):
165 subs = self._download_json(
166 sub_file + '.json', video_id,
167 'Downloading subtitles info')['page']['items']
168 return dict(
169 (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
170 for s in subs)
171
172
173 class RTVEAudioIE(RTVEALaCartaIE):
174 IE_NAME = 'rtve.es:audio'
175 IE_DESC = 'RTVE audio'
176 _VALID_URL = r'https?://(?:www\.)?rtve\.es/(alacarta|play)/audios/[^/]+/[^/]+/(?P<id>[0-9]+)'
177
178 _TESTS = [{
179 'url': 'https://www.rtve.es/alacarta/audios/a-hombros-de-gigantes/palabra-ingeniero-codigos-informaticos-27-04-21/5889192/',
180 'md5': 'ae06d27bff945c4e87a50f89f6ce48ce',
181 'info_dict': {
182 'id': '5889192',
183 'ext': 'mp3',
184 'title': 'Códigos informáticos',
185 'thumbnail': r're:https?://.+/1598856591583.jpg',
186 'duration': 349.440,
187 'series': 'A hombros de gigantes',
188 },
189 }, {
190 'url': 'https://www.rtve.es/play/audios/en-radio-3/ignatius-farray/5791165/',
191 'md5': '072855ab89a9450e0ba314c717fa5ebc',
192 'info_dict': {
193 'id': '5791165',
194 'ext': 'mp3',
195 'title': 'Ignatius Farray',
196 'thumbnail': r're:https?://.+/1613243011863.jpg',
197 'duration': 3559.559,
198 'series': 'En Radio 3'
199 },
200 }, {
201 'url': 'https://www.rtve.es/play/audios/frankenstein-o-el-moderno-prometeo/capitulo-26-ultimo-muerte-victor-juan-jose-plans-mary-shelley/6082623/',
202 'md5': '0eadab248cc8dd193fa5765712e84d5c',
203 'info_dict': {
204 'id': '6082623',
205 'ext': 'mp3',
206 'title': 'Capítulo 26 y último: La muerte de Victor',
207 'thumbnail': r're:https?://.+/1632147445707.jpg',
208 'duration': 3174.086,
209 'series': 'Frankenstein o el moderno Prometeo'
210 },
211 }]
212
213 def _extract_png_formats(self, audio_id):
214 """
215 This function retrieves media related png thumbnail which obfuscate
216 valuable information about the media. This information is decrypted
217 via base class _decrypt_url function providing media quality and
218 media url
219 """
220 png = self._download_webpage(
221 'http://www.rtve.es/ztnr/movil/thumbnail/%s/audios/%s.png' %
222 (self._manager, audio_id),
223 audio_id, 'Downloading url information', query={'q': 'v2'})
224 q = qualities(['Media', 'Alta', 'HQ', 'HD_READY', 'HD_FULL'])
225 formats = []
226 for quality, audio_url in self._decrypt_url(png):
227 ext = determine_ext(audio_url)
228 if ext == 'm3u8':
229 formats.extend(self._extract_m3u8_formats(
230 audio_url, audio_id, 'mp4', 'm3u8_native',
231 m3u8_id='hls', fatal=False))
232 elif ext == 'mpd':
233 formats.extend(self._extract_mpd_formats(
234 audio_url, audio_id, 'dash', fatal=False))
235 else:
236 formats.append({
237 'format_id': quality,
238 'quality': q(quality),
239 'url': audio_url,
240 })
241 self._sort_formats(formats)
242 return formats
243
244 def _real_extract(self, url):
245 audio_id = self._match_id(url)
246 info = self._download_json(
247 'https://www.rtve.es/api/audios/%s.json' % audio_id,
248 audio_id)['page']['items'][0]
249
250 return {
251 'id': audio_id,
252 'title': info['title'].strip(),
253 'thumbnail': info.get('thumbnail'),
254 'duration': float_or_none(info.get('duration'), 1000),
255 'series': try_get(info, lambda x: x['programInfo']['title']),
256 'formats': self._extract_png_formats(audio_id),
257 }
258
259
260 class RTVEInfantilIE(RTVEALaCartaIE):
261 IE_NAME = 'rtve.es:infantil'
262 IE_DESC = 'RTVE infantil'
263 _VALID_URL = r'https?://(?:www\.)?rtve\.es/infantil/serie/[^/]+/video/[^/]+/(?P<id>[0-9]+)/'
264
265 _TESTS = [{
266 'url': 'http://www.rtve.es/infantil/serie/cleo/video/maneras-vivir/3040283/',
267 'md5': '5747454717aedf9f9fdf212d1bcfc48d',
268 'info_dict': {
269 'id': '3040283',
270 'ext': 'mp4',
271 'title': 'Maneras de vivir',
272 'thumbnail': r're:https?://.+/1426182947956\.JPG',
273 'duration': 357.958,
274 },
275 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
276 }]
277
278
279 class RTVELiveIE(RTVEALaCartaIE):
280 IE_NAME = 'rtve.es:live'
281 IE_DESC = 'RTVE.es live streams'
282 _VALID_URL = r'https?://(?:www\.)?rtve\.es/directo/(?P<id>[a-zA-Z0-9-]+)'
283
284 _TESTS = [{
285 'url': 'http://www.rtve.es/directo/la-1/',
286 'info_dict': {
287 'id': 'la-1',
288 'ext': 'mp4',
289 'title': 're:^La 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
290 },
291 'params': {
292 'skip_download': 'live stream',
293 }
294 }]
295
296 def _real_extract(self, url):
297 mobj = self._match_valid_url(url)
298 video_id = mobj.group('id')
299
300 webpage = self._download_webpage(url, video_id)
301 title = remove_end(self._og_search_title(webpage), ' en directo en RTVE.es')
302 title = remove_start(title, 'Estoy viendo ')
303
304 vidplayer_id = self._search_regex(
305 (r'playerId=player([0-9]+)',
306 r'class=["\'].*?\blive_mod\b.*?["\'][^>]+data-assetid=["\'](\d+)',
307 r'data-id=["\'](\d+)'),
308 webpage, 'internal video ID')
309
310 return {
311 'id': video_id,
312 'title': title,
313 'formats': self._extract_png_formats(vidplayer_id),
314 'is_live': True,
315 }
316
317
318 class RTVETelevisionIE(InfoExtractor):
319 IE_NAME = 'rtve.es:television'
320 _VALID_URL = r'https?://(?:www\.)?rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
321
322 _TEST = {
323 'url': 'http://www.rtve.es/television/20160628/revolucion-del-movil/1364141.shtml',
324 'info_dict': {
325 'id': '3069778',
326 'ext': 'mp4',
327 'title': 'Documentos TV - La revolución del móvil',
328 'duration': 3496.948,
329 },
330 'params': {
331 'skip_download': True,
332 },
333 }
334
335 def _real_extract(self, url):
336 page_id = self._match_id(url)
337 webpage = self._download_webpage(url, page_id)
338
339 alacarta_url = self._search_regex(
340 r'data-location="alacarta_videos"[^<]+url&quot;:&quot;(http://www\.rtve\.es/alacarta.+?)&',
341 webpage, 'alacarta url', default=None)
342 if alacarta_url is None:
343 raise ExtractorError(
344 'The webpage doesn\'t contain any video', expected=True)
345
346 return self.url_result(alacarta_url, ie=RTVEALaCartaIE.ie_key())