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