[nexx] Add support for free cdn (closes #16538)
[youtube-dl] / 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                             https?://arc\.nexx\.cloud/api/video/
26                         )
27                         (?P<id>\d+)
28                     '''
29     _TESTS = [{
30         # movie
31         'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
32         'md5': '828cea195be04e66057b846288295ba1',
33         'info_dict': {
34             'id': '128907',
35             'ext': 'mp4',
36             'title': 'Stiftung Warentest',
37             'alt_title': 'Wie ein Test abläuft',
38             'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
39             'release_year': 2013,
40             'creator': 'SPIEGEL TV',
41             'thumbnail': r're:^https?://.*\.jpg$',
42             'duration': 2509,
43             'timestamp': 1384264416,
44             'upload_date': '20131112',
45         },
46     }, {
47         # episode
48         'url': 'https://api.nexx.cloud/v3/741/videos/byid/247858',
49         'info_dict': {
50             'id': '247858',
51             'ext': 'mp4',
52             'title': 'Return of the Golden Child (OV)',
53             'description': 'md5:5d969537509a92b733de21bae249dc63',
54             'release_year': 2017,
55             'thumbnail': r're:^https?://.*\.jpg$',
56             'duration': 1397,
57             'timestamp': 1495033267,
58             'upload_date': '20170517',
59             'episode_number': 2,
60             'season_number': 2,
61         },
62         'params': {
63             'skip_download': True,
64         },
65     }, {
66         # does not work via arc
67         'url': 'nexx:741:1269984',
68         'md5': 'c714b5b238b2958dc8d5642addba6886',
69         'info_dict': {
70             'id': '1269984',
71             'ext': 'mp4',
72             'title': '1 TAG ohne KLO... wortwörtlich! 😑',
73             'alt_title': '1 TAG ohne KLO... wortwörtlich! 😑',
74             'description': 'md5:4604539793c49eda9443ab5c5b1d612f',
75             'thumbnail': r're:^https?://.*\.jpg$',
76             'duration': 607,
77             'timestamp': 1518614955,
78             'upload_date': '20180214',
79         },
80     }, {
81         # free cdn from http://www.spiegel.de/video/eifel-zoo-aufregung-um-ausgebrochene-raubtiere-video-99018031.html
82         'url': 'nexx:747:1533779',
83         'md5': '6bf6883912b82b7069fb86c2297e9893',
84         'info_dict': {
85             'id': '1533779',
86             'ext': 'mp4',
87             'title': 'Aufregung um ausgebrochene Raubtiere',
88             'alt_title': 'Eifel-Zoo',
89             'description': 'md5:f21375c91c74ad741dcb164c427999d2',
90             'thumbnail': r're:^https?://.*\.jpg$',
91             'duration': 111,
92             'timestamp': 1527874460,
93             'upload_date': '20180601',
94         },
95     }, {
96         'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
97         'only_matching': True,
98     }, {
99         'url': 'nexx:748:128907',
100         'only_matching': True,
101     }, {
102         'url': 'nexx:128907',
103         'only_matching': True,
104     }, {
105         'url': 'https://arc.nexx.cloud/api/video/128907.json',
106         'only_matching': True,
107     }]
108
109     @staticmethod
110     def _extract_domain_id(webpage):
111         mobj = re.search(
112             r'<script\b[^>]+\bsrc=["\'](?:https?:)?//require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
113             webpage)
114         return mobj.group('id') if mobj else None
115
116     @staticmethod
117     def _extract_urls(webpage):
118         # Reference:
119         # 1. https://nx-s.akamaized.net/files/201510/44.pdf
120
121         entries = []
122
123         # JavaScript Integration
124         domain_id = NexxIE._extract_domain_id(webpage)
125         if domain_id:
126             for video_id in re.findall(
127                     r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
128                     webpage):
129                 entries.append(
130                     'https://api.nexx.cloud/v3/%s/videos/byid/%s'
131                     % (domain_id, video_id))
132
133         # TODO: support more embed formats
134
135         return entries
136
137     @staticmethod
138     def _extract_url(webpage):
139         return NexxIE._extract_urls(webpage)[0]
140
141     def _handle_error(self, response):
142         status = int_or_none(try_get(
143             response, lambda x: x['metadata']['status']) or 200)
144         if 200 <= status < 300:
145             return
146         raise ExtractorError(
147             '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
148             expected=True)
149
150     def _call_api(self, domain_id, path, video_id, data=None, headers={}):
151         headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
152         result = self._download_json(
153             'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
154             'Downloading %s JSON' % path, data=urlencode_postdata(data),
155             headers=headers)
156         self._handle_error(result)
157         return result['result']
158
159     def _extract_free_formats(self, video, video_id):
160         stream_data = video['streamdata']
161         cdn = stream_data['cdnType']
162         assert cdn == 'free'
163
164         hash = video['general']['hash']
165
166         ps = compat_str(stream_data['originalDomain'])
167         if stream_data['applyFolderHierarchy'] == 1:
168             s = ('%04d' % int(video_id))[::-1]
169             ps += '/%s/%s' % (s[0:2], s[2:4])
170         ps += '/%s/%s_' % (video_id, hash)
171
172         formats = [{
173             'url': 'http://%s%s2500_var.mp4' % (stream_data['cdnPathHTTP'], ps),
174             'format_id': '%s-http' % cdn,
175         }]
176
177         def make_url(root, protocol):
178             t = 'http://' + root + ps
179             fd = stream_data['azureFileDistribution'].split(',')
180             cdn_provider = stream_data['cdnProvider']
181
182             def p0(p):
183                 return '_%s' % int(p[0]) if stream_data['applyAzureStructure'] == 1 else ''
184
185             if cdn_provider == 'ak':
186                 t += ','
187                 for i in fd:
188                     p = i.split(':')
189                     t += p[1] + p0(p) + ','
190                 t += '.mp4.csmil/master.m3u8'
191             elif cdn_provider == 'ce':
192                 k = t.split('/')
193                 h = k.pop()
194                 t = '/'.join(k)
195                 t += '/asset.ism/manifest.' + ('m3u8' if protocol == 'hls' else 'mpd') + '?dcp_ver=aos4&videostream='
196                 for i in fd:
197                     p = i.split(':')
198                     a = '%s%s%s.mp4:%s' % (h, p[1], p0(p), int(p[0]) * 1000)
199                     t += a + ','
200                 t = t[:-1] + '&audiostream=' + a.split(':')[0]
201             return t
202
203         formats.extend(self._extract_mpd_formats(
204             make_url(stream_data['cdnPathDASH'], 'dash'), video_id,
205             mpd_id='%s-dash' % cdn, fatal=False))
206         formats.extend(self._extract_m3u8_formats(
207             make_url(stream_data['cdnPathHLS'], 'hls'), video_id, 'mp4',
208             entry_protocol='m3u8_native', m3u8_id='%s-hls' % cdn, fatal=False))
209
210         return formats
211
212     def _extract_azure_formats(self, video, video_id):
213         stream_data = video['streamdata']
214         cdn = stream_data['cdnType']
215         assert cdn == 'azure'
216
217         azure_locator = stream_data['azureLocator']
218
219         def get_cdn_shield_base(shield_type='', static=False):
220             for secure in ('', 's'):
221                 cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
222                 if cdn_shield:
223                     return 'http%s://%s' % (secure, cdn_shield)
224             else:
225                 if 'fb' in stream_data['azureAccount']:
226                     prefix = 'df' if static else 'f'
227                 else:
228                     prefix = 'd' if static else 'p'
229                 account = int(stream_data['azureAccount'].replace('nexxplayplus', '').replace('nexxplayfb', ''))
230                 return 'http://nx-%s%02d.akamaized.net/' % (prefix, account)
231
232         language = video['general'].get('language_raw') or ''
233
234         azure_stream_base = get_cdn_shield_base()
235         is_ml = ',' in language
236         azure_manifest_url = '%s%s/%s_src%s.ism/Manifest' % (
237             azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
238
239         protection_token = try_get(
240             video, lambda x: x['protectiondata']['token'], compat_str)
241         if protection_token:
242             azure_manifest_url += '?hdnts=%s' % protection_token
243
244         formats = self._extract_m3u8_formats(
245             azure_manifest_url % '(format=m3u8-aapl)',
246             video_id, 'mp4', 'm3u8_native',
247             m3u8_id='%s-hls' % cdn, fatal=False)
248         formats.extend(self._extract_mpd_formats(
249             azure_manifest_url % '(format=mpd-time-csf)',
250             video_id, mpd_id='%s-dash' % cdn, fatal=False))
251         formats.extend(self._extract_ism_formats(
252             azure_manifest_url % '', video_id, ism_id='%s-mss' % cdn, fatal=False))
253
254         azure_progressive_base = get_cdn_shield_base('Prog', True)
255         azure_file_distribution = stream_data.get('azureFileDistribution')
256         if azure_file_distribution:
257             fds = azure_file_distribution.split(',')
258             if fds:
259                 for fd in fds:
260                     ss = fd.split(':')
261                     if len(ss) == 2:
262                         tbr = int_or_none(ss[0])
263                         if tbr:
264                             f = {
265                                 'url': '%s%s/%s_src_%s_%d.mp4' % (
266                                     azure_progressive_base, azure_locator, video_id, ss[1], tbr),
267                                 'format_id': '%s-http-%d' % (cdn, tbr),
268                                 'tbr': tbr,
269                             }
270                             width_height = ss[1].split('x')
271                             if len(width_height) == 2:
272                                 f.update({
273                                     'width': int_or_none(width_height[0]),
274                                     'height': int_or_none(width_height[1]),
275                                 })
276                             formats.append(f)
277
278         return formats
279
280     def _real_extract(self, url):
281         mobj = re.match(self._VALID_URL, url)
282         domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
283         video_id = mobj.group('id')
284
285         video = None
286
287         response = self._download_json(
288             'https://arc.nexx.cloud/api/video/%s.json' % video_id,
289             video_id, fatal=False)
290         if response and isinstance(response, dict):
291             result = response.get('result')
292             if result and isinstance(result, dict):
293                 video = result
294
295         # not all videos work via arc, e.g. nexx:741:1269984
296         if not video:
297             # Reverse engineered from JS code (see getDeviceID function)
298             device_id = '%d:%d:%d%d' % (
299                 random.randint(1, 4), int(time.time()),
300                 random.randint(1e4, 99999), random.randint(1, 9))
301
302             result = self._call_api(domain_id, 'session/init', video_id, data={
303                 'nxp_devh': device_id,
304                 'nxp_userh': '',
305                 'precid': '0',
306                 'playlicense': '0',
307                 'screenx': '1920',
308                 'screeny': '1080',
309                 'playerversion': '6.0.00',
310                 'gateway': 'html5',
311                 'adGateway': '',
312                 'explicitlanguage': 'en-US',
313                 'addTextTemplates': '1',
314                 'addDomainData': '1',
315                 'addAdModel': '1',
316             }, headers={
317                 'X-Request-Enable-Auth-Fallback': '1',
318             })
319
320             cid = result['general']['cid']
321
322             # As described in [1] X-Request-Token generation algorithm is
323             # as follows:
324             #   md5( operation + domain_id + domain_secret )
325             # where domain_secret is a static value that will be given by nexx.tv
326             # as per [1]. Here is how this "secret" is generated (reversed
327             # from _play.api.init function, search for clienttoken). So it's
328             # actually not static and not that much of a secret.
329             # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
330             secret = result['device']['clienttoken'][int(device_id[0]):]
331             secret = secret[0:len(secret) - int(device_id[-1])]
332
333             op = 'byid'
334
335             # Reversed from JS code for _play.api.call function (search for
336             # X-Request-Token)
337             request_token = hashlib.md5(
338                 ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
339
340             video = self._call_api(
341                 domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
342                     'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
343                     'addInteractionOptions': '1',
344                     'addStatusDetails': '1',
345                     'addStreamDetails': '1',
346                     'addCaptions': '1',
347                     'addScenes': '1',
348                     'addHotSpots': '1',
349                     'addBumpers': '1',
350                     'captionFormat': 'data',
351                 }, headers={
352                     'X-Request-CID': cid,
353                     'X-Request-Token': request_token,
354                 })
355
356         general = video['general']
357         title = general['title']
358
359         cdn = video['streamdata']['cdnType']
360
361         if cdn == 'azure':
362             formats = self._extract_azure_formats(video, video_id)
363         elif cdn == 'free':
364             formats = self._extract_free_formats(video, video_id)
365         else:
366             # TODO: reverse more cdns
367             assert False
368
369         self._sort_formats(formats)
370
371         return {
372             'id': video_id,
373             'title': title,
374             'alt_title': general.get('subtitle'),
375             'description': general.get('description'),
376             'release_year': int_or_none(general.get('year')),
377             'creator': general.get('studio') or general.get('studio_adref'),
378             'thumbnail': try_get(
379                 video, lambda x: x['imagedata']['thumb'], compat_str),
380             'duration': parse_duration(general.get('runtime')),
381             'timestamp': int_or_none(general.get('uploaded')),
382             'episode_number': int_or_none(try_get(
383                 video, lambda x: x['episodedata']['episode'])),
384             'season_number': int_or_none(try_get(
385                 video, lambda x: x['episodedata']['season'])),
386             'formats': formats,
387         }
388
389
390 class NexxEmbedIE(InfoExtractor):
391     _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
392     _TEST = {
393         'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
394         'md5': '16746bfc28c42049492385c989b26c4a',
395         'info_dict': {
396             'id': '161464',
397             'ext': 'mp4',
398             'title': 'Nervenkitzel Achterbahn',
399             'alt_title': 'Karussellbauer in Deutschland',
400             'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
401             'release_year': 2005,
402             'creator': 'SPIEGEL TV',
403             'thumbnail': r're:^https?://.*\.jpg$',
404             'duration': 2761,
405             'timestamp': 1394021479,
406             'upload_date': '20140305',
407         },
408         'params': {
409             'format': 'bestvideo',
410             'skip_download': True,
411         },
412     }
413
414     @staticmethod
415     def _extract_urls(webpage):
416         # Reference:
417         # 1. https://nx-s.akamaized.net/files/201510/44.pdf
418
419         # iFrame Embed Integration
420         return [mobj.group('url') for mobj in re.finditer(
421             r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
422             webpage)]
423
424     def _real_extract(self, url):
425         embed_id = self._match_id(url)
426
427         webpage = self._download_webpage(url, embed_id)
428
429         return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())