[cleanup] Misc (#8968)
[yt-dlp.git] / yt_dlp / extractor / rtve.py
bloba99a266c6083dd9d6e939887838f86dabf9b8feb
1 import base64
2 import io
3 import struct
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,
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+)'
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',
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,
43 'params': {
44 'skip_download': 'live stream',
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,
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,
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']
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
109 yield quality.decode(), url
110 encrypted_data.read(4) # CRC
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,
133 return formats
135 def _real_extract(self, url):
136 video_id = self._match_id(url)
137 info = self._download_json(
138 'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
139 video_id)['page']['items'][0]
140 if info['state'] == 'DESPU':
141 raise ExtractorError('The video is no longer available', expected=True)
142 title = info['title'].strip()
143 formats = self._extract_png_formats(video_id)
145 subtitles = None
146 sbt_file = info.get('sbtFile')
147 if sbt_file:
148 subtitles = self.extract_subtitles(video_id, sbt_file)
150 is_live = info.get('live') is True
152 return {
153 'id': video_id,
154 'title': title,
155 'formats': formats,
156 'thumbnail': info.get('image'),
157 'subtitles': subtitles,
158 'duration': float_or_none(info.get('duration'), 1000),
159 'is_live': is_live,
160 'series': info.get('programTitle'),
163 def _get_subtitles(self, video_id, sub_file):
164 subs = self._download_json(
165 sub_file + '.json', video_id,
166 'Downloading subtitles info')['page']['items']
167 return dict(
168 (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
169 for s in subs)
172 class RTVEAudioIE(RTVEALaCartaIE): # XXX: Do not subclass from concrete IE
173 IE_NAME = 'rtve.es:audio'
174 IE_DESC = 'RTVE audio'
175 _VALID_URL = r'https?://(?:www\.)?rtve\.es/(alacarta|play)/audios/[^/]+/[^/]+/(?P<id>[0-9]+)'
177 _TESTS = [{
178 'url': 'https://www.rtve.es/alacarta/audios/a-hombros-de-gigantes/palabra-ingeniero-codigos-informaticos-27-04-21/5889192/',
179 'md5': 'ae06d27bff945c4e87a50f89f6ce48ce',
180 'info_dict': {
181 'id': '5889192',
182 'ext': 'mp3',
183 'title': 'Códigos informáticos',
184 'thumbnail': r're:https?://.+/1598856591583.jpg',
185 'duration': 349.440,
186 'series': 'A hombros de gigantes',
188 }, {
189 'url': 'https://www.rtve.es/play/audios/en-radio-3/ignatius-farray/5791165/',
190 'md5': '072855ab89a9450e0ba314c717fa5ebc',
191 'info_dict': {
192 'id': '5791165',
193 'ext': 'mp3',
194 'title': 'Ignatius Farray',
195 'thumbnail': r're:https?://.+/1613243011863.jpg',
196 'duration': 3559.559,
197 'series': 'En Radio 3'
199 }, {
200 'url': 'https://www.rtve.es/play/audios/frankenstein-o-el-moderno-prometeo/capitulo-26-ultimo-muerte-victor-juan-jose-plans-mary-shelley/6082623/',
201 'md5': '0eadab248cc8dd193fa5765712e84d5c',
202 'info_dict': {
203 'id': '6082623',
204 'ext': 'mp3',
205 'title': 'Capítulo 26 y último: La muerte de Victor',
206 'thumbnail': r're:https?://.+/1632147445707.jpg',
207 'duration': 3174.086,
208 'series': 'Frankenstein o el moderno Prometeo'
212 def _extract_png_formats(self, audio_id):
214 This function retrieves media related png thumbnail which obfuscate
215 valuable information about the media. This information is decrypted
216 via base class _decrypt_url function providing media quality and
217 media url
219 png = self._download_webpage(
220 'http://www.rtve.es/ztnr/movil/thumbnail/%s/audios/%s.png' %
221 (self._manager, audio_id),
222 audio_id, 'Downloading url information', query={'q': 'v2'})
223 q = qualities(['Media', 'Alta', 'HQ', 'HD_READY', 'HD_FULL'])
224 formats = []
225 for quality, audio_url in self._decrypt_url(png):
226 ext = determine_ext(audio_url)
227 if ext == 'm3u8':
228 formats.extend(self._extract_m3u8_formats(
229 audio_url, audio_id, 'mp4', 'm3u8_native',
230 m3u8_id='hls', fatal=False))
231 elif ext == 'mpd':
232 formats.extend(self._extract_mpd_formats(
233 audio_url, audio_id, 'dash', fatal=False))
234 else:
235 formats.append({
236 'format_id': quality,
237 'quality': q(quality),
238 'url': audio_url,
240 return formats
242 def _real_extract(self, url):
243 audio_id = self._match_id(url)
244 info = self._download_json(
245 'https://www.rtve.es/api/audios/%s.json' % audio_id,
246 audio_id)['page']['items'][0]
248 return {
249 'id': audio_id,
250 'title': info['title'].strip(),
251 'thumbnail': info.get('thumbnail'),
252 'duration': float_or_none(info.get('duration'), 1000),
253 'series': try_get(info, lambda x: x['programInfo']['title']),
254 'formats': self._extract_png_formats(audio_id),
258 class RTVEInfantilIE(RTVEALaCartaIE): # XXX: Do not subclass from concrete IE
259 IE_NAME = 'rtve.es:infantil'
260 IE_DESC = 'RTVE infantil'
261 _VALID_URL = r'https?://(?:www\.)?rtve\.es/infantil/serie/[^/]+/video/[^/]+/(?P<id>[0-9]+)/'
263 _TESTS = [{
264 'url': 'http://www.rtve.es/infantil/serie/cleo/video/maneras-vivir/3040283/',
265 'md5': '5747454717aedf9f9fdf212d1bcfc48d',
266 'info_dict': {
267 'id': '3040283',
268 'ext': 'mp4',
269 'title': 'Maneras de vivir',
270 'thumbnail': r're:https?://.+/1426182947956\.JPG',
271 'duration': 357.958,
273 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
277 class RTVELiveIE(RTVEALaCartaIE): # XXX: Do not subclass from concrete IE
278 IE_NAME = 'rtve.es:live'
279 IE_DESC = 'RTVE.es live streams'
280 _VALID_URL = r'https?://(?:www\.)?rtve\.es/directo/(?P<id>[a-zA-Z0-9-]+)'
282 _TESTS = [{
283 'url': 'http://www.rtve.es/directo/la-1/',
284 'info_dict': {
285 'id': 'la-1',
286 'ext': 'mp4',
287 'title': 're:^La 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
289 'params': {
290 'skip_download': 'live stream',
294 def _real_extract(self, url):
295 mobj = self._match_valid_url(url)
296 video_id = mobj.group('id')
298 webpage = self._download_webpage(url, video_id)
299 title = remove_end(self._og_search_title(webpage), ' en directo en RTVE.es')
300 title = remove_start(title, 'Estoy viendo ')
302 vidplayer_id = self._search_regex(
303 (r'playerId=player([0-9]+)',
304 r'class=["\'].*?\blive_mod\b.*?["\'][^>]+data-assetid=["\'](\d+)',
305 r'data-id=["\'](\d+)'),
306 webpage, 'internal video ID')
308 return {
309 'id': video_id,
310 'title': title,
311 'formats': self._extract_png_formats(vidplayer_id),
312 'is_live': True,
316 class RTVETelevisionIE(InfoExtractor):
317 IE_NAME = 'rtve.es:television'
318 _VALID_URL = r'https?://(?:www\.)?rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
320 _TEST = {
321 'url': 'http://www.rtve.es/television/20160628/revolucion-del-movil/1364141.shtml',
322 'info_dict': {
323 'id': '3069778',
324 'ext': 'mp4',
325 'title': 'Documentos TV - La revolución del móvil',
326 'duration': 3496.948,
328 'params': {
329 'skip_download': True,
333 def _real_extract(self, url):
334 page_id = self._match_id(url)
335 webpage = self._download_webpage(url, page_id)
337 alacarta_url = self._search_regex(
338 r'data-location="alacarta_videos"[^<]+url&quot;:&quot;(http://www\.rtve\.es/alacarta.+?)&',
339 webpage, 'alacarta url', default=None)
340 if alacarta_url is None:
341 raise ExtractorError(
342 'The webpage doesn\'t contain any video', expected=True)
344 return self.url_result(alacarta_url, ie=RTVEALaCartaIE.ie_key())