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.

210 lines
7.5 KiB

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