nexx.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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'https?://api\.nexx(?:\.cloud|cdn\.com)/v3/(?P<domain_id>\d+)/videos/byid/(?P<id>\d+)'
  18. _TESTS = [{
  19. # movie
  20. 'url': 'https://api.nexx.cloud/v3/748/videos/byid/128907',
  21. 'md5': '16746bfc28c42049492385c989b26c4a',
  22. 'info_dict': {
  23. 'id': '128907',
  24. 'ext': 'mp4',
  25. 'title': 'Stiftung Warentest',
  26. 'alt_title': 'Wie ein Test abläuft',
  27. 'description': 'md5:d1ddb1ef63de721132abd38639cc2fd2',
  28. 'release_year': 2013,
  29. 'creator': 'SPIEGEL TV',
  30. 'thumbnail': r're:^https?://.*\.jpg$',
  31. 'duration': 2509,
  32. 'timestamp': 1384264416,
  33. 'upload_date': '20131112',
  34. },
  35. 'params': {
  36. 'format': 'bestvideo',
  37. },
  38. }, {
  39. # episode
  40. 'url': 'https://api.nexx.cloud/v3/741/videos/byid/247858',
  41. 'info_dict': {
  42. 'id': '247858',
  43. 'ext': 'mp4',
  44. 'title': 'Return of the Golden Child (OV)',
  45. 'description': 'md5:5d969537509a92b733de21bae249dc63',
  46. 'release_year': 2017,
  47. 'thumbnail': r're:^https?://.*\.jpg$',
  48. 'duration': 1397,
  49. 'timestamp': 1495033267,
  50. 'upload_date': '20170517',
  51. 'episode_number': 2,
  52. 'season_number': 2,
  53. },
  54. 'params': {
  55. 'format': 'bestvideo',
  56. 'skip_download': True,
  57. },
  58. }, {
  59. 'url': 'https://api.nexxcdn.com/v3/748/videos/byid/128907',
  60. 'only_matching': True,
  61. }]
  62. @staticmethod
  63. def _extract_urls(webpage):
  64. # Reference:
  65. # 1. https://nx-s.akamaized.net/files/201510/44.pdf
  66. entries = []
  67. # JavaScript Integration
  68. mobj = re.search(
  69. r'<script\b[^>]+\bsrc=["\']https?://require\.nexx(?:\.cloud|cdn\.com)/(?P<id>\d+)',
  70. webpage)
  71. if mobj:
  72. domain_id = mobj.group('id')
  73. for video_id in re.findall(
  74. r'(?is)onPLAYReady.+?_play\.init\s*\(.+?\s*,\s*["\']?(\d+)',
  75. webpage):
  76. entries.append(
  77. 'https://api.nexx.cloud/v3/%s/videos/byid/%s'
  78. % (domain_id, video_id))
  79. # TODO: support more embed formats
  80. return entries
  81. def _handle_error(self, response):
  82. status = int_or_none(try_get(
  83. response, lambda x: x['metadata']['status']) or 200)
  84. if 200 <= status < 300:
  85. return
  86. raise ExtractorError(
  87. '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
  88. expected=True)
  89. def _call_api(self, domain_id, path, video_id, data=None, headers={}):
  90. headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  91. result = self._download_json(
  92. 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
  93. 'Downloading %s JSON' % path, data=urlencode_postdata(data),
  94. headers=headers)
  95. self._handle_error(result)
  96. return result['result']
  97. def _real_extract(self, url):
  98. mobj = re.match(self._VALID_URL, url)
  99. domain_id, video_id = mobj.group('domain_id', 'id')
  100. # Reverse engineered from JS code (see getDeviceID function)
  101. device_id = '%d:%d:%d%d' % (
  102. random.randint(1, 4), int(time.time()),
  103. random.randint(1e4, 99999), random.randint(1, 9))
  104. result = self._call_api(domain_id, 'session/init', video_id, data={
  105. 'nxp_devh': device_id,
  106. 'nxp_userh': '',
  107. 'precid': '0',
  108. 'playlicense': '0',
  109. 'screenx': '1920',
  110. 'screeny': '1080',
  111. 'playerversion': '6.0.00',
  112. 'gateway': 'html5',
  113. 'adGateway': '',
  114. 'explicitlanguage': 'en-US',
  115. 'addTextTemplates': '1',
  116. 'addDomainData': '1',
  117. 'addAdModel': '1',
  118. }, headers={
  119. 'X-Request-Enable-Auth-Fallback': '1',
  120. })
  121. cid = result['general']['cid']
  122. # As described in [1] X-Request-Token generation algorithm is
  123. # as follows:
  124. # md5( operation + domain_id + domain_secret )
  125. # where domain_secret is a static value that will be given by nexx.tv
  126. # as per [1]. Here is how this "secret" is generated (reversed
  127. # from _play.api.init function, search for clienttoken). So it's
  128. # actually not static and not that much of a secret.
  129. # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
  130. secret = result['device']['clienttoken'][int(device_id[0]):]
  131. secret = secret[0:len(secret) - int(device_id[-1])]
  132. op = 'byid'
  133. # Reversed from JS code for _play.api.call function (search for
  134. # X-Request-Token)
  135. request_token = hashlib.md5(
  136. ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
  137. video = self._call_api(
  138. domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
  139. 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
  140. 'addInteractionOptions': '1',
  141. 'addStatusDetails': '1',
  142. 'addStreamDetails': '1',
  143. 'addCaptions': '1',
  144. 'addScenes': '1',
  145. 'addHotSpots': '1',
  146. 'addBumpers': '1',
  147. 'captionFormat': 'data',
  148. }, headers={
  149. 'X-Request-CID': cid,
  150. 'X-Request-Token': request_token,
  151. })
  152. general = video['general']
  153. title = general['title']
  154. stream_data = video['streamdata']
  155. language = general.get('language_raw') or ''
  156. # TODO: reverse more cdns and formats
  157. cdn = stream_data['cdnType']
  158. assert cdn == 'azure'
  159. azure_locator = stream_data['azureLocator']
  160. AZURE_URL = 'http://nx-p%02d.akamaized.net/'
  161. for secure in ('s', ''):
  162. cdn_shield = stream_data.get('cdnShieldHTTP%s' % secure.upper())
  163. if cdn_shield:
  164. azure_base = 'http%s://%s' % (secure, cdn_shield)
  165. break
  166. else:
  167. azure_base = AZURE_URL % int(stream_data['azureAccount'].replace('nexxplayplus', ''))
  168. is_ml = ',' in language
  169. azure_m3u8_url = '%s%s/%s_src%s.ism/Manifest(format=m3u8-aapl)' % (
  170. azure_base, azure_locator, video_id, ('_manifest' if is_ml else ''))
  171. protection_token = try_get(
  172. video, lambda x: x['protectiondata']['token'], compat_str)
  173. if protection_token:
  174. azure_m3u8_url += '?hdnts=%s' % protection_token
  175. formats = self._extract_m3u8_formats(
  176. azure_m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native',
  177. m3u8_id='%s-hls' % cdn)
  178. self._sort_formats(formats)
  179. return {
  180. 'id': video_id,
  181. 'title': title,
  182. 'alt_title': general.get('subtitle'),
  183. 'description': general.get('description'),
  184. 'release_year': int_or_none(general.get('year')),
  185. 'creator': general.get('studio') or general.get('studio_adref'),
  186. 'thumbnail': try_get(
  187. video, lambda x: x['imagedata']['thumb'], compat_str),
  188. 'duration': parse_duration(general.get('runtime')),
  189. 'timestamp': int_or_none(general.get('uploaded')),
  190. 'episode_number': int_or_none(try_get(
  191. video, lambda x: x['episodedata']['episode'])),
  192. 'season_number': int_or_none(try_get(
  193. video, lambda x: x['episodedata']['season'])),
  194. 'formats': formats,
  195. }