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