]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/rtve.py
Completely change project name to yt-dlp (#85)
[yt-dlp.git] / yt_dlp / extractor / rtve.py
CommitLineData
dcdb292f 1# coding: utf-8
91a6adde
JMF
2from __future__ import unicode_literals
3
91a6adde 4import base64
2b9faf55
PH
5import re
6import time
91a6adde
JMF
7
8from .common import InfoExtractor
dab0daee 9from ..compat import (
cf282071 10 compat_b64decode,
edaa23f8 11 compat_struct_unpack,
dab0daee 12)
91a6adde 13from ..utils import (
2c53bd51 14 determine_ext,
ce73839f 15 ExtractorError,
f3bff94c 16 float_or_none,
2b9faf55 17 remove_end,
3e769682 18 remove_start,
5c2266df 19 sanitized_Request,
e9f65f87 20 std_headers,
91a6adde
JMF
21)
22
23
2b9faf55 24def _decrypt_url(png):
cf282071 25 encrypted_data = compat_b64decode(png)
2b9faf55
PH
26 text_index = encrypted_data.find(b'tEXt')
27 text_chunk = encrypted_data[text_index - 4:]
edaa23f8 28 length = compat_struct_unpack('!I', text_chunk[:4])[0]
2b9faf55
PH
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:]
9650c3e9
JMF
35 if url_data[0] == 'H' and url_data[3] == '%':
36 # remove useless HQ%% at the start
37 url_data = url_data[4:]
2b9faf55
PH
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
91a6adde
JMF
69class RTVEALaCartaIE(InfoExtractor):
70 IE_NAME = 'rtve.es:alacarta'
71 IE_DESC = 'RTVE a la carta'
92519402 72 _VALID_URL = r'https?://(?:www\.)?rtve\.es/(m/)?(alacarta/videos|filmoteca)/[^/]+/[^/]+/(?P<id>\d+)'
91a6adde 73
2b9faf55 74 _TESTS = [{
91a6adde 75 'url': 'http://www.rtve.es/alacarta/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
9aeaf730 76 'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
91a6adde
JMF
77 'info_dict': {
78 'id': '2491869',
79 'ext': 'mp4',
80 'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
f3bff94c 81 'duration': 5024.566,
91a6adde 82 },
2b9faf55
PH
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',
cc57bd33
JMF
90 },
91 'skip': 'The f4m manifest can\'t be used yet',
2c53bd51
GF
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 },
cd596028
JMF
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,
4c718d3c
JMF
107 }, {
108 'url': 'http://www.rtve.es/filmoteca/no-do/not-1-introduccion-primer-noticiario-espanol/1465256/',
109 'only_matching': True,
2b9faf55 110 }]
91a6adde 111
e9f65f87
JMF
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
91a6adde
JMF
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]
ce73839f
JMF
125 if info['state'] == 'DESPU':
126 raise ExtractorError('The video is no longer available', expected=True)
2c53bd51 127 title = info['title']
e9f65f87 128 png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/%s/videos/%s.png' % (self._manager, video_id)
5c2266df 129 png_request = sanitized_Request(png_url)
080997b8
JMF
130 png_request.add_header('Referer', url)
131 png = self._download_webpage(png_request, video_id, 'Downloading url information')
2b9faf55 132 video_url = _decrypt_url(png)
2c53bd51
GF
133 ext = determine_ext(video_url)
134
135 formats = []
136 if not video_url.endswith('.f4m') and ext != 'm3u8':
da0baba5
JMF
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')
91a6adde 140
2c53bd51
GF
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
25ac63ed
JMF
154 subtitles = None
155 if info.get('sbtFile') is not None:
156 subtitles = self.extract_subtitles(video_id, info['sbtFile'])
157
91a6adde
JMF
158 return {
159 'id': video_id,
2c53bd51
GF
160 'title': title,
161 'formats': formats,
2b9faf55
PH
162 'thumbnail': info.get('image'),
163 'page_url': url,
25ac63ed 164 'subtitles': subtitles,
f3bff94c 165 'duration': float_or_none(info.get('duration'), scale=1000),
2b9faf55
PH
166 }
167
25ac63ed
JMF
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']
9c665ab7
PH
172 return dict(
173 (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
25ac63ed
JMF
174 for s in subs)
175
b68eedba 176
d5b55939 177class RTVEInfantilIE(InfoExtractor):
b68eedba
JMF
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]+)/'
d5b55939
EF
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 },
b68eedba 192 }]
d5b55939
EF
193
194 def _real_extract(self, url):
b68eedba 195 video_id = self._match_id(url)
d5b55939
EF
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
2b9faf55
PH
218class RTVELiveIE(InfoExtractor):
219 IE_NAME = 'rtve.es:live'
220 IE_DESC = 'RTVE.es live streams'
92519402 221 _VALID_URL = r'https?://(?:www\.)?rtve\.es/directo/(?P<id>[a-zA-Z0-9-]+)'
2b9faf55
PH
222
223 _TESTS = [{
3e769682 224 'url': 'http://www.rtve.es/directo/la-1/',
2b9faf55 225 'info_dict': {
3e769682
JMF
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}$',
2b9faf55
PH
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)
3e769682
JMF
241 title = remove_end(self._og_search_title(webpage), ' en directo en RTVE.es')
242 title = remove_start(title, 'Estoy viendo ')
2b9faf55
PH
243 title += ' ' + time.strftime('%Y-%m-%dZ%H%M%S', start_time)
244
245 vidplayer_id = self._search_regex(
b63005f5
S
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')
3e769682 250 png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/amonet/videos/%s.png' % vidplayer_id
2b9faf55 251 png = self._download_webpage(png_url, video_id, 'Downloading url information')
3e769682
JMF
252 m3u8_url = _decrypt_url(png)
253 formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4')
19dbaeec 254 self._sort_formats(formats)
2b9faf55 255
2b9faf55
PH
256 return {
257 'id': video_id,
2b9faf55 258 'title': title,
3e769682
JMF
259 'formats': formats,
260 'is_live': True,
91a6adde 261 }
233b58de
JMF
262
263
264class RTVETelevisionIE(InfoExtractor):
265 IE_NAME = 'rtve.es:television'
92519402 266 _VALID_URL = r'https?://(?:www\.)?rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
233b58de
JMF
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())