]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/atresplayer.py
debian/patches: Drop patch included in version 2017.02.07.
[youtubedl] / youtube_dl / extractor / atresplayer.py
1 from __future__ import unicode_literals
2
3 import time
4 import hmac
5 import hashlib
6 import re
7
8 from .common import InfoExtractor
9 from ..compat import compat_str
10 from ..utils import (
11 ExtractorError,
12 float_or_none,
13 int_or_none,
14 sanitized_Request,
15 urlencode_postdata,
16 xpath_text,
17 )
18
19
20 class AtresPlayerIE(InfoExtractor):
21 _VALID_URL = r'https?://(?:www\.)?atresplayer\.com/television/[^/]+/[^/]+/[^/]+/(?P<id>.+?)_\d+\.html'
22 _NETRC_MACHINE = 'atresplayer'
23 _TESTS = [
24 {
25 'url': 'http://www.atresplayer.com/television/programas/el-club-de-la-comedia/temporada-4/capitulo-10-especial-solidario-nochebuena_2014122100174.html',
26 'md5': 'efd56753cda1bb64df52a3074f62e38a',
27 'info_dict': {
28 'id': 'capitulo-10-especial-solidario-nochebuena',
29 'ext': 'mp4',
30 'title': 'Especial Solidario de Nochebuena',
31 'description': 'md5:e2d52ff12214fa937107d21064075bf1',
32 'duration': 5527.6,
33 'thumbnail': r're:^https?://.*\.jpg$',
34 },
35 'skip': 'This video is only available for registered users'
36 },
37 {
38 'url': 'http://www.atresplayer.com/television/especial/videoencuentros/temporada-1/capitulo-112-david-bustamante_2014121600375.html',
39 'md5': '0d0e918533bbd4b263f2de4d197d4aac',
40 'info_dict': {
41 'id': 'capitulo-112-david-bustamante',
42 'ext': 'flv',
43 'title': 'David Bustamante',
44 'description': 'md5:f33f1c0a05be57f6708d4dd83a3b81c6',
45 'duration': 1439.0,
46 'thumbnail': r're:^https?://.*\.jpg$',
47 },
48 },
49 {
50 'url': 'http://www.atresplayer.com/television/series/el-secreto-de-puente-viejo/el-chico-de-los-tres-lunares/capitulo-977-29-12-14_2014122400174.html',
51 'only_matching': True,
52 },
53 ]
54
55 _USER_AGENT = 'Dalvik/1.6.0 (Linux; U; Android 4.3; GT-I9300 Build/JSS15J'
56 _MAGIC = 'QWtMLXs414Yo+c#_+Q#K@NN)'
57 _TIMESTAMP_SHIFT = 30000
58
59 _TIME_API_URL = 'http://servicios.atresplayer.com/api/admin/time.json'
60 _URL_VIDEO_TEMPLATE = 'https://servicios.atresplayer.com/api/urlVideo/{1}/{0}/{1}|{2}|{3}.json'
61 _PLAYER_URL_TEMPLATE = 'https://servicios.atresplayer.com/episode/getplayer.json?episodePk=%s'
62 _EPISODE_URL_TEMPLATE = 'http://www.atresplayer.com/episodexml/%s'
63
64 _LOGIN_URL = 'https://servicios.atresplayer.com/j_spring_security_check'
65
66 _ERRORS = {
67 'UNPUBLISHED': 'We\'re sorry, but this video is not yet available.',
68 'DELETED': 'This video has expired and is no longer available for online streaming.',
69 'GEOUNPUBLISHED': 'We\'re sorry, but this video is not available in your region due to right restrictions.',
70 # 'PREMIUM': 'PREMIUM',
71 }
72
73 def _real_initialize(self):
74 self._login()
75
76 def _login(self):
77 (username, password) = self._get_login_info()
78 if username is None:
79 return
80
81 login_form = {
82 'j_username': username,
83 'j_password': password,
84 }
85
86 request = sanitized_Request(
87 self._LOGIN_URL, urlencode_postdata(login_form))
88 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
89 response = self._download_webpage(
90 request, None, 'Logging in as %s' % username)
91
92 error = self._html_search_regex(
93 r'(?s)<ul class="list_error">(.+?)</ul>', response, 'error', default=None)
94 if error:
95 raise ExtractorError(
96 'Unable to login: %s' % error, expected=True)
97
98 def _real_extract(self, url):
99 video_id = self._match_id(url)
100
101 webpage = self._download_webpage(url, video_id)
102
103 episode_id = self._search_regex(
104 r'episode="([^"]+)"', webpage, 'episode id')
105
106 request = sanitized_Request(
107 self._PLAYER_URL_TEMPLATE % episode_id,
108 headers={'User-Agent': self._USER_AGENT})
109 player = self._download_json(request, episode_id, 'Downloading player JSON')
110
111 episode_type = player.get('typeOfEpisode')
112 error_message = self._ERRORS.get(episode_type)
113 if error_message:
114 raise ExtractorError(
115 '%s returned error: %s' % (self.IE_NAME, error_message), expected=True)
116
117 formats = []
118 video_url = player.get('urlVideo')
119 if video_url:
120 format_info = {
121 'url': video_url,
122 'format_id': 'http',
123 }
124 mobj = re.search(r'(?P<bitrate>\d+)K_(?P<width>\d+)x(?P<height>\d+)', video_url)
125 if mobj:
126 format_info.update({
127 'width': int_or_none(mobj.group('width')),
128 'height': int_or_none(mobj.group('height')),
129 'tbr': int_or_none(mobj.group('bitrate')),
130 })
131 formats.append(format_info)
132
133 timestamp = int_or_none(self._download_webpage(
134 self._TIME_API_URL,
135 video_id, 'Downloading timestamp', fatal=False), 1000, time.time())
136 timestamp_shifted = compat_str(timestamp + self._TIMESTAMP_SHIFT)
137 token = hmac.new(
138 self._MAGIC.encode('ascii'),
139 (episode_id + timestamp_shifted).encode('utf-8'), hashlib.md5
140 ).hexdigest()
141
142 request = sanitized_Request(
143 self._URL_VIDEO_TEMPLATE.format('windows', episode_id, timestamp_shifted, token),
144 headers={'User-Agent': self._USER_AGENT})
145
146 fmt_json = self._download_json(
147 request, video_id, 'Downloading windows video JSON')
148
149 result = fmt_json.get('resultDes')
150 if result.lower() != 'ok':
151 raise ExtractorError(
152 '%s returned error: %s' % (self.IE_NAME, result), expected=True)
153
154 for format_id, video_url in fmt_json['resultObject'].items():
155 if format_id == 'token' or not video_url.startswith('http'):
156 continue
157 if 'geodeswowsmpra3player' in video_url:
158 f4m_path = video_url.split('smil:', 1)[-1].split('free_', 1)[0]
159 f4m_url = 'http://drg.antena3.com/{0}hds/es/sd.f4m'.format(f4m_path)
160 # this videos are protected by DRM, the f4m downloader doesn't support them
161 continue
162 else:
163 f4m_url = video_url[:-9] + '/manifest.f4m'
164 formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
165 self._sort_formats(formats)
166
167 path_data = player.get('pathData')
168
169 episode = self._download_xml(
170 self._EPISODE_URL_TEMPLATE % path_data, video_id,
171 'Downloading episode XML')
172
173 duration = float_or_none(xpath_text(
174 episode, './media/asset/info/technical/contentDuration', 'duration'))
175
176 art = episode.find('./media/asset/info/art')
177 title = xpath_text(art, './name', 'title')
178 description = xpath_text(art, './description', 'description')
179 thumbnail = xpath_text(episode, './media/asset/files/background', 'thumbnail')
180
181 subtitles = {}
182 subtitle_url = xpath_text(episode, './media/asset/files/subtitle', 'subtitle')
183 if subtitle_url:
184 subtitles['es'] = [{
185 'ext': 'srt',
186 'url': subtitle_url,
187 }]
188
189 return {
190 'id': video_id,
191 'title': title,
192 'description': description,
193 'thumbnail': thumbnail,
194 'duration': duration,
195 'formats': formats,
196 'subtitles': subtitles,
197 }