]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/nexx.py
071879ba4f5317326ebed99ee59e8a6f4e6b4ce4
[youtubedl] / youtube_dl / extractor / nexx.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import hashlib
5 import random
6 import re
7 import time
8
9 from .common import InfoExtractor
10 from ..compat import compat_str
11 from ..utils import (
12 ExtractorError,
13 int_or_none,
14 parse_duration,
15 try_get,
16 urlencode_postdata,
17 )
18
19
20 class NexxIE(InfoExtractor):
21 _VALID_URL = r'''(?x)
22 (?:
23 https?://api\.nexx(?:\.cloud|cdn\.com)/v3/(?P<domain_id>\d+)/videos/byid/|
24 nexx:(?P<domain_id_s>\d+):
25 )
26 (?P<id>\d+)
27 '''
28 _TESTS = [{
29 # movie
30 'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
31 'md5': '16746bfc28c42049492385c989b26c4a',
32 'info_dict': {
33 'id': '128907',
34 'ext': 'mp4',
35 'title': 'Stiftung Warentest',
36 'alt_title': 'Wie ein Test abläuft',
37 'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
38 'release_year': 2013,
39 'creator': 'SPIEGEL TV',
40 'thumbnail': r're:^https?://.*\.jpg$',
41 'duration': 2509,
42 'timestamp': 1384264416,
43 'upload_date': '20131112',
44 },
45 'params': {
46 'format': 'bestvideo',
47 },
48 }, {
49 # episode
50 'url': 'https://api.nexx.cloud/v3/741/videos/byid/247858',
51 'info_dict': {
52 'id': '247858',
53 'ext': 'mp4',
54 'title': 'Return of the Golden Child (OV)',
55 'description': 'md5:5d969537509a92b733de21bae249dc63',
56 'release_year': 2017,
57 'thumbnail': r're:^https?://.*\.jpg$',
58 'duration': 1397,
59 'timestamp': 1495033267,
60 'upload_date': '20170517',
61 'episode_number': 2,
62 'season_number': 2,
63 },
64 'params': {
65 'format': 'bestvideo',
66 'skip_download': True,
67 },
68 }, {
69 'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
70 'only_matching': True,
71 }, {
72 'url': 'nexx:748:128907',
73 'only_matching': True,
74 }]
75
76 @staticmethod
77 def _extract_domain_id(webpage):
78 mobj = re.search(
79 r'<script\b[^>]+\bsrc=["\'](?:https?:)?//require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
80 webpage)
81 return mobj.group('id') if mobj else None
82
83 @staticmethod
84 def _extract_urls(webpage):
85 # Reference:
86 # 1. https://nx-s.akamaized.net/files/201510/44.pdf
87
88 entries = []
89
90 # JavaScript Integration
91 domain_id = NexxIE._extract_domain_id(webpage)
92 if domain_id:
93 for video_id in re.findall(
94 r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
95 webpage):
96 entries.append(
97 'https://api.nexx.cloud/v3/%s/videos/byid/%s'
98 % (domain_id, video_id))
99
100 # TODO: support more embed formats
101
102 return entries
103
104 @staticmethod
105 def _extract_url(webpage):
106 return NexxIE._extract_urls(webpage)[0]
107
108 def _handle_error(self, response):
109 status = int_or_none(try_get(
110 response, lambda x: x['metadata']['status']) or 200)
111 if 200 <= status < 300:
112 return
113 raise ExtractorError(
114 '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
115 expected=True)
116
117 def _call_api(self, domain_id, path, video_id, data=None, headers={}):
118 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
119 result = self._download_json(
120 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
121 'Downloading %s JSON' % path, data=urlencode_postdata(data),
122 headers=headers)
123 self._handle_error(result)
124 return result['result']
125
126 def _real_extract(self, url):
127 mobj = re.match(self._VALID_URL, url)
128 domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
129 video_id = mobj.group('id')
130
131 # Reverse engineered from JS code (see getDeviceID function)
132 device_id = '%d:%d:%d%d' % (
133 random.randint(1, 4), int(time.time()),
134 random.randint(1e4, 99999), random.randint(1, 9))
135
136 result = self._call_api(domain_id, 'session/init', video_id, data={
137 'nxp_devh': device_id,
138 'nxp_userh': '',
139 'precid': '0',
140 'playlicense': '0',
141 'screenx': '1920',
142 'screeny': '1080',
143 'playerversion': '6.0.00',
144 'gateway': 'html5',
145 'adGateway': '',
146 'explicitlanguage': 'en-US',
147 'addTextTemplates': '1',
148 'addDomainData': '1',
149 'addAdModel': '1',
150 }, headers={
151 'X-Request-Enable-Auth-Fallback': '1',
152 })
153
154 cid = result['general']['cid']
155
156 # As described in [1] X-Request-Token generation algorithm is
157 # as follows:
158 # md5( operation + domain_id + domain_secret )
159 # where domain_secret is a static value that will be given by nexx.tv
160 # as per [1]. Here is how this "secret" is generated (reversed
161 # from _play.api.init function, search for clienttoken). So it's
162 # actually not static and not that much of a secret.
163 # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
164 secret = result['device']['clienttoken'][int(device_id[0]):]
165 secret = secret[0:len(secret) - int(device_id[-1])]
166
167 op = 'byid'
168
169 # Reversed from JS code for _play.api.call function (search for
170 # X-Request-Token)
171 request_token = hashlib.md5(
172 ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
173
174 video = self._call_api(
175 domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
176 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
177 'addInteractionOptions': '1',
178 'addStatusDetails': '1',
179 'addStreamDetails': '1',
180 'addCaptions': '1',
181 'addScenes': '1',
182 'addHotSpots': '1',
183 'addBumpers': '1',
184 'captionFormat': 'data',
185 }, headers={
186 'X-Request-CID': cid,
187 'X-Request-Token': request_token,
188 })
189
190 general = video['general']
191 title = general['title']
192
193 stream_data = video['streamdata']
194 language = general.get('language_raw') or ''
195
196 # TODO: reverse more cdns and formats
197
198 cdn = stream_data['cdnType']
199 assert cdn == 'azure'
200
201 azure_locator = stream_data['azureLocator']
202
203 AZURE_URL = 'http://nx-p%02d.akamaized.net/'
204
205 for secure in ('s', ''):
206 cdn_shield = stream_data.get('cdnShieldHTTP%s' % secure.upper())
207 if cdn_shield:
208 azure_base = 'http%s://%s' % (secure, cdn_shield)
209 break
210 else:
211 azure_base = AZURE_URL % int(stream_data['azureAccount'].replace('nexxplayplus', ''))
212
213 is_ml = ',' in language
214 azure_m3u8_url = '%s%s/%s_src%s.ism/Manifest(format=m3u8-aapl)' % (
215 azure_base, azure_locator, video_id, ('_manifest' if is_ml else ''))
216
217 protection_token = try_get(
218 video, lambda x: x['protectiondata']['token'], compat_str)
219 if protection_token:
220 azure_m3u8_url += '?hdnts=%s' % protection_token
221
222 formats = self._extract_m3u8_formats(
223 azure_m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native',
224 m3u8_id='%s-hls' % cdn)
225 self._sort_formats(formats)
226
227 return {
228 'id': video_id,
229 'title': title,
230 'alt_title': general.get('subtitle'),
231 'description': general.get('description'),
232 'release_year': int_or_none(general.get('year')),
233 'creator': general.get('studio') or general.get('studio_adref'),
234 'thumbnail': try_get(
235 video, lambda x: x['imagedata']['thumb'], compat_str),
236 'duration': parse_duration(general.get('runtime')),
237 'timestamp': int_or_none(general.get('uploaded')),
238 'episode_number': int_or_none(try_get(
239 video, lambda x: x['episodedata']['episode'])),
240 'season_number': int_or_none(try_get(
241 video, lambda x: x['episodedata']['season'])),
242 'formats': formats,
243 }
244
245
246 class NexxEmbedIE(InfoExtractor):
247 _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
248 _TEST = {
249 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
250 'md5': '16746bfc28c42049492385c989b26c4a',
251 'info_dict': {
252 'id': '161464',
253 'ext': 'mp4',
254 'title': 'Nervenkitzel Achterbahn',
255 'alt_title': 'Karussellbauer in Deutschland',
256 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
257 'release_year': 2005,
258 'creator': 'SPIEGEL TV',
259 'thumbnail': r're:^https?://.*\.jpg$',
260 'duration': 2761,
261 'timestamp': 1394021479,
262 'upload_date': '20140305',
263 },
264 'params': {
265 'format': 'bestvideo',
266 'skip_download': True,
267 },
268 }
269
270 @staticmethod
271 def _extract_urls(webpage):
272 # Reference:
273 # 1. https://nx-s.akamaized.net/files/201510/44.pdf
274
275 # iFrame Embed Integration
276 return [mobj.group('url') for mobj in re.finditer(
277 r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
278 webpage)]
279
280 def _real_extract(self, url):
281 embed_id = self._match_id(url)
282
283 webpage = self._download_webpage(url, embed_id)
284
285 return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())