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.

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