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.

271 lines
9.4 KiB

  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. @staticmethod
  82. def _extract_url(webpage):
  83. return NexxIE._extract_urls(webpage)[0]
  84. def _handle_error(self, response):
  85. status = int_or_none(try_get(
  86. response, lambda x: x['metadata']['status']) or 200)
  87. if 200 <= status < 300:
  88. return
  89. raise ExtractorError(
  90. '%s said: %s' % (self.IE_NAME, response['metadata']['errorhint']),
  91. expected=True)
  92. def _call_api(self, domain_id, path, video_id, data=None, headers={}):
  93. headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  94. result = self._download_json(
  95. 'https://api.nexx.cloud/v3/%s/%s' % (domain_id, path), video_id,
  96. 'Downloading %s JSON' % path, data=urlencode_postdata(data),
  97. headers=headers)
  98. self._handle_error(result)
  99. return result['result']
  100. def _real_extract(self, url):
  101. mobj = re.match(self._VALID_URL, url)
  102. domain_id, video_id = mobj.group('domain_id', 'id')
  103. # Reverse engineered from JS code (see getDeviceID function)
  104. device_id = '%d:%d:%d%d' % (
  105. random.randint(1, 4), int(time.time()),
  106. random.randint(1e4, 99999), random.randint(1, 9))
  107. result = self._call_api(domain_id, 'session/init', video_id, data={
  108. 'nxp_devh': device_id,
  109. 'nxp_userh': '',
  110. 'precid': '0',
  111. 'playlicense': '0',
  112. 'screenx': '1920',
  113. 'screeny': '1080',
  114. 'playerversion': '6.0.00',
  115. 'gateway': 'html5',
  116. 'adGateway': '',
  117. 'explicitlanguage': 'en-US',
  118. 'addTextTemplates': '1',
  119. 'addDomainData': '1',
  120. 'addAdModel': '1',
  121. }, headers={
  122. 'X-Request-Enable-Auth-Fallback': '1',
  123. })
  124. cid = result['general']['cid']
  125. # As described in [1] X-Request-Token generation algorithm is
  126. # as follows:
  127. # md5( operation + domain_id + domain_secret )
  128. # where domain_secret is a static value that will be given by nexx.tv
  129. # as per [1]. Here is how this "secret" is generated (reversed
  130. # from _play.api.init function, search for clienttoken). So it's
  131. # actually not static and not that much of a secret.
  132. # 1. https://nexxtvstorage.blob.core.windows.net/files/201610/27.pdf
  133. secret = result['device']['clienttoken'][int(device_id[0]):]
  134. secret = secret[0:len(secret) - int(device_id[-1])]
  135. op = 'byid'
  136. # Reversed from JS code for _play.api.call function (search for
  137. # X-Request-Token)
  138. request_token = hashlib.md5(
  139. ''.join((op, domain_id, secret)).encode('utf-8')).hexdigest()
  140. video = self._call_api(
  141. domain_id, 'videos/%s/%s' % (op, video_id), video_id, data={
  142. 'additionalfields': 'language,channel,actors,studio,licenseby,slug,subtitle,teaser,description',
  143. 'addInteractionOptions': '1',
  144. 'addStatusDetails': '1',
  145. 'addStreamDetails': '1',
  146. 'addCaptions': '1',
  147. 'addScenes': '1',
  148. 'addHotSpots': '1',
  149. 'addBumpers': '1',
  150. 'captionFormat': 'data',
  151. }, headers={
  152. 'X-Request-CID': cid,
  153. 'X-Request-Token': request_token,
  154. })
  155. general = video['general']
  156. title = general['title']
  157. stream_data = video['streamdata']
  158. language = general.get('language_raw') or ''
  159. # TODO: reverse more cdns and formats
  160. cdn = stream_data['cdnType']
  161. assert cdn == 'azure'
  162. azure_locator = stream_data['azureLocator']
  163. AZURE_URL = 'http://nx-p%02d.akamaized.net/'
  164. for secure in ('s', ''):
  165. cdn_shield = stream_data.get('cdnShieldHTTP%s' % secure.upper())
  166. if cdn_shield:
  167. azure_base = 'http%s://%s' % (secure, cdn_shield)
  168. break
  169. else:
  170. azure_base = AZURE_URL % int(stream_data['azureAccount'].replace('nexxplayplus', ''))
  171. is_ml = ',' in language
  172. azure_m3u8_url = '%s%s/%s_src%s.ism/Manifest(format=m3u8-aapl)' % (
  173. azure_base, azure_locator, video_id, ('_manifest' if is_ml else ''))
  174. protection_token = try_get(
  175. video, lambda x: x['protectiondata']['token'], compat_str)
  176. if protection_token:
  177. azure_m3u8_url += '?hdnts=%s' % protection_token
  178. formats = self._extract_m3u8_formats(
  179. azure_m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native',
  180. m3u8_id='%s-hls' % cdn)
  181. self._sort_formats(formats)
  182. return {
  183. 'id': video_id,
  184. 'title': title,
  185. 'alt_title': general.get('subtitle'),
  186. 'description': general.get('description'),
  187. 'release_year': int_or_none(general.get('year')),
  188. 'creator': general.get('studio') or general.get('studio_adref'),
  189. 'thumbnail': try_get(
  190. video, lambda x: x['imagedata']['thumb'], compat_str),
  191. 'duration': parse_duration(general.get('runtime')),
  192. 'timestamp': int_or_none(general.get('uploaded')),
  193. 'episode_number': int_or_none(try_get(
  194. video, lambda x: x['episodedata']['episode'])),
  195. 'season_number': int_or_none(try_get(
  196. video, lambda x: x['episodedata']['season'])),
  197. 'formats': formats,
  198. }
  199. class NexxEmbedIE(InfoExtractor):
  200. _VALID_URL = r'https?://embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?P<id>[^/?#&]+)'
  201. _TEST = {
  202. 'url': 'http://embed.nexx.cloud/748/KC1614647Z27Y7T?autoplay=1',
  203. 'md5': '16746bfc28c42049492385c989b26c4a',
  204. 'info_dict': {
  205. 'id': '161464',
  206. 'ext': 'mp4',
  207. 'title': 'Nervenkitzel Achterbahn',
  208. 'alt_title': 'Karussellbauer in Deutschland',
  209. 'description': 'md5:ffe7b1cc59a01f585e0569949aef73cc',
  210. 'release_year': 2005,
  211. 'creator': 'SPIEGEL TV',
  212. 'thumbnail': r're:^https?://.*\.jpg$',
  213. 'duration': 2761,
  214. 'timestamp': 1394021479,
  215. 'upload_date': '20140305',
  216. },
  217. 'params': {
  218. 'format': 'bestvideo',
  219. 'skip_download': True,
  220. },
  221. }
  222. @staticmethod
  223. def _extract_urls(webpage):
  224. # Reference:
  225. # 1. https://nx-s.akamaized.net/files/201510/44.pdf
  226. # iFrame Embed Integration
  227. return [mobj.group('url') for mobj in re.finditer(
  228. r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//embed\.nexx(?:\.cloud|cdn\.com)/\d+/(?:(?!\1).)+)\1',
  229. webpage)]
  230. def _real_extract(self, url):
  231. embed_id = self._match_id(url)
  232. webpage = self._download_webpage(url, embed_id)
  233. return self.url_result(NexxIE._extract_url(webpage), ie=NexxIE.ie_key())