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