[nexx:embed] Add extractor for iframe embeds
[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     @staticmethod
92     def _extract_url(webpage):
93         return NexxIE._extract_urls(webpage)[0]
94
95     def _handle_error(self, response):
96         status = int_or_none(try_get(
97             response, lambda x: x['metadata']['status']) or 200)
98         if 200 <= status < 300:
99             return
100         raise ExtractorError(
101             '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
102             expected=True)
103
104     def _call_api(self, domain_id, path, video_id, data=None, headers={}):
105         headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
106         result = self._download_json(
107             'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
108             'Downloading %s JSON' % path, data=urlencode_postdata(data),
109             headers=headers)
110         self._handle_error(result)
111         return result['result']
112
113     def _real_extract(self, url):
114         mobj = re.match(self._VALID_URL, url)
115         domain_id, video_id = mobj.group('domain_id', 'id')
116
117         # Reverse engineered from JS code (see getDeviceID function)
118         device_id = '%d:%d:%d%d' % (
119             random.randint(1, 4), int(time.time()),
120             random.randint(1e4, 99999), random.randint(1, 9))
121
122         result = self._call_api(domain_id, 'session/init', video_id, data={
123             'nxp_devh': device_id,
124             'nxp_userh': '',
125             'precid': '0',
126             'playlicense': '0',
127             'screenx': '1920',
128             'screeny': '1080',
129             'playerversion': '6.0.00',
130             'gateway': 'html5',
131             'adGateway': '',
132             'explicitlanguage': 'en-US',
133             'addTextTemplates': '1',
134             'addDomainData': '1',
135             'addAdModel': '1',
136         }, headers={
137             'X-Request-Enable-Auth-Fallback': '1',
138         })
139
140         cid = result['general']['cid']
141
142         # As described in [1] X-Request-Token generation algorithm is
143         # as follows:
144         #   md5( operation + domain_id + domain_secret )
145         # where domain_secret is a static value that will be given by nexx.tv
146         # as per [1]. Here is how this "secret" is generated (reversed
147         # from _play.api.init function, search for clienttoken). So it's
148         # actually not static and not that much of a secret.
149         # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
150         secret = result['device']['clienttoken'][int(device_id[0]):]
151         secret = secret[0:len(secret) - int(device_id[-1])]
152
153         op = 'byid'
154
155         # Reversed from JS code for _play.api.call function (search for
156         # X-Request-Token)
157         request_token = hashlib.md5(
158             ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
159
160         video = self._call_api(
161             domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
162                 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
163                 'addInteractionOptions': '1',
164                 'addStatusDetails': '1',
165                 'addStreamDetails': '1',
166                 'addCaptions': '1',
167                 'addScenes': '1',
168                 'addHotSpots': '1',
169                 'addBumpers': '1',
170                 'captionFormat': 'data',
171             }, headers={
172                 'X-Request-CID': cid,
173                 'X-Request-Token': request_token,
174             })
175
176         general = video['general']
177         title = general['title']
178
179         stream_data = video['streamdata']
180         language = general.get('language_raw') or ''
181
182         # TODO: reverse more cdns and formats
183
184         cdn = stream_data['cdnType']
185         assert cdn == 'azure'
186
187         azure_locator = stream_data['azureLocator']
188
189         AZURE_URL = 'http://nx-p%02d.akamaized.net/'
190
191         for secure in ('s', ''):
192             cdn_shield = stream_data.get('cdnShieldHTTP%s' % secure.upper())
193             if cdn_shield:
194                 azure_base = 'http%s://%s' % (secure, cdn_shield)
195                 break
196         else:
197             azure_base = AZURE_URL % int(stream_data['azureAccount'].replace('nexxplayplus', ''))
198
199         is_ml = ',' in language
200         azure_m3u8_url = '%s%s/%s_src%s.ism/Manifest(format=m3u8-aapl)' % (
201             azure_base, azure_locator, video_id, ('_manifest' if is_ml else ''))
202
203         protection_token = try_get(
204             video, lambda x: x['protectiondata']['token'], compat_str)
205         if protection_token:
206             azure_m3u8_url += '?hdnts=%s' % protection_token
207
208         formats = self._extract_m3u8_formats(
209             azure_m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native',
210             m3u8_id='%s-hls' % cdn)
211         self._sort_formats(formats)
212
213         return {
214             'id': video_id,
215             'title': title,
216             'alt_title': general.get('subtitle'),
217             'description': general.get('description'),
218             'release_year': int_or_none(general.get('year')),
219             'creator': general.get('studio') or general.get('studio_adref'),
220             'thumbnail': try_get(
221                 video, lambda x: x['imagedata']['thumb'], compat_str),
222             'duration': parse_duration(general.get('runtime')),
223             'timestamp': int_or_none(general.get('uploaded')),
224             'episode_number': int_or_none(try_get(
225                 video, lambda x: x['episodedata']['episode'])),
226             'season_number': int_or_none(try_get(
227                 video, lambda x: x['episodedata']['season'])),
228             'formats': formats,
229         }
230
231
232 class NexxEmbedIE(InfoExtractor):
233     _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
234     _TEST = {
235         'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
236         'md5': '16746bfc28c42049492385c989b26c4a',
237         'info_dict': {
238             'id': '161464',
239             'ext': 'mp4',
240             'title': 'Nervenkitzel Achterbahn',
241             'alt_title': 'Karussellbauer in Deutschland',
242             'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
243             'release_year': 2005,
244             'creator': 'SPIEGEL TV',
245             'thumbnail': r're:^https?://.*\.jpg$',
246             'duration': 2761,
247             'timestamp': 1394021479,
248             'upload_date': '20140305',
249         },
250         'params': {
251             'format': 'bestvideo',
252             'skip_download': True,
253         },
254     }
255
256     @staticmethod
257     def _extract_urls(webpage):
258         # Reference:
259         # 1. https://nx-s.akamaized.net/files/201510/44.pdf
260
261         # iFrame Embed Integration
262         return [mobj.group('url') for mobj in re.finditer(
263                 r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
264             webpage)]
265
266     def _real_extract(self, url):
267         embed_id = self._match_id(url)
268
269         webpage = self._download_webpage(url, embed_id)
270
271         return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())