hotstar.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. formats = []
  108. geo_restricted = False
  109. playback_sets = self._call_api_v2('h/v2/play', video_id)['playBackSets']
  110. for playback_set in playback_sets:
  111. if not isinstance(playback_set, dict):
  112. continue
  113. format_url = url_or_none(playback_set.get('playbackUrl'))
  114. if not format_url:
  115. continue
  116. format_url = re.sub(
  117. r'(?<=//staragvod)(\d)', r'web\1', format_url)
  118. tags = str_or_none(playback_set.get('tagsCombination')) or ''
  119. if tags and 'encryption:plain' not in tags:
  120. continue
  121. ext = determine_ext(format_url)
  122. try:
  123. if 'package:hls' in tags or ext == 'm3u8':
  124. formats.extend(self._extract_m3u8_formats(
  125. format_url, video_id, 'mp4', m3u8_id='hls'))
  126. elif 'package:dash' in tags or ext == 'mpd':
  127. formats.extend(self._extract_mpd_formats(
  128. format_url, video_id, mpd_id='dash'))
  129. elif ext == 'f4m':
  130. # produce broken files
  131. pass
  132. else:
  133. formats.append({
  134. 'url': format_url,
  135. 'width': int_or_none(playback_set.get('width')),
  136. 'height': int_or_none(playback_set.get('height')),
  137. })
  138. except ExtractorError as e:
  139. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  140. geo_restricted = True
  141. continue
  142. if not formats and geo_restricted:
  143. self.raise_geo_restricted(countries=['IN'])
  144. self._sort_formats(formats)
  145. return {
  146. 'id': video_id,
  147. 'title': title,
  148. 'description': video_data.get('description'),
  149. 'duration': int_or_none(video_data.get('duration')),
  150. 'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
  151. 'formats': formats,
  152. 'channel': video_data.get('channelName'),
  153. 'channel_id': video_data.get('channelId'),
  154. 'series': video_data.get('showName'),
  155. 'season': video_data.get('seasonName'),
  156. 'season_number': int_or_none(video_data.get('seasonNo')),
  157. 'season_id': video_data.get('seasonId'),
  158. 'episode': title,
  159. 'episode_number': int_or_none(video_data.get('episodeNo')),
  160. }
  161. class HotStarPlaylistIE(HotStarBaseIE):
  162. IE_NAME = 'hotstar:playlist'
  163. _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)'
  164. _TESTS = [{
  165. 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
  166. 'info_dict': {
  167. 'id': '3_2_26',
  168. },
  169. 'playlist_mincount': 20,
  170. }, {
  171. 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
  172. 'only_matching': True,
  173. }]
  174. def _real_extract(self, url):
  175. playlist_id = self._match_id(url)
  176. collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')
  177. entries = [
  178. self.url_result(
  179. 'https://www.hotstar.com/%s' % video['contentId'],
  180. ie=HotStarIE.ie_key(), video_id=video['contentId'])
  181. for video in collection['assets']['items']
  182. if video.get('contentId')]
  183. return self.playlist_result(entries, playlist_id)