hotstar.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import hashlib
  2. import hmac
  3. import json
  4. import re
  5. import time
  6. import uuid
  7. from .common import InfoExtractor
  8. from ..compat import compat_HTTPError, compat_str
  9. from ..utils import (
  10. ExtractorError,
  11. determine_ext,
  12. int_or_none,
  13. join_nonempty,
  14. str_or_none,
  15. traverse_obj,
  16. url_or_none,
  17. )
  18. class HotStarBaseIE(InfoExtractor):
  19. _BASE_URL = 'https://www.hotstar.com'
  20. _API_URL = 'https://api.hotstar.com'
  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_v1(self, path, *args, **kwargs):
  23. return self._download_json(
  24. f'{self._API_URL}/o/v1/{path}', *args, **kwargs,
  25. headers={'x-country-code': 'IN', 'x-platform-code': 'PCTV'})
  26. def _call_api_impl(self, path, video_id, query, st=None, cookies=None):
  27. st = int_or_none(st) or int(time.time())
  28. exp = st + 6000
  29. auth = 'st=%d~exp=%d~acl=/*' % (st, exp)
  30. auth += '~hmac=' + hmac.new(self._AKAMAI_ENCRYPTION_KEY, auth.encode(), hashlib.sha256).hexdigest()
  31. if cookies and cookies.get('userUP'):
  32. token = cookies.get('userUP').value
  33. else:
  34. token = self._download_json(
  35. f'{self._API_URL}/um/v3/users',
  36. video_id, note='Downloading token',
  37. data=json.dumps({"device_ids": [{"id": compat_str(uuid.uuid4()), "type": "device_id"}]}).encode('utf-8'),
  38. headers={
  39. 'hotstarauth': auth,
  40. 'x-hs-platform': 'PCTV', # or 'web'
  41. 'Content-Type': 'application/json',
  42. })['user_identity']
  43. response = self._download_json(
  44. f'{self._API_URL}/{path}', video_id, query=query,
  45. headers={
  46. 'hotstarauth': auth,
  47. 'x-hs-appversion': '6.72.2',
  48. 'x-hs-platform': 'web',
  49. 'x-hs-usertoken': token,
  50. })
  51. if response['message'] != "Playback URL's fetched successfully":
  52. raise ExtractorError(
  53. response['message'], expected=True)
  54. return response['data']
  55. def _call_api_v2(self, path, video_id, st=None, cookies=None):
  56. return self._call_api_impl(
  57. f'{path}/content/{video_id}', video_id, st=st, cookies=cookies, query={
  58. 'desired-config': 'audio_channel:stereo|container:fmp4|dynamic_range:hdr|encryption:plain|ladder:tv|package:dash|resolution:fhd|subs-tag:HotstarVIP|video_codec:h265',
  59. 'device-id': cookies.get('device_id').value if cookies.get('device_id') else compat_str(uuid.uuid4()),
  60. 'os-name': 'Windows',
  61. 'os-version': '10',
  62. })
  63. def _playlist_entries(self, path, item_id, root=None, **kwargs):
  64. results = self._call_api_v1(path, item_id, **kwargs)['body']['results']
  65. for video in traverse_obj(results, (('assets', None), 'items', ...)):
  66. if video.get('contentId'):
  67. yield self.url_result(
  68. HotStarIE._video_url(video['contentId'], root=root), HotStarIE, video['contentId'])
  69. class HotStarIE(HotStarBaseIE):
  70. IE_NAME = 'hotstar'
  71. _VALID_URL = r'''(?x)
  72. https?://(?:www\.)?hotstar\.com(?:/in)?/(?!in/)
  73. (?:
  74. (?P<type>movies|sports|episode|(?P<tv>tv))/
  75. (?(tv)(?:[^/?#]+/){2}|[^?#]*)
  76. )?
  77. [^/?#]+/
  78. (?P<id>\d{10})
  79. '''
  80. _TESTS = [{
  81. 'url': 'https://www.hotstar.com/can-you-not-spread-rumours/1000076273',
  82. 'info_dict': {
  83. 'id': '1000076273',
  84. 'ext': 'mp4',
  85. 'title': 'Can You Not Spread Rumours?',
  86. 'description': 'md5:c957d8868e9bc793ccb813691cc4c434',
  87. 'timestamp': 1447248600,
  88. 'upload_date': '20151111',
  89. 'duration': 381,
  90. 'episode': 'Can You Not Spread Rumours?',
  91. },
  92. 'params': {'skip_download': 'm3u8'},
  93. }, {
  94. 'url': 'https://www.hotstar.com/tv/ek-bhram-sarvagun-sampanna/s-2116/janhvi-targets-suman/1000234847',
  95. 'info_dict': {
  96. 'id': '1000234847',
  97. 'ext': 'mp4',
  98. 'title': 'Janhvi Targets Suman',
  99. 'description': 'md5:78a85509348910bd1ca31be898c5796b',
  100. 'timestamp': 1556670600,
  101. 'upload_date': '20190501',
  102. 'duration': 1219,
  103. 'channel': 'StarPlus',
  104. 'channel_id': 3,
  105. 'series': 'Ek Bhram - Sarvagun Sampanna',
  106. 'season': 'Chapter 1',
  107. 'season_number': 1,
  108. 'season_id': 6771,
  109. 'episode': 'Janhvi Targets Suman',
  110. 'episode_number': 8,
  111. }
  112. }, {
  113. 'url': 'https://www.hotstar.com/movies/radha-gopalam/1000057157',
  114. 'only_matching': True,
  115. }, {
  116. 'url': 'https://www.hotstar.com/in/sports/cricket/follow-the-blues-2021/recap-eng-fight-back-on-day-2/1260066104',
  117. 'only_matching': True,
  118. }, {
  119. 'url': 'https://www.hotstar.com/in/sports/football/most-costly-pl-transfers-ft-grealish/1260065956',
  120. 'only_matching': True,
  121. }]
  122. _GEO_BYPASS = False
  123. _TYPE = {
  124. 'movies': 'movie',
  125. 'sports': 'match',
  126. 'episode': 'episode',
  127. 'tv': 'episode',
  128. None: 'content',
  129. }
  130. _IGNORE_MAP = {
  131. 'res': 'resolution',
  132. 'vcodec': 'video_codec',
  133. 'dr': 'dynamic_range',
  134. }
  135. @classmethod
  136. def _video_url(cls, video_id, video_type=None, *, slug='ignore_me', root=None):
  137. assert None in (video_type, root)
  138. if not root:
  139. root = join_nonempty(cls._BASE_URL, video_type, delim='/')
  140. return f'{root}/{slug}/{video_id}'
  141. def _real_extract(self, url):
  142. video_id, video_type = self._match_valid_url(url).group('id', 'type')
  143. video_type = self._TYPE.get(video_type, video_type)
  144. cookies = self._get_cookies(url) # Cookies before any request
  145. video_data = self._call_api_v1(f'{video_type}/detail', video_id,
  146. query={'tas': 10000, 'contentId': video_id})['body']['results']['item']
  147. if not self.get_param('allow_unplayable_formats') and video_data.get('drmProtected'):
  148. self.report_drm(video_id)
  149. # See https://github.com/hypervideo/hypervideo/issues/396
  150. st = self._download_webpage_handle(f'{self._BASE_URL}/in', video_id)[1].headers.get('x-origin-date')
  151. geo_restricted = False
  152. formats, subs = [], {}
  153. headers = {'Referer': f'{self._BASE_URL}/in'}
  154. # change to v2 in the future
  155. playback_sets = self._call_api_v2('play/v1/playback', video_id, st=st, cookies=cookies)['playBackSets']
  156. for playback_set in playback_sets:
  157. if not isinstance(playback_set, dict):
  158. continue
  159. tags = str_or_none(playback_set.get('tagsCombination')) or ''
  160. if any(f'{prefix}:{ignore}' in tags
  161. for key, prefix in self._IGNORE_MAP.items()
  162. for ignore in self._configuration_arg(key)):
  163. continue
  164. format_url = url_or_none(playback_set.get('playbackUrl'))
  165. if not format_url:
  166. continue
  167. format_url = re.sub(r'(?<=//staragvod)(\d)', r'web\1', format_url)
  168. dr = re.search(r'dynamic_range:(?P<dr>[a-z]+)', playback_set.get('tagsCombination')).group('dr')
  169. ext = determine_ext(format_url)
  170. current_formats, current_subs = [], {}
  171. try:
  172. if 'package:hls' in tags or ext == 'm3u8':
  173. current_formats, current_subs = self._extract_m3u8_formats_and_subtitles(
  174. format_url, video_id, 'mp4',
  175. entry_protocol='m3u8_native',
  176. m3u8_id=f'{dr}-hls', headers=headers)
  177. elif 'package:dash' in tags or ext == 'mpd':
  178. current_formats, current_subs = self._extract_mpd_formats_and_subtitles(
  179. format_url, video_id, mpd_id=f'{dr}-dash', headers=headers)
  180. elif ext == 'f4m':
  181. pass # XXX: produce broken files
  182. else:
  183. current_formats = [{
  184. 'url': format_url,
  185. 'width': int_or_none(playback_set.get('width')),
  186. 'height': int_or_none(playback_set.get('height')),
  187. }]
  188. except ExtractorError as e:
  189. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  190. geo_restricted = True
  191. continue
  192. if tags and 'encryption:plain' not in tags:
  193. for f in current_formats:
  194. f['has_drm'] = True
  195. if tags and 'language' in tags:
  196. lang = re.search(r'language:(?P<lang>[a-z]+)', tags).group('lang')
  197. for f in current_formats:
  198. if not f.get('langauge'):
  199. f['language'] = lang
  200. formats.extend(current_formats)
  201. subs = self._merge_subtitles(subs, current_subs)
  202. if not formats and geo_restricted:
  203. self.raise_geo_restricted(countries=['IN'], metadata_available=True)
  204. for f in formats:
  205. f.setdefault('http_headers', {}).update(headers)
  206. return {
  207. 'id': video_id,
  208. 'title': video_data.get('title'),
  209. 'description': video_data.get('description'),
  210. 'duration': int_or_none(video_data.get('duration')),
  211. 'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
  212. 'formats': formats,
  213. 'subtitles': subs,
  214. 'channel': video_data.get('channelName'),
  215. 'channel_id': video_data.get('channelId'),
  216. 'series': video_data.get('showName'),
  217. 'season': video_data.get('seasonName'),
  218. 'season_number': int_or_none(video_data.get('seasonNo')),
  219. 'season_id': video_data.get('seasonId'),
  220. 'episode': video_data.get('title'),
  221. 'episode_number': int_or_none(video_data.get('episodeNo')),
  222. }
  223. class HotStarPrefixIE(InfoExtractor):
  224. """ The "hotstar:" prefix is no longer in use, but this is kept for backward compatibility """
  225. IE_DESC = False
  226. _VALID_URL = r'hotstar:(?:(?P<type>\w+):)?(?P<id>\d+)$'
  227. _TESTS = [{
  228. 'url': 'hotstar:1000076273',
  229. 'only_matching': True,
  230. }, {
  231. 'url': 'hotstar:movies:1260009879',
  232. 'info_dict': {
  233. 'id': '1260009879',
  234. 'ext': 'mp4',
  235. 'title': 'Nuvvu Naaku Nachav',
  236. 'description': 'md5:d43701b1314e6f8233ce33523c043b7d',
  237. 'timestamp': 1567525674,
  238. 'upload_date': '20190903',
  239. 'duration': 10787,
  240. 'episode': 'Nuvvu Naaku Nachav',
  241. },
  242. }, {
  243. 'url': 'hotstar:episode:1000234847',
  244. 'only_matching': True,
  245. }, {
  246. # contentData
  247. 'url': 'hotstar:sports:1260065956',
  248. 'only_matching': True,
  249. }, {
  250. # contentData
  251. 'url': 'hotstar:sports:1260066104',
  252. 'only_matching': True,
  253. }]
  254. def _real_extract(self, url):
  255. video_id, video_type = self._match_valid_url(url).group('id', 'type')
  256. return self.url_result(HotStarIE._video_url(video_id, video_type), HotStarIE, video_id)
  257. class HotStarPlaylistIE(HotStarBaseIE):
  258. IE_NAME = 'hotstar:playlist'
  259. _VALID_URL = r'https?://(?:www\.)?hotstar\.com(?:/in)?/tv(?:/[^/]+){2}/list/[^/]+/t-(?P<id>\w+)'
  260. _TESTS = [{
  261. 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
  262. 'info_dict': {
  263. 'id': '3_2_26',
  264. },
  265. 'playlist_mincount': 20,
  266. }, {
  267. 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
  268. 'only_matching': True,
  269. }, {
  270. 'url': 'https://www.hotstar.com/in/tv/karthika-deepam/15457/list/popular-clips/t-3_2_1272',
  271. 'only_matching': True,
  272. }]
  273. def _real_extract(self, url):
  274. id_ = self._match_id(url)
  275. return self.playlist_result(
  276. self._playlist_entries('tray/find', id_, query={'tas': 10000, 'uqId': id_}), id_)
  277. class HotStarSeasonIE(HotStarBaseIE):
  278. IE_NAME = 'hotstar:season'
  279. _VALID_URL = r'(?P<url>https?://(?:www\.)?hotstar\.com(?:/in)?/tv/[^/]+/\w+)/seasons/[^/]+/ss-(?P<id>\w+)'
  280. _TESTS = [{
  281. 'url': 'https://www.hotstar.com/tv/radhakrishn/1260000646/seasons/season-2/ss-8028',
  282. 'info_dict': {
  283. 'id': '8028',
  284. },
  285. 'playlist_mincount': 35,
  286. }, {
  287. 'url': 'https://www.hotstar.com/in/tv/ishqbaaz/9567/seasons/season-2/ss-4357',
  288. 'info_dict': {
  289. 'id': '4357',
  290. },
  291. 'playlist_mincount': 30,
  292. }, {
  293. 'url': 'https://www.hotstar.com/in/tv/bigg-boss/14714/seasons/season-4/ss-8208/',
  294. 'info_dict': {
  295. 'id': '8208',
  296. },
  297. 'playlist_mincount': 19,
  298. }]
  299. def _real_extract(self, url):
  300. url, season_id = self._match_valid_url(url).groups()
  301. return self.playlist_result(self._playlist_entries(
  302. 'season/asset', season_id, url, query={'tao': 0, 'tas': 0, 'size': 10000, 'id': season_id}), season_id)
  303. class HotStarSeriesIE(HotStarBaseIE):
  304. IE_NAME = 'hotstar:series'
  305. _VALID_URL = r'(?P<url>https?://(?:www\.)?hotstar\.com(?:/in)?/tv/[^/]+/(?P<id>\d+))/?(?:[#?]|$)'
  306. _TESTS = [{
  307. 'url': 'https://www.hotstar.com/in/tv/radhakrishn/1260000646',
  308. 'info_dict': {
  309. 'id': '1260000646',
  310. },
  311. 'playlist_mincount': 690,
  312. }, {
  313. 'url': 'https://www.hotstar.com/tv/dancee-/1260050431',
  314. 'info_dict': {
  315. 'id': '1260050431',
  316. },
  317. 'playlist_mincount': 43,
  318. }, {
  319. 'url': 'https://www.hotstar.com/in/tv/mahabharat/435/',
  320. 'info_dict': {
  321. 'id': '435',
  322. },
  323. 'playlist_mincount': 267,
  324. }]
  325. def _real_extract(self, url):
  326. url, series_id = self._match_valid_url(url).groups()
  327. id_ = self._call_api_v1(
  328. 'show/detail', series_id, query={'contentId': series_id})['body']['results']['item']['id']
  329. return self.playlist_result(self._playlist_entries(
  330. 'tray/g/1/items', series_id, url, query={'tao': 0, 'tas': 10000, 'etid': 0, 'eid': id_}), series_id)