[nexx] switch to ark api(closes #15652)
[youtube-dl] / youtube_dl / extractor / nexx.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import compat_str
8 from ..utils import (
9     int_or_none,
10     parse_duration,
11     try_get,
12 )
13
14
15 class NexxIE(InfoExtractor):
16     _VALID_URL = r'''(?x)
17                         (?:
18                             https?://api\.nexx(?:\.cloud|cdn\.com)/v3/(?P<domain_id>\d+)/videos/byid/|
19                             nexx:(?P<domain_id_s>\d+):
20                         )
21                         (?P<id>\d+)
22                     '''
23     _TESTS = [{
24         # movie
25         'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
26         'md5': '828cea195be04e66057b846288295ba1',
27         'info_dict': {
28             'id': '128907',
29             'ext': 'mp4',
30             'title': 'Stiftung Warentest',
31             'alt_title': 'Wie ein Test abläuft',
32             'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
33             'release_year': 2013,
34             'creator': 'SPIEGEL TV',
35             'thumbnail': r're:^https?://.*\.jpg$',
36             'duration': 2509,
37             'timestamp': 1384264416,
38             'upload_date': '20131112',
39         },
40     }, {
41         # episode
42         'url': 'https://api.nexx.cloud/v3/741/videos/byid/247858',
43         'info_dict': {
44             'id': '247858',
45             'ext': 'mp4',
46             'title': 'Return of the Golden Child (OV)',
47             'description': 'md5:5d969537509a92b733de21bae249dc63',
48             'release_year': 2017,
49             'thumbnail': r're:^https?://.*\.jpg$',
50             'duration': 1397,
51             'timestamp': 1495033267,
52             'upload_date': '20170517',
53             'episode_number': 2,
54             'season_number': 2,
55         },
56         'params': {
57             'skip_download': True,
58         },
59     }, {
60         'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
61         'only_matching': True,
62     }, {
63         'url': 'nexx:748:128907',
64         'only_matching': True,
65     }]
66
67     @staticmethod
68     def _extract_domain_id(webpage):
69         mobj = re.search(
70             r'<script\b[^>]+\bsrc=["\'](?:https?:)?//require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
71             webpage)
72         return mobj.group('id') if mobj else None
73
74     @staticmethod
75     def _extract_urls(webpage):
76         # Reference:
77         # 1. https://nx-s.akamaized.net/files/201510/44.pdf
78
79         entries = []
80
81         # JavaScript Integration
82         domain_id = NexxIE._extract_domain_id(webpage)
83         if domain_id:
84             for video_id in re.findall(
85                     r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
86                     webpage):
87                 entries.append(
88                     'https://api.nexx.cloud/v3/%s/videos/byid/%s'
89                     % (domain_id, video_id))
90
91         # TODO: support more embed formats
92
93         return entries
94
95     @staticmethod
96     def _extract_url(webpage):
97         return NexxIE._extract_urls(webpage)[0]
98
99     def _real_extract(self, url):
100         video_id = self._match_id(url)
101
102         video = self._download_json(
103             'https://arc.nexx.cloud/api/video/%s.json' % video_id,
104             video_id)['result']
105
106         general = video['general']
107         title = general['title']
108
109         stream_data = video['streamdata']
110         language = general.get('language_raw') or ''
111
112         # TODO: reverse more cdns
113
114         cdn = stream_data['cdnType']
115         assert cdn == 'azure'
116
117         azure_locator = stream_data['azureLocator']
118
119         AZURE_URL = 'http://nx%s%02d.akamaized.net/'
120
121         def get_cdn_shield_base(shield_type='', prefix='-p'):
122             for secure in ('', 's'):
123                 cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
124                 if cdn_shield:
125                     return 'http%s://%s' % (secure, cdn_shield)
126             else:
127                 return AZURE_URL % (prefix, int(stream_data['azureAccount'].replace('nexxplayplus', '')))
128
129         azure_stream_base = get_cdn_shield_base()
130         is_ml = ',' in language
131         azure_manifest_url = '%s%s/%s_src%s.ism/Manifest' % (
132             azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
133
134         protection_token = try_get(
135             video, lambda x: x['protectiondata']['token'], compat_str)
136         if protection_token:
137             azure_manifest_url += '?hdnts=%s' % protection_token
138
139         formats = self._extract_m3u8_formats(
140             azure_manifest_url % '(format=m3u8-aapl)',
141             video_id, 'mp4', 'm3u8_native',
142             m3u8_id='%s-hls' % cdn, fatal=False)
143         formats.extend(self._extract_mpd_formats(
144             azure_manifest_url % '(format=mpd-time-csf)',
145             video_id, mpd_id='%s-dash' % cdn, fatal=False))
146         formats.extend(self._extract_ism_formats(
147             azure_manifest_url % '', video_id, ism_id='%s-mss' % cdn, fatal=False))
148
149         azure_progressive_base = get_cdn_shield_base('Prog', '-d')
150         azure_file_distribution = stream_data.get('azureFileDistribution')
151         if azure_file_distribution:
152             fds = azure_file_distribution.split(',')
153             if fds:
154                 for fd in fds:
155                     ss = fd.split(':')
156                     if len(ss) == 2:
157                         tbr = int_or_none(ss[0])
158                         if tbr:
159                             f = {
160                                 'url': '%s%s/%s_src_%s_%d.mp4' % (
161                                     azure_progressive_base, azure_locator, video_id, ss[1], tbr),
162                                 'format_id': '%s-http-%d' % (cdn, tbr),
163                                 'tbr': tbr,
164                             }
165                             width_height = ss[1].split('x')
166                             if len(width_height) == 2:
167                                 f.update({
168                                     'width': int_or_none(width_height[0]),
169                                     'height': int_or_none(width_height[1]),
170                                 })
171                             formats.append(f)
172
173         self._sort_formats(formats)
174
175         return {
176             'id': video_id,
177             'title': title,
178             'alt_title': general.get('subtitle'),
179             'description': general.get('description'),
180             'release_year': int_or_none(general.get('year')),
181             'creator': general.get('studio') or general.get('studio_adref'),
182             'thumbnail': try_get(
183                 video, lambda x: x['imagedata']['thumb'], compat_str),
184             'duration': parse_duration(general.get('runtime')),
185             'timestamp': int_or_none(general.get('uploaded')),
186             'episode_number': int_or_none(try_get(
187                 video, lambda x: x['episodedata']['episode'])),
188             'season_number': int_or_none(try_get(
189                 video, lambda x: x['episodedata']['season'])),
190             'formats': formats,
191         }
192
193
194 class NexxEmbedIE(InfoExtractor):
195     _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
196     _TEST = {
197         'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
198         'md5': '16746bfc28c42049492385c989b26c4a',
199         'info_dict': {
200             'id': '161464',
201             'ext': 'mp4',
202             'title': 'Nervenkitzel Achterbahn',
203             'alt_title': 'Karussellbauer in Deutschland',
204             'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
205             'release_year': 2005,
206             'creator': 'SPIEGEL TV',
207             'thumbnail': r're:^https?://.*\.jpg$',
208             'duration': 2761,
209             'timestamp': 1394021479,
210             'upload_date': '20140305',
211         },
212         'params': {
213             'format': 'bestvideo',
214             'skip_download': True,
215         },
216     }
217
218     @staticmethod
219     def _extract_urls(webpage):
220         # Reference:
221         # 1. https://nx-s.akamaized.net/files/201510/44.pdf
222
223         # iFrame Embed Integration
224         return [mobj.group('url') for mobj in re.finditer(
225             r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
226             webpage)]
227
228     def _real_extract(self, url):
229         embed_id = self._match_id(url)
230
231         webpage = self._download_webpage(url, embed_id)
232
233         return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())