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