You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

453 lines
17 KiB

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