[nexx] Improve JS embed extraction
[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         mobj = re.search(
76             r'<script\b[^>]+\bsrc=["\']https?://require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
77             webpage)
78         if mobj:
79             domain_id = mobj.group('id')
80             for video_id in re.findall(
81                     r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
82                     webpage):
83                 entries.append(
84                     'https://api.nexx.cloud/v3/%s/videos/byid/%s'
85                     % (domain_id, video_id))
86
87         # TODO: support more embed formats
88
89         return entries
90
91     def _handle_error(self, response):
92         status = int_or_none(try_get(
93             response, lambda x: x['metadata']['status']) or 200)
94         if 200 <= status < 300:
95             return
96         raise ExtractorError(
97             '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
98             expected=True)
99
100     def _call_api(self, domain_id, path, video_id, data=None, headers={}):
101         headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
102         result = self._download_json(
103             'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
104             'Downloading %s JSON' % path, data=urlencode_postdata(data),
105             headers=headers)
106         self._handle_error(result)
107         return result['result']
108
109     def _real_extract(self, url):
110         mobj = re.match(self._VALID_URL, url)
111         domain_id, video_id = mobj.group('domain_id', 'id')
112
113         # Reverse engineered from JS code (see getDeviceID function)
114         device_id = '%d:%d:%d%d' % (
115             random.randint(1, 4), int(time.time()),
116             random.randint(1e4, 99999), random.randint(1, 9))
117
118         result = self._call_api(domain_id, 'session/init', video_id, data={
119             'nxp_devh': device_id,
120             'nxp_userh': '',
121             'precid': '0',
122             'playlicense': '0',
123             'screenx': '1920',
124             'screeny': '1080',
125             'playerversion': '6.0.00',
126             'gateway': 'html5',
127             'adGateway': '',
128             'explicitlanguage': 'en-US',
129             'addTextTemplates': '1',
130             'addDomainData': '1',
131             'addAdModel': '1',
132         }, headers={
133             'X-Request-Enable-Auth-Fallback': '1',
134         })
135
136         cid = result['general']['cid']
137
138         # As described in [1] X-Request-Token generation algorithm is
139         # as follows:
140         #   md5( operation + domain_id + domain_secret )
141         # where domain_secret is a static value that will be given by nexx.tv
142         # as per [1]. Here is how this "secret" is generated (reversed
143         # from _play.api.init function, search for clienttoken). So it's
144         # actually not static and not that much of a secret.
145         # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
146         secret = result['device']['clienttoken'][int(device_id[0]):]
147         secret = secret[0:len(secret) - int(device_id[-1])]
148
149         op = 'byid'
150
151         # Reversed from JS code for _play.api.call function (search for
152         # X-Request-Token)
153         request_token = hashlib.md5(
154             ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
155
156         video = self._call_api(
157             domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
158                 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
159                 'addInteractionOptions': '1',
160                 'addStatusDetails': '1',
161                 'addStreamDetails': '1',
162                 'addCaptions': '1',
163                 'addScenes': '1',
164                 'addHotSpots': '1',
165                 'addBumpers': '1',
166                 'captionFormat': 'data',
167             }, headers={
168                 'X-Request-CID': cid,
169                 'X-Request-Token': request_token,
170             })
171
172         general = video['general']
173         title = general['title']
174
175         stream_data = video['streamdata']
176         language = general.get('language_raw') or ''
177
178         # TODO: reverse more cdns and formats
179
180         cdn = stream_data['cdnType']
181         assert cdn == 'azure'
182
183         azure_locator = stream_data['azureLocator']
184
185         AZURE_URL = 'http://nx-p%02d.akamaized.net/'
186
187         for secure in ('s', ''):
188             cdn_shield = stream_data.get('cdnShieldHTTP%s' % secure.upper())
189             if cdn_shield:
190                 azure_base = 'http%s://%s' % (secure, cdn_shield)
191                 break
192         else:
193             azure_base = AZURE_URL % int(stream_data['azureAccount'].replace('nexxplayplus', ''))
194
195         is_ml = ',' in language
196         azure_m3u8_url = '%s%s/%s_src%s.ism/Manifest(format=m3u8-aapl)' % (
197             azure_base, azure_locator, video_id, ('_manifest' if is_ml else ''))
198
199         protection_token = try_get(
200             video, lambda x: x['protectiondata']['token'], compat_str)
201         if protection_token:
202             azure_m3u8_url += '?hdnts=%s' % protection_token
203
204         formats = self._extract_m3u8_formats(
205             azure_m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native',
206             m3u8_id='%s-hls' % cdn)
207         self._sort_formats(formats)
208
209         return {
210             'id': video_id,
211             'title': title,
212             'alt_title': general.get('subtitle'),
213             'description': general.get('description'),
214             'release_year': int_or_none(general.get('year')),
215             'creator': general.get('studio') or general.get('studio_adref'),
216             'thumbnail': try_get(
217                 video, lambda x: x['imagedata']['thumb'], compat_str),
218             'duration': parse_duration(general.get('runtime')),
219             'timestamp': int_or_none(general.get('uploaded')),
220             'episode_number': int_or_none(try_get(
221                 video, lambda x: x['episodedata']['episode'])),
222             'season_number': int_or_none(try_get(
223                 video, lambda x: x['episodedata']['season'])),
224             'formats': formats,
225         }