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