nexx.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. 'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
  78. 'only_matching': True,
  79. }, {
  80. 'url': 'nexx:748:128907',
  81. 'only_matching': True,
  82. }, {
  83. 'url': 'nexx:128907',
  84. 'only_matching': True,
  85. }, {
  86. 'url': 'https://arc.nexx.cloud/api/video/128907.json',
  87. 'only_matching': True,
  88. }]
  89. @staticmethod
  90. def _extract_domain_id(webpage):
  91. mobj = re.search(
  92. r'<script\b[^>]+\bsrc=["\'](?:https?:)?//require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
  93. webpage)
  94. return mobj.group('id') if mobj else None
  95. @staticmethod
  96. def _extract_urls(webpage):
  97. # Reference:
  98. # 1. https://nx-s.akamaized.net/files/201510/44.pdf
  99. entries = []
  100. # JavaScript Integration
  101. domain_id = NexxIE._extract_domain_id(webpage)
  102. if domain_id:
  103. for video_id in re.findall(
  104. r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
  105. webpage):
  106. entries.append(
  107. 'https://api.nexx.cloud/v3/%s/videos/byid/%s'
  108. % (domain_id, video_id))
  109. # TODO: support more embed formats
  110. return entries
  111. @staticmethod
  112. def _extract_url(webpage):
  113. return NexxIE._extract_urls(webpage)[0]
  114. def _handle_error(self, response):
  115. status = int_or_none(try_get(
  116. response, lambda x: x['metadata']['status']) or 200)
  117. if 200 <= status < 300:
  118. return
  119. raise ExtractorError(
  120. '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
  121. expected=True)
  122. def _call_api(self, domain_id, path, video_id, data=None, headers={}):
  123. headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  124. result = self._download_json(
  125. 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
  126. 'Downloading %s JSON' % path, data=urlencode_postdata(data),
  127. headers=headers)
  128. self._handle_error(result)
  129. return result['result']
  130. def _real_extract(self, url):
  131. mobj = re.match(self._VALID_URL, url)
  132. domain_id = mobj.group('domain_id') or mobj.group('domain_id_s')
  133. video_id = mobj.group('id')
  134. video = None
  135. response = self._download_json(
  136. 'https://arc.nexx.cloud/api/video/%s.json' % video_id,
  137. video_id, fatal=False)
  138. if response and isinstance(response, dict):
  139. result = response.get('result')
  140. if result and isinstance(result, dict):
  141. video = result
  142. # not all videos work via arc, e.g. nexx:741:1269984
  143. if not video:
  144. # Reverse engineered from JS code (see getDeviceID function)
  145. device_id = '%d:%d:%d%d' % (
  146. random.randint(1, 4), int(time.time()),
  147. random.randint(1e4, 99999), random.randint(1, 9))
  148. result = self._call_api(domain_id, 'session/init', video_id, data={
  149. 'nxp_devh': device_id,
  150. 'nxp_userh': '',
  151. 'precid': '0',
  152. 'playlicense': '0',
  153. 'screenx': '1920',
  154. 'screeny': '1080',
  155. 'playerversion': '6.0.00',
  156. 'gateway': 'html5',
  157. 'adGateway': '',
  158. 'explicitlanguage': 'en-US',
  159. 'addTextTemplates': '1',
  160. 'addDomainData': '1',
  161. 'addAdModel': '1',
  162. }, headers={
  163. 'X-Request-Enable-Auth-Fallback': '1',
  164. })
  165. cid = result['general']['cid']
  166. # As described in [1] X-Request-Token generation algorithm is
  167. # as follows:
  168. # md5( operation + domain_id + domain_secret )
  169. # where domain_secret is a static value that will be given by nexx.tv
  170. # as per [1]. Here is how this "secret" is generated (reversed
  171. # from _play.api.init function, search for clienttoken). So it's
  172. # actually not static and not that much of a secret.
  173. # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
  174. secret = result['device']['clienttoken'][int(device_id[0]):]
  175. secret = secret[0:len(secret) - int(device_id[-1])]
  176. op = 'byid'
  177. # Reversed from JS code for _play.api.call function (search for
  178. # X-Request-Token)
  179. request_token = hashlib.md5(
  180. ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
  181. video = self._call_api(
  182. domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
  183. 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
  184. 'addInteractionOptions': '1',
  185. 'addStatusDetails': '1',
  186. 'addStreamDetails': '1',
  187. 'addCaptions': '1',
  188. 'addScenes': '1',
  189. 'addHotSpots': '1',
  190. 'addBumpers': '1',
  191. 'captionFormat': 'data',
  192. }, headers={
  193. 'X-Request-CID': cid,
  194. 'X-Request-Token': request_token,
  195. })
  196. general = video['general']
  197. title = general['title']
  198. stream_data = video['streamdata']
  199. language = general.get('language_raw') or ''
  200. # TODO: reverse more cdns
  201. cdn = stream_data['cdnType']
  202. assert cdn == 'azure'
  203. azure_locator = stream_data['azureLocator']
  204. AZURE_URL = 'http://nx%s%02d.akamaized.net/'
  205. def get_cdn_shield_base(shield_type='', prefix='-p'):
  206. for secure in ('', 's'):
  207. cdn_shield = stream_data.get('cdnShield%sHTTP%s' % (shield_type, secure.upper()))
  208. if cdn_shield:
  209. return 'http%s://%s' % (secure, cdn_shield)
  210. else:
  211. return AZURE_URL % (prefix, int(stream_data['azureAccount'].replace('nexxplayplus', '')))
  212. azure_stream_base = get_cdn_shield_base()
  213. is_ml = ',' in language
  214. azure_manifest_url = '%s%s/%s_src%s.ism/Manifest' % (
  215. azure_stream_base, azure_locator, video_id, ('_manifest' if is_ml else '')) + '%s'
  216. protection_token = try_get(
  217. video, lambda x: x['protectiondata']['token'], compat_str)
  218. if protection_token:
  219. azure_manifest_url += '?hdnts=%s' % protection_token
  220. formats = self._extract_m3u8_formats(
  221. azure_manifest_url % '(format=m3u8-aapl)',
  222. video_id, 'mp4', 'm3u8_native',
  223. m3u8_id='%s-hls' % cdn, fatal=False)
  224. formats.extend(self._extract_mpd_formats(
  225. azure_manifest_url % '(format=mpd-time-csf)',
  226. video_id, mpd_id='%s-dash' % cdn, fatal=False))
  227. formats.extend(self._extract_ism_formats(
  228. azure_manifest_url % '', video_id, ism_id='%s-mss' % cdn, fatal=False))
  229. azure_progressive_base = get_cdn_shield_base('Prog', '-d')
  230. azure_file_distribution = stream_data.get('azureFileDistribution')
  231. if azure_file_distribution:
  232. fds = azure_file_distribution.split(',')
  233. if fds:
  234. for fd in fds:
  235. ss = fd.split(':')
  236. if len(ss) == 2:
  237. tbr = int_or_none(ss[0])
  238. if tbr:
  239. f = {
  240. 'url': '%s%s/%s_src_%s_%d.mp4' % (
  241. azure_progressive_base, azure_locator, video_id, ss[1], tbr),
  242. 'format_id': '%s-http-%d' % (cdn, tbr),
  243. 'tbr': tbr,
  244. }
  245. width_height = ss[1].split('x')
  246. if len(width_height) == 2:
  247. f.update({
  248. 'width': int_or_none(width_height[0]),
  249. 'height': int_or_none(width_height[1]),
  250. })
  251. formats.append(f)
  252. self._sort_formats(formats)
  253. return {
  254. 'id': video_id,
  255. 'title': title,
  256. 'alt_title': general.get('subtitle'),
  257. 'description': general.get('description'),
  258. 'release_year': int_or_none(general.get('year')),
  259. 'creator': general.get('studio') or general.get('studio_adref'),
  260. 'thumbnail': try_get(
  261. video, lambda x: x['imagedata']['thumb'], compat_str),
  262. 'duration': parse_duration(general.get('runtime')),
  263. 'timestamp': int_or_none(general.get('uploaded')),
  264. 'episode_number': int_or_none(try_get(
  265. video, lambda x: x['episodedata']['episode'])),
  266. 'season_number': int_or_none(try_get(
  267. video, lambda x: x['episodedata']['season'])),
  268. 'formats': formats,
  269. }
  270. class NexxEmbedIE(InfoExtractor):
  271. _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
  272. _TEST = {
  273. 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
  274. 'md5': '16746bfc28c42049492385c989b26c4a',
  275. 'info_dict': {
  276. 'id': '161464',
  277. 'ext': 'mp4',
  278. 'title': 'Nervenkitzel Achterbahn',
  279. 'alt_title': 'Karussellbauer in Deutschland',
  280. 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
  281. 'release_year': 2005,
  282. 'creator': 'SPIEGEL TV',
  283. 'thumbnail': r're:^https?://.*\.jpg$',
  284. 'duration': 2761,
  285. 'timestamp': 1394021479,
  286. 'upload_date': '20140305',
  287. },
  288. 'params': {
  289. 'format': 'bestvideo',
  290. 'skip_download': True,
  291. },
  292. }
  293. @staticmethod
  294. def _extract_urls(webpage):
  295. # Reference:
  296. # 1. https://nx-s.akamaized.net/files/201510/44.pdf
  297. # iFrame Embed Integration
  298. return [mobj.group('url') for mobj in re.finditer(
  299. r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
  300. webpage)]
  301. def _real_extract(self, url):
  302. embed_id = self._match_id(url)
  303. webpage = self._download_webpage(url, embed_id)
  304. return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())