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