[rtve] Extract a better quality video
[youtube-dl] / youtube_dl / extractor / rtve.py
1 # encoding: 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 compat_urlparse
10 from ..utils import (
11     float_or_none,
12     remove_end,
13     std_headers,
14     struct_unpack,
15 )
16
17
18 def _decrypt_url(png):
19     encrypted_data = base64.b64decode(png)
20     text_index = encrypted_data.find(b'tEXt')
21     text_chunk = encrypted_data[text_index - 4:]
22     length = struct_unpack('!I', text_chunk[:4])[0]
23     # Use bytearray to get integers when iterating in both python 2.x and 3.x
24     data = bytearray(text_chunk[8:8 + length])
25     data = [chr(b) for b in data if b != 0]
26     hash_index = data.index('#')
27     alphabet_data = data[:hash_index]
28     url_data = data[hash_index + 1:]
29
30     alphabet = []
31     e = 0
32     d = 0
33     for l in alphabet_data:
34         if d == 0:
35             alphabet.append(l)
36             d = e = (e + 1) % 4
37         else:
38             d -= 1
39     url = ''
40     f = 0
41     e = 3
42     b = 1
43     for letter in url_data:
44         if f == 0:
45             l = int(letter) * 10
46             f = 1
47         else:
48             if e == 0:
49                 l += int(letter)
50                 url += alphabet[l]
51                 e = (b + 3) % 4
52                 f = 0
53                 b += 1
54             else:
55                 e -= 1
56
57     return url
58
59
60 class RTVEALaCartaIE(InfoExtractor):
61     IE_NAME = 'rtve.es:alacarta'
62     IE_DESC = 'RTVE a la carta'
63     _VALID_URL = r'http://www\.rtve\.es/(m/)?alacarta/videos/[^/]+/[^/]+/(?P<id>\d+)'
64
65     _TESTS = [{
66         'url': 'http://www.rtve.es/alacarta/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
67         'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
68         'info_dict': {
69             'id': '2491869',
70             'ext': 'mp4',
71             'title': 'Balonmano - Swiss Cup masculina. Final: EspaƱa-Suecia',
72             'duration': 5024.566,
73         },
74     }, {
75         'note': 'Live stream',
76         'url': 'http://www.rtve.es/alacarta/videos/television/24h-live/1694255/',
77         'info_dict': {
78             'id': '1694255',
79             'ext': 'flv',
80             'title': 'TODO',
81         },
82         'skip': 'The f4m manifest can\'t be used yet',
83     }, {
84         'url': 'http://www.rtve.es/m/alacarta/videos/cuentame-como-paso/cuentame-como-paso-t16-ultimo-minuto-nuestra-vida-capitulo-276/2969138/?media=tve',
85         'only_matching': True,
86     }]
87
88     def _real_initialize(self):
89         user_agent_b64 = base64.b64encode(std_headers['User-Agent'].encode('utf-8')).decode('utf-8')
90         manager_info = self._download_json(
91             'http://www.rtve.es/odin/loki/' + user_agent_b64,
92             None, 'Fetching manager info')
93         self._manager = manager_info['manager']
94
95     def _real_extract(self, url):
96         mobj = re.match(self._VALID_URL, url)
97         video_id = mobj.group('id')
98         info = self._download_json(
99             'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
100             video_id)['page']['items'][0]
101         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/%s/videos/%s.png' % (self._manager, video_id)
102         png = self._download_webpage(png_url, video_id, 'Downloading url information')
103         video_url = _decrypt_url(png)
104         if not video_url.endswith('.f4m'):
105             auth_url = video_url.replace(
106                 'resources/', 'auth/resources/'
107             ).replace('.net.rtve', '.multimedia.cdn.rtve')
108             video_path = self._download_webpage(
109                 auth_url, video_id, 'Getting video url')
110             # Use mvod1.akcdn instead of flash.akamaihd.multimedia.cdn to get
111             # the right Content-Length header and the mp4 format
112             video_url = compat_urlparse.urljoin(
113                 'http://mvod1.akcdn.rtve.es/', video_path)
114
115         subtitles = None
116         if info.get('sbtFile') is not None:
117             subtitles = self.extract_subtitles(video_id, info['sbtFile'])
118
119         return {
120             'id': video_id,
121             'title': info['title'],
122             'url': video_url,
123             'thumbnail': info.get('image'),
124             'page_url': url,
125             'subtitles': subtitles,
126             'duration': float_or_none(info.get('duration'), scale=1000),
127         }
128
129     def _get_subtitles(self, video_id, sub_file):
130         subs = self._download_json(
131             sub_file + '.json', video_id,
132             'Downloading subtitles info')['page']['items']
133         return dict(
134             (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
135             for s in subs)
136
137
138 class RTVEInfantilIE(InfoExtractor):
139     IE_NAME = 'rtve.es:infantil'
140     IE_DESC = 'RTVE infantil'
141     _VALID_URL = r'https?://(?:www\.)?rtve\.es/infantil/serie/(?P<show>[^/]*)/video/(?P<short_title>[^/]*)/(?P<id>[0-9]+)/'
142
143     _TESTS = [{
144         'url': 'http://www.rtve.es/infantil/serie/cleo/video/maneras-vivir/3040283/',
145         'md5': '915319587b33720b8e0357caaa6617e6',
146         'info_dict': {
147             'id': '3040283',
148             'ext': 'mp4',
149             'title': 'Maneras de vivir',
150             'thumbnail': 'http://www.rtve.es/resources/jpg/6/5/1426182947956.JPG',
151             'duration': 357.958,
152         },
153     }]
154
155     def _real_extract(self, url):
156         video_id = self._match_id(url)
157         info = self._download_json(
158             'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
159             video_id)['page']['items'][0]
160
161         webpage = self._download_webpage(url, video_id)
162         vidplayer_id = self._search_regex(
163             r' id="vidplayer([0-9]+)"', webpage, 'internal video ID')
164
165         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/default/videos/%s.png' % vidplayer_id
166         png = self._download_webpage(png_url, video_id, 'Downloading url information')
167         video_url = _decrypt_url(png)
168
169         return {
170             'id': video_id,
171             'ext': 'mp4',
172             'title': info['title'],
173             'url': video_url,
174             'thumbnail': info.get('image'),
175             'duration': float_or_none(info.get('duration'), scale=1000),
176         }
177
178
179 class RTVELiveIE(InfoExtractor):
180     IE_NAME = 'rtve.es:live'
181     IE_DESC = 'RTVE.es live streams'
182     _VALID_URL = r'http://www\.rtve\.es/(?:deportes/directo|noticias|television)/(?P<id>[a-zA-Z0-9-]+)'
183
184     _TESTS = [{
185         'url': 'http://www.rtve.es/noticias/directo-la-1/',
186         'info_dict': {
187             'id': 'directo-la-1',
188             'ext': 'flv',
189             'title': 're:^La 1 de TVE [0-9]{4}-[0-9]{2}-[0-9]{2}Z[0-9]{6}$',
190         },
191         'params': {
192             'skip_download': 'live stream',
193         }
194     }]
195
196     def _real_extract(self, url):
197         mobj = re.match(self._VALID_URL, url)
198         start_time = time.gmtime()
199         video_id = mobj.group('id')
200
201         webpage = self._download_webpage(url, video_id)
202         player_url = self._search_regex(
203             r'<param name="movie" value="([^"]+)"/>', webpage, 'player URL')
204         title = remove_end(self._og_search_title(webpage), ' en directo')
205         title += ' ' + time.strftime('%Y-%m-%dZ%H%M%S', start_time)
206
207         vidplayer_id = self._search_regex(
208             r' id="vidplayer([0-9]+)"', webpage, 'internal video ID')
209         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/default/videos/%s.png' % vidplayer_id
210         png = self._download_webpage(png_url, video_id, 'Downloading url information')
211         video_url = _decrypt_url(png)
212
213         return {
214             'id': video_id,
215             'ext': 'flv',
216             'title': title,
217             'url': video_url,
218             'app': 'rtve-live-live?ovpfv=2.1.2',
219             'player_url': player_url,
220             'rtmp_live': True,
221         }