nexx.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import hashlib
  4. import random
  5. import re
  6. import time
  7. from .common import InfoExtractor
  8. from ..compat import compat_str
  9. from ..utils import (
  10. ExtractorError,
  11. int_or_none,
  12. parse_duration,
  13. try_get,
  14. urlencode_postdata,
  15. )
  16. class NexxIE(InfoExtractor):
  17. _VALID_URL = r'''(?x)
  18. (?:
  19. https?://api\.nexx(?:\.cloud|cdn\.com)/v3/(?P<domain_id>\d+)/videos/byid/|
  20. nexx:(?:(?P<domain_id_s>\d+):)?|
  21. https?://arc\.nexx\.cloud/api/video/
  22. )
  23. (?P<id>\d+)
  24. '''
  25. _TESTS = [{
  26. # movie
  27. 'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
  28. 'md5': '828cea195be04e66057b846288295ba1',
  29. 'info_dict': {
  30. 'id': '128907',
  31. 'ext': 'mp4',
  32. 'title': 'Stiftung Warentest',
  33. 'alt_title': 'Wie ein Test abläuft',
  34. 'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
  35. 'release_year': 2013,
  36. 'creator': 'SPIEGEL TV',
  37. 'thumbnail': r're:^https?://.*\.jpg$',
  38. 'duration': 2509,
  39. 'timestamp': 1384264416,
  40. 'upload_date': '20131112',
  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. 'skip_download': True,
  60. },
  61. }, {
  62. # does not work via arc
  63. 'url': 'nexx:741:1269984',
  64. 'md5': 'c714b5b238b2958dc8d5642addba6886',
  65. 'info_dict': {
  66. 'id': '1269984',
  67. 'ext': 'mp4',
  68. 'title': '1 TAG ohne KLO... wortwörtlich! 😑',
  69. 'alt_title': '1 TAG ohne KLO... wortwörtlich! 😑',
  70. 'description': 'md5:4604539793c49eda9443ab5c5b1d612f',
  71. 'thumbnail': r're:^https?://.*\.jpg$',
  72. 'duration': 607,
  73. 'timestamp': 1518614955,
  74. 'upload_date': '20180214',
  75. },
  76. }, {
  77. # free cdn from http://www.spiegel.de/video/eifel-zoo-aufregung-um-ausgebrochene-raubtiere-video-99018031.html
  78. 'url': 'nexx:747:1533779',
  79. 'md5': '6bf6883912b82b7069fb86c2297e9893',
  80. 'info_dict': {
  81. 'id': '1533779',
  82. 'ext': 'mp4',
  83. 'title': 'Aufregung um ausgebrochene Raubtiere',
  84. 'alt_title': 'Eifel-Zoo',
  85. 'description': 'md5:f21375c91c74ad741dcb164c427999d2',
  86. 'thumbnail': r're:^https?://.*\.jpg$',
  87. 'duration': 111,
  88. 'timestamp': 1527874460,
  89. 'upload_date': '20180601',
  90. },
  91. }, {
  92. 'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
  93. 'only_matching': True,
  94. }, {
  95. 'url': 'nexx:748:128907',
  96. 'only_matching': True,
  97. }, {
  98. 'url': 'nexx:128907',
  99. 'only_matching': True,
  100. }, {
  101. 'url': 'https://arc.nexx.cloud/api/video/128907.json',
  102. 'only_matching': True,
  103. }]
  104. @staticmethod
  105. def _extract_domain_id(webpage):
  106. mobj = re.search(
  107. r'<script\b[^>]+\bsrc=["\'](?:https?:)?//require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
  108. webpage)
  109. return mobj.group('id') if mobj else None
  110. @staticmethod
  111. def _extract_urls(webpage):
  112. # Reference:
  113. # 1. https://nx-s.akamaized.net/files/201510/44.pdf
  114. entries = []
  115. # JavaScript Integration
  116. domain_id = NexxIE._extract_domain_id(webpage)
  117. if domain_id:
  118. for video_id in re.findall(
  119. r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
  120. webpage):
  121. entries.append(
  122. 'https://api.nexx.cloud/v3/%s/videos/byid/%s'
  123. % (domain_id, video_id))
  124. # TODO: support more embed formats
  125. return entries
  126. @staticmethod
  127. def _extract_url(webpage):
  128. return NexxIE._extract_urls(webpage)[0]
  129. def _handle_error(self, response):
  130. status = int_or_none(try_get(
  131. response, lambda x: x['metadata']['status']) or 200)
  132. if 200 <= status < 300:
  133. return
  134. raise ExtractorError(
  135. '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
  136. expected=True)
  137. def _call_api(self, domain_id, path, video_id, data=None, headers={}):
  138. headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  139. result = self._download_json(
  140. 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
  141. 'Downloading %s JSON' % path, data=urlencode_postdata(data),
  142. headers=headers)
  143. self._handle_error(result)
  144. return result['result']
  145. def _extract_free_formats(self, video, video_id):
  146. stream_data = video['streamdata']
  147. cdn = stream_data['cdnType']
  148. assert cdn == 'free'
  149. hash = video['general']['hash']
  150. ps = compat_str(stream_data['originalDomain'])
  151. if stream_data['applyFolderHierarchy'] == 1:
  152. s = ('%04d' % int(video_id))[::-1]
  153. ps += '/%s/%s' % (s[0:2], s[2:4])
  154. ps += '/%s/%s_' % (video_id, hash)
  155. formats = [{
  156. 'url': 'http://%s%s2500_var.mp4' % (stream_data['cdnPathHTTP'], ps),
  157. 'format_id': '%s-http' % cdn,
  158. }]
  159. def make_url(root, protocol):
  160. t = 'http://' + root + ps
  161. fd = stream_data['azureFileDistribution'].split(',')
  162. cdn_provider = stream_data['cdnProvider']
  163. def p0(p):
  164. return '_%s' % int(p[0]) if stream_data['applyAzureStructure'] == 1 else ''
  165. if cdn_provider == 'ak':
  166. t += ','
  167. for i in fd:
  168. p = i.split(':')
  169. t += p[1] + p0(p) + ','
  170. t += '.mp4.csmil/master.m3u8'
  171. elif cdn_provider == 'ce':
  172. k = t.split('/')
  173. h = k.pop()
  174. t = '/'.join(k)
  175. t += '/asset.ism/manifest.' + ('m3u8' if protocol == 'hls' else 'mpd') + '?dcp_ver=aos4&videostream='
  176. for i in fd:
  177. p = i.split(':')
  178. a = '%s%s%s.mp4:%s' % (h, p[1], p0(p), int(p[0]) * 1000)
  179. t += a + ','
  180. t = t[:-1] + '&audiostream=' + a.split(':')[0]
  181. return t
  182. formats.extend(self._extract_mpd_formats(
  183. make_url(stream_data['cdnPathDASH'], 'dash'), video_id,
  184. mpd_id='%s-dash' % cdn, fatal=False))
  185. formats.extend(self._extract_m3u8_formats(
  186. make_url(stream_data['cdnPathHLS'], 'hls'), video_id, 'mp4',
  187. entry_protocol='m3u8_native', m3u8_id='%s-hls' % cdn, fatal=False))
  188. return formats
  189. def _extract_azure_formats(self, video, video_id):
  190. stream_data = video['streamdata']
  191. cdn = stream_data['cdnType']
  192. assert cdn == 'azure'
  193. azure_locator = stream_data['azureLocator']
  194. def get_cdn_shield_base(shield_type='', static=False):
  195. for secure in ('', 's'):
  196. cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
  197. if cdn_shield:
  198. return 'http%s://%s' % (secure, cdn_shield)
  199. else:
  200. if 'fb' in stream_data['azureAccount']:
  201. prefix = 'df' if static else 'f'
  202. else:
  203. prefix = 'd' if static else 'p'
  204. account = int(stream_data['azureAccount'].replace('nexxplayplus', '').replace('nexxplayfb', ''))
  205. return 'http://nx-%s%02d.akamaized.net/' % (prefix, account)
  206. language = video['general'].get('language_raw') or ''
  207. azure_stream_base = get_cdn_shield_base()
  208. is_ml = ',' in language
  209. azure_manifest_url = '%s%s/%s_src%s.ism/Manifest' % (
  210. azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
  211. protection_token = try_get(
  212. video, lambda x: x['protectiondata']['token'], compat_str)
  213. if protection_token:
  214. azure_manifest_url += '?hdnts=%s' % protection_token
  215. formats = self._extract_m3u8_formats(
  216. azure_manifest_url % '(format=m3u8-aapl)',
  217. video_id, 'mp4', 'm3u8_native',
  218. m3u8_id='%s-hls' % cdn, fatal=False)
  219. formats.extend(self._extract_mpd_formats(
  220. azure_manifest_url % '(format=mpd-time-csf)',
  221. video_id, mpd_id='%s-dash' % cdn, fatal=False))
  222. formats.extend(self._extract_ism_formats(
  223. azure_manifest_url % '', video_id, ism_id='%s-mss' % cdn, fatal=False))
  224. azure_progressive_base = get_cdn_shield_base('Prog', True)
  225. azure_file_distribution = stream_data.get('azureFileDistribution')
  226. if azure_file_distribution:
  227. fds = azure_file_distribution.split(',')
  228. if fds:
  229. for fd in fds:
  230. ss = fd.split(':')
  231. if len(ss) == 2:
  232. tbr = int_or_none(ss[0])
  233. if tbr:
  234. f = {
  235. 'url': '%s%s/%s_src_%s_%d.mp4' % (
  236. azure_progressive_base, azure_locator, video_id, ss[1], tbr),
  237. 'format_id': '%s-http-%d' % (cdn, tbr),
  238. 'tbr': tbr,
  239. }
  240. width_height = ss[1].split('x')
  241. if len(width_height) == 2:
  242. f.update({
  243. 'width': int_or_none(width_height[0]),
  244. 'height': int_or_none(width_height[1]),
  245. })
  246. formats.append(f)
  247. return formats
  248. def _real_extract(self, url):
  249. mobj = re.match(self._VALID_URL, url)
  250. domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
  251. video_id = mobj.group('id')
  252. video = None
  253. response = self._download_json(
  254. 'https://arc.nexx.cloud/api/video/%s.json' % video_id,
  255. video_id, fatal=False)
  256. if response and isinstance(response, dict):
  257. result = response.get('result')
  258. if result and isinstance(result, dict):
  259. video = result
  260. # not all videos work via arc, e.g. nexx:741:1269984
  261. if not video:
  262. # Reverse engineered from JS code (see getDeviceID function)
  263. device_id = '%d:%d:%d%d' % (
  264. random.randint(1, 4), int(time.time()),
  265. random.randint(1e4, 99999), random.randint(1, 9))
  266. result = self._call_api(domain_id, 'session/init', video_id, data={
  267. 'nxp_devh': device_id,
  268. 'nxp_userh': '',
  269. 'precid': '0',
  270. 'playlicense': '0',
  271. 'screenx': '1920',
  272. 'screeny': '1080',
  273. 'playerversion': '6.0.00',
  274. 'gateway': 'html5',
  275. 'adGateway': '',
  276. 'explicitlanguage': 'en-US',
  277. 'addTextTemplates': '1',
  278. 'addDomainData': '1',
  279. 'addAdModel': '1',
  280. }, headers={
  281. 'X-Request-Enable-Auth-Fallback': '1',
  282. })
  283. cid = result['general']['cid']
  284. # As described in [1] X-Request-Token generation algorithm is
  285. # as follows:
  286. # md5( operation + domain_id + domain_secret )
  287. # where domain_secret is a static value that will be given by nexx.tv
  288. # as per [1]. Here is how this "secret" is generated (reversed
  289. # from _play.api.init function, search for clienttoken). So it's
  290. # actually not static and not that much of a secret.
  291. # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
  292. secret = result['device']['clienttoken'][int(device_id[0]):]
  293. secret = secret[0:len(secret) - int(device_id[-1])]
  294. op = 'byid'
  295. # Reversed from JS code for _play.api.call function (search for
  296. # X-Request-Token)
  297. request_token = hashlib.md5(
  298. ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
  299. video = self._call_api(
  300. domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
  301. 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
  302. 'addInteractionOptions': '1',
  303. 'addStatusDetails': '1',
  304. 'addStreamDetails': '1',
  305. 'addCaptions': '1',
  306. 'addScenes': '1',
  307. 'addHotSpots': '1',
  308. 'addBumpers': '1',
  309. 'captionFormat': 'data',
  310. }, headers={
  311. 'X-Request-CID': cid,
  312. 'X-Request-Token': request_token,
  313. })
  314. general = video['general']
  315. title = general['title']
  316. cdn = video['streamdata']['cdnType']
  317. if cdn == 'azure':
  318. formats = self._extract_azure_formats(video, video_id)
  319. elif cdn == 'free':
  320. formats = self._extract_free_formats(video, video_id)
  321. else:
  322. # TODO: reverse more cdns
  323. assert False
  324. self._sort_formats(formats)
  325. return {
  326. 'id': video_id,
  327. 'title': title,
  328. 'alt_title': general.get('subtitle'),
  329. 'description': general.get('description'),
  330. 'release_year': int_or_none(general.get('year')),
  331. 'creator': general.get('studio') or general.get('studio_adref'),
  332. 'thumbnail': try_get(
  333. video, lambda x: x['imagedata']['thumb'], compat_str),
  334. 'duration': parse_duration(general.get('runtime')),
  335. 'timestamp': int_or_none(general.get('uploaded')),
  336. 'episode_number': int_or_none(try_get(
  337. video, lambda x: x['episodedata']['episode'])),
  338. 'season_number': int_or_none(try_get(
  339. video, lambda x: x['episodedata']['season'])),
  340. 'formats': formats,
  341. }
  342. class NexxEmbedIE(InfoExtractor):
  343. _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
  344. _TEST = {
  345. 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
  346. 'md5': '16746bfc28c42049492385c989b26c4a',
  347. 'info_dict': {
  348. 'id': '161464',
  349. 'ext': 'mp4',
  350. 'title': 'Nervenkitzel Achterbahn',
  351. 'alt_title': 'Karussellbauer in Deutschland',
  352. 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
  353. 'release_year': 2005,
  354. 'creator': 'SPIEGEL TV',
  355. 'thumbnail': r're:^https?://.*\.jpg$',
  356. 'duration': 2761,
  357. 'timestamp': 1394021479,
  358. 'upload_date': '20140305',
  359. },
  360. 'params': {
  361. 'format': 'bestvideo',
  362. 'skip_download': True,
  363. },
  364. }
  365. @staticmethod
  366. def _extract_urls(webpage):
  367. # Reference:
  368. # 1. https://nx-s.akamaized.net/files/201510/44.pdf
  369. # iFrame Embed Integration
  370. return [mobj.group('url') for mobj in re.finditer(
  371. r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
  372. webpage)]
  373. def _real_extract(self, url):
  374. embed_id = self._match_id(url)
  375. webpage = self._download_webpage(url, embed_id)
  376. return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())