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.

201 lines
7.2 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import hashlib
  4. import hmac
  5. import time
  6. import uuid
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_HTTPError,
  10. compat_str,
  11. )
  12. from ..utils import (
  13. determine_ext,
  14. ExtractorError,
  15. int_or_none,
  16. str_or_none,
  17. try_get,
  18. url_or_none,
  19. )
  20. class HotStarBaseIE(InfoExtractor):
  21. _AKAMAI_ENCRYPTION_KEY = b'\x05\xfc\x1a\x01\xca\xc9\x4b\xc4\x12\xfc\x53\x12\x07\x75\xf9\xee'
  22. def _call_api_impl(self, path, video_id, query):
  23. st = int(time.time())
  24. exp = st + 6000
  25. auth = 'st=%d~exp=%d~acl=/*' % (st, exp)
  26. auth += '~hmac=' + hmac.new(self._AKAMAI_ENCRYPTION_KEY, auth.encode(), hashlib.sha256).hexdigest()
  27. response = self._download_json(
  28. 'https://api.hotstar.com/' + path, video_id, headers={
  29. 'hotstarauth': auth,
  30. 'x-country-code': 'IN',
  31. 'x-platform-code': 'JIO',
  32. }, query=query)
  33. if response['statusCode'] != 'OK':
  34. raise ExtractorError(
  35. response['body']['message'], expected=True)
  36. return response['body']['results']
  37. def _call_api(self, path, video_id, query_name='contentId'):
  38. return self._call_api_impl(path, video_id, {
  39. query_name: video_id,
  40. 'tas': 10000,
  41. })
  42. def _call_api_v2(self, path, video_id):
  43. return self._call_api_impl(
  44. '%s/in/contents/%s' % (path, video_id), video_id, {
  45. 'desiredConfig': 'encryption:plain;ladder:phone,tv;package:hls,dash',
  46. 'client': 'mweb',
  47. 'clientVersion': '6.18.0',
  48. 'deviceId': compat_str(uuid.uuid4()),
  49. 'osName': 'Windows',
  50. 'osVersion': '10',
  51. })
  52. class HotStarIE(HotStarBaseIE):
  53. IE_NAME = 'hotstar'
  54. _VALID_URL = r'https?://(?:www\.)?hotstar\.com/(?:.+?[/-])?(?P<id>\d{10})'
  55. _TESTS = [{
  56. # contentData
  57. 'url': 'https://www.hotstar.com/can-you-not-spread-rumours/1000076273',
  58. 'info_dict': {
  59. 'id': '1000076273',
  60. 'ext': 'mp4',
  61. 'title': 'Can You Not Spread Rumours?',
  62. 'description': 'md5:c957d8868e9bc793ccb813691cc4c434',
  63. 'timestamp': 1447248600,
  64. 'upload_date': '20151111',
  65. 'duration': 381,
  66. },
  67. 'params': {
  68. # m3u8 download
  69. 'skip_download': True,
  70. }
  71. }, {
  72. # contentDetail
  73. 'url': 'https://www.hotstar.com/movies/radha-gopalam/1000057157',
  74. 'only_matching': True,
  75. }, {
  76. 'url': 'http://www.hotstar.com/sports/cricket/rajitha-sizzles-on-debut-with-329/2001477583',
  77. 'only_matching': True,
  78. }, {
  79. 'url': 'http://www.hotstar.com/1000000515',
  80. 'only_matching': True,
  81. }, {
  82. # only available via api v2
  83. 'url': 'https://www.hotstar.com/tv/ek-bhram-sarvagun-sampanna/s-2116/janhvi-targets-suman/1000234847',
  84. 'only_matching': True,
  85. }]
  86. _GEO_BYPASS = False
  87. def _real_extract(self, url):
  88. video_id = self._match_id(url)
  89. webpage = self._download_webpage(url, video_id)
  90. app_state = self._parse_json(self._search_regex(
  91. r'<script>window\.APP_STATE\s*=\s*({.+?})</script>',
  92. webpage, 'app state'), video_id)
  93. video_data = {}
  94. getters = list(
  95. lambda x, k=k: x['initialState']['content%s' % k]['content']
  96. for k in ('Data', 'Detail')
  97. )
  98. for v in app_state.values():
  99. content = try_get(v, getters, dict)
  100. if content and content.get('contentId') == video_id:
  101. video_data = content
  102. break
  103. title = video_data['title']
  104. if video_data.get('drmProtected'):
  105. raise ExtractorError('This video is DRM protected.', expected=True)
  106. formats = []
  107. geo_restricted = False
  108. playback_sets = self._call_api_v2('h/v2/play', video_id)['playBackSets']
  109. for playback_set in playback_sets:
  110. if not isinstance(playback_set, dict):
  111. continue
  112. format_url = url_or_none(playback_set.get('playbackUrl'))
  113. if not format_url:
  114. continue
  115. tags = str_or_none(playback_set.get('tagsCombination')) or ''
  116. if tags and 'encryption:plain' not in tags:
  117. continue
  118. ext = determine_ext(format_url)
  119. try:
  120. if 'package:hls' in tags or ext == 'm3u8':
  121. formats.extend(self._extract_m3u8_formats(
  122. format_url, video_id, 'mp4', m3u8_id='hls'))
  123. elif 'package:dash' in tags or ext == 'mpd':
  124. formats.extend(self._extract_mpd_formats(
  125. format_url, video_id, mpd_id='dash'))
  126. elif ext == 'f4m':
  127. # produce broken files
  128. pass
  129. else:
  130. formats.append({
  131. 'url': format_url,
  132. 'width': int_or_none(playback_set.get('width')),
  133. 'height': int_or_none(playback_set.get('height')),
  134. })
  135. except ExtractorError as e:
  136. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  137. geo_restricted = True
  138. continue
  139. if not formats and geo_restricted:
  140. self.raise_geo_restricted(countries=['IN'])
  141. self._sort_formats(formats)
  142. return {
  143. 'id': video_id,
  144. 'title': title,
  145. 'description': video_data.get('description'),
  146. 'duration': int_or_none(video_data.get('duration')),
  147. 'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
  148. 'formats': formats,
  149. 'channel': video_data.get('channelName'),
  150. 'channel_id': video_data.get('channelId'),
  151. 'series': video_data.get('showName'),
  152. 'season': video_data.get('seasonName'),
  153. 'season_number': int_or_none(video_data.get('seasonNo')),
  154. 'season_id': video_data.get('seasonId'),
  155. 'episode': title,
  156. 'episode_number': int_or_none(video_data.get('episodeNo')),
  157. }
  158. class HotStarPlaylistIE(HotStarBaseIE):
  159. IE_NAME = 'hotstar:playlist'
  160. _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)'
  161. _TESTS = [{
  162. 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
  163. 'info_dict': {
  164. 'id': '3_2_26',
  165. },
  166. 'playlist_mincount': 20,
  167. }, {
  168. 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
  169. 'only_matching': True,
  170. }]
  171. def _real_extract(self, url):
  172. playlist_id = self._match_id(url)
  173. collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')
  174. entries = [
  175. self.url_result(
  176. 'https://www.hotstar.com/%s' % video['contentId'],
  177. ie=HotStarIE.ie_key(), video_id=video['contentId'])
  178. for video in collection['assets']['items']
  179. if video.get('contentId')]
  180. return self.playlist_result(entries, playlist_id)