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.

440 lines
16 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\.nexx(?:\.cloud|cdn\.com)/(?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\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. response = self._download_json(
  266. 'https://arc.nexx.cloud/api/video/%s.json' % video_id,
  267. video_id, fatal=False)
  268. if response and isinstance(response, dict):
  269. result = response.get('result')
  270. if result and isinstance(result, dict):
  271. video = result
  272. # not all videos work via arc, e.g. nexx:741:1269984
  273. if not video:
  274. # Reverse engineered from JS code (see getDeviceID function)
  275. device_id = '%d:%d:%d%d' % (
  276. random.randint(1, 4), int(time.time()),
  277. random.randint(1e4, 99999), random.randint(1, 9))
  278. result = self._call_api(domain_id, 'session/init', video_id, data={
  279. 'nxp_devh': device_id,
  280. 'nxp_userh': '',
  281. 'precid': '0',
  282. 'playlicense': '0',
  283. 'screenx': '1920',
  284. 'screeny': '1080',
  285. 'playerversion': '6.0.00',
  286. 'gateway': 'html5',
  287. 'adGateway': '',
  288. 'explicitlanguage': 'en-US',
  289. 'addTextTemplates': '1',
  290. 'addDomainData': '1',
  291. 'addAdModel': '1',
  292. }, headers={
  293. 'X-Request-Enable-Auth-Fallback': '1',
  294. })
  295. cid = result['general']['cid']
  296. # As described in [1] X-Request-Token generation algorithm is
  297. # as follows:
  298. # md5( operation + domain_id + domain_secret )
  299. # where domain_secret is a static value that will be given by nexx.tv
  300. # as per [1]. Here is how this "secret" is generated (reversed
  301. # from _play.api.init function, search for clienttoken). So it's
  302. # actually not static and not that much of a secret.
  303. # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
  304. secret = result['device']['clienttoken'][int(device_id[0]):]
  305. secret = secret[0:len(secret) - int(device_id[-1])]
  306. op = 'byid'
  307. # Reversed from JS code for _play.api.call function (search for
  308. # X-Request-Token)
  309. request_token = hashlib.md5(
  310. ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
  311. video = self._call_api(
  312. domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
  313. 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
  314. 'addInteractionOptions': '1',
  315. 'addStatusDetails': '1',
  316. 'addStreamDetails': '1',
  317. 'addCaptions': '1',
  318. 'addScenes': '1',
  319. 'addHotSpots': '1',
  320. 'addBumpers': '1',
  321. 'captionFormat': 'data',
  322. }, headers={
  323. 'X-Request-CID': cid,
  324. 'X-Request-Token': request_token,
  325. })
  326. general = video['general']
  327. title = general['title']
  328. cdn = video['streamdata']['cdnType']
  329. if cdn == 'azure':
  330. formats = self._extract_azure_formats(video, video_id)
  331. elif cdn == 'free':
  332. formats = self._extract_free_formats(video, video_id)
  333. else:
  334. # TODO: reverse more cdns
  335. assert False
  336. self._sort_formats(formats)
  337. return {
  338. 'id': video_id,
  339. 'title': title,
  340. 'alt_title': general.get('subtitle'),
  341. 'description': general.get('description'),
  342. 'release_year': int_or_none(general.get('year')),
  343. 'creator': general.get('studio') or general.get('studio_adref'),
  344. 'thumbnail': try_get(
  345. video, lambda x: x['imagedata']['thumb'], compat_str),
  346. 'duration': parse_duration(general.get('runtime')),
  347. 'timestamp': int_or_none(general.get('uploaded')),
  348. 'episode_number': int_or_none(try_get(
  349. video, lambda x: x['episodedata']['episode'])),
  350. 'season_number': int_or_none(try_get(
  351. video, lambda x: x['episodedata']['season'])),
  352. 'formats': formats,
  353. }
  354. class NexxEmbedIE(InfoExtractor):
  355. _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
  356. _TEST = {
  357. 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
  358. 'md5': '16746bfc28c42049492385c989b26c4a',
  359. 'info_dict': {
  360. 'id': '161464',
  361. 'ext': 'mp4',
  362. 'title': 'Nervenkitzel Achterbahn',
  363. 'alt_title': 'Karussellbauer in Deutschland',
  364. 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
  365. 'release_year': 2005,
  366. 'creator': 'SPIEGEL TV',
  367. 'thumbnail': r're:^https?://.*\.jpg$',
  368. 'duration': 2761,
  369. 'timestamp': 1394021479,
  370. 'upload_date': '20140305',
  371. },
  372. 'params': {
  373. 'format': 'bestvideo',
  374. 'skip_download': True,
  375. },
  376. }
  377. @staticmethod
  378. def _extract_urls(webpage):
  379. # Reference:
  380. # 1. https://nx-s.akamaized.net/files/201510/44.pdf
  381. # iFrame Embed Integration
  382. return [mobj.group('url') for mobj in re.finditer(
  383. r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
  384. webpage)]
  385. def _real_extract(self, url):
  386. embed_id = self._match_id(url)
  387. webpage = self._download_webpage(url, embed_id)
  388. return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())