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