]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/hotstar.py
[cleanup] Add more ruff rules (#10149)
[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
3d2623a8 9from ..networking.exceptions import HTTPError
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 33 exp = st + 6000
add96eb9 34 auth = f'st={st}~exp={exp}~acl=/*'
85cd69ad 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 42 video_id, note='Downloading token',
add96eb9 43 data=json.dumps({'device_ids': [{'id': str(uuid.uuid4()), 'type': 'device_id'}]}).encode(),
fe07e2c6
A
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',
add96eb9 68 'device-id': cookies.get('device_id').value if cookies.get('device_id') else 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 (?:
86eeb044 86 (?P<type>movies|sports|clips|episode|(?P<tv>tv|shows))/
a1ddaa89 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',
f4f9f6d0 117 'channel_id': '3',
b6a35ad8
A
118 'series': 'Ek Bhram - Sarvagun Sampanna',
119 'season': 'Chapter 1',
120 'season_number': 1,
f4f9f6d0 121 'season_id': '6771',
b6a35ad8
A
122 'episode': 'Janhvi Targets Suman',
123 'episode_number': 8,
add96eb9 124 },
7f8ddebb 125 }, {
126 'url': 'https://www.hotstar.com/in/shows/anupama/1260022017/anupama-anuj-share-a-moment/1000282843',
127 'info_dict': {
128 'id': '1000282843',
129 'ext': 'mp4',
130 'title': 'Anupama, Anuj Share a Moment',
131 'season': 'Chapter 1',
132 'description': 'md5:8d74ed2248423b8b06d5c8add4d7a0c0',
133 'timestamp': 1678149000,
134 'channel': 'StarPlus',
135 'series': 'Anupama',
136 'season_number': 1,
f4f9f6d0 137 'season_id': '7399',
7f8ddebb 138 'upload_date': '20230307',
139 'episode': 'Anupama, Anuj Share a Moment',
140 'episode_number': 853,
141 'duration': 1272,
f4f9f6d0 142 'channel_id': '3',
7f8ddebb 143 },
7237c8dc
R
144 'skip': 'HTTP Error 504: Gateway Time-out', # XXX: Investigate 504 errors on some episodes
145 }, {
146 'url': 'https://www.hotstar.com/in/shows/kana-kaanum-kaalangal/1260097087/back-to-school/1260097320',
147 'info_dict': {
148 'id': '1260097320',
149 'ext': 'mp4',
150 'title': 'Back To School',
151 'season': 'Chapter 1',
152 'description': 'md5:b0d6a4c8a650681491e7405496fc7e13',
153 'timestamp': 1650564000,
154 'channel': 'Hotstar Specials',
155 'series': 'Kana Kaanum Kaalangal',
156 'season_number': 1,
f4f9f6d0 157 'season_id': '9441',
7237c8dc
R
158 'upload_date': '20220421',
159 'episode': 'Back To School',
160 'episode_number': 1,
161 'duration': 1810,
f4f9f6d0 162 'channel_id': '54',
7237c8dc 163 },
86eeb044 164 }, {
165 'url': 'https://www.hotstar.com/in/clips/e3-sairat-kahani-pyaar-ki/1000262286',
166 'info_dict': {
167 'id': '1000262286',
168 'ext': 'mp4',
169 'title': 'E3 - SaiRat, Kahani Pyaar Ki',
170 'description': 'md5:e3b4b3203bc0c5396fe7d0e4948a6385',
171 'episode': 'E3 - SaiRat, Kahani Pyaar Ki',
172 'upload_date': '20210606',
173 'timestamp': 1622943900,
174 'duration': 5395,
175 },
7237c8dc
R
176 }, {
177 'url': 'https://www.hotstar.com/in/movies/premam/1000091195',
178 'info_dict': {
179 'id': '1000091195',
180 'ext': 'mp4',
181 'title': 'Premam',
182 'release_year': 2015,
183 'description': 'md5:d833c654e4187b5e34757eafb5b72d7f',
184 'timestamp': 1462149000,
185 'upload_date': '20160502',
186 'episode': 'Premam',
187 'duration': 8994,
188 },
b6a35ad8 189 }, {
a1ddaa89 190 'url': 'https://www.hotstar.com/movies/radha-gopalam/1000057157',
191 'only_matching': True,
192 }, {
193 'url': 'https://www.hotstar.com/in/sports/cricket/follow-the-blues-2021/recap-eng-fight-back-on-day-2/1260066104',
194 'only_matching': True,
195 }, {
196 'url': 'https://www.hotstar.com/in/sports/football/most-costly-pl-transfers-ft-grealish/1260065956',
2533f5b6 197 'only_matching': True,
89d23f37 198 }]
85cd69ad 199 _GEO_BYPASS = False
a1ddaa89 200
b6a35ad8
A
201 _TYPE = {
202 'movies': 'movie',
203 'sports': 'match',
204 'episode': 'episode',
205 'tv': 'episode',
7f8ddebb 206 'shows': 'episode',
86eeb044 207 'clips': 'content',
b6a35ad8
A
208 None: 'content',
209 }
fb8e402a 210
a1ddaa89 211 _IGNORE_MAP = {
212 'res': 'resolution',
213 'vcodec': 'video_codec',
214 'dr': 'dynamic_range',
215 }
216
e74a3c6d 217 _TAG_FIELDS = {
218 'language': 'language',
219 'acodec': 'audio_codec',
220 'vcodec': 'video_codec',
221 }
222
a1ddaa89 223 @classmethod
224 def _video_url(cls, video_id, video_type=None, *, slug='ignore_me', root=None):
225 assert None in (video_type, root)
226 if not root:
227 root = join_nonempty(cls._BASE_URL, video_type, delim='/')
228 return f'{root}/{slug}/{video_id}'
229
fb8e402a 230 def _real_extract(self, url):
a1ddaa89 231 video_id, video_type = self._match_valid_url(url).group('id', 'type')
b6a35ad8 232 video_type = self._TYPE.get(video_type, video_type)
5d5c0f7e 233 cookies = self._get_cookies(url) # Cookies before any request
0dac7cbb 234
30ea8859 235 video_data = traverse_obj(
236 self._call_api_v1(
237 f'{video_type}/detail', video_id, fatal=False, query={'tas': 10000, 'contentId': video_id}),
238 ('body', 'results', 'item', {dict})) or {}
a06916d9 239 if not self.get_param('allow_unplayable_formats') and video_data.get('drmProtected'):
88acdbc2 240 self.report_drm(video_id)
241
a1ddaa89 242 # See https://github.com/yt-dlp/yt-dlp/issues/396
243 st = self._download_webpage_handle(f'{self._BASE_URL}/in', video_id)[1].headers.get('x-origin-date')
244
2533f5b6 245 geo_restricted = False
a1ddaa89 246 formats, subs = [], {}
247 headers = {'Referer': f'{self._BASE_URL}/in'}
248
6923b538 249 # change to v2 in the future
5d5c0f7e 250 playback_sets = self._call_api_v2('play/v1/playback', video_id, st=st, cookies=cookies)['playBackSets']
2533f5b6
S
251 for playback_set in playback_sets:
252 if not isinstance(playback_set, dict):
253 continue
a1ddaa89 254 tags = str_or_none(playback_set.get('tagsCombination')) or ''
255 if any(f'{prefix}:{ignore}' in tags
256 for key, prefix in self._IGNORE_MAP.items()
257 for ignore in self._configuration_arg(key)):
258 continue
259
2533f5b6
S
260 format_url = url_or_none(playback_set.get('playbackUrl'))
261 if not format_url:
262 continue
a1ddaa89 263 format_url = re.sub(r'(?<=//staragvod)(\d)', r'web\1', format_url)
2533f5b6 264 ext = determine_ext(format_url)
a1ddaa89 265
6ff34542 266 current_formats, current_subs = [], {}
85cd69ad 267 try:
2533f5b6 268 if 'package:hls' in tags or ext == 'm3u8':
6ff34542 269 current_formats, current_subs = self._extract_m3u8_formats_and_subtitles(
e74a3c6d 270 format_url, video_id, ext='mp4', headers=headers)
2533f5b6 271 elif 'package:dash' in tags or ext == 'mpd':
6ff34542 272 current_formats, current_subs = self._extract_mpd_formats_and_subtitles(
e74a3c6d 273 format_url, video_id, headers=headers)
2533f5b6 274 elif ext == 'f4m':
a1ddaa89 275 pass # XXX: produce broken files
2533f5b6 276 else:
6ff34542 277 current_formats = [{
2533f5b6
S
278 'url': format_url,
279 'width': int_or_none(playback_set.get('width')),
280 'height': int_or_none(playback_set.get('height')),
6ff34542 281 }]
85cd69ad 282 except ExtractorError as e:
3d2623a8 283 if isinstance(e.cause, HTTPError) and e.cause.status == 403:
2533f5b6
S
284 geo_restricted = True
285 continue
a1ddaa89 286
add96eb9 287 tag_dict = dict((*t.split(':', 1), None)[:2] for t in tags.split(';'))
e74a3c6d 288 if tag_dict.get('encryption') not in ('plain', None):
6ff34542
AG
289 for f in current_formats:
290 f['has_drm'] = True
e74a3c6d 291 for f in current_formats:
292 for k, v in self._TAG_FIELDS.items():
293 if not f.get(k):
294 f[k] = tag_dict.get(v)
295 if f.get('vcodec') != 'none' and not f.get('dynamic_range'):
296 f['dynamic_range'] = tag_dict.get('dynamic_range')
297 if f.get('acodec') != 'none' and not f.get('audio_channels'):
298 f['audio_channels'] = {
299 'stereo': 2,
300 'dolby51': 6,
301 }.get(tag_dict.get('audio_channel'))
302 f['format_note'] = join_nonempty(
303 tag_dict.get('ladder'),
304 tag_dict.get('audio_channel') if f.get('acodec') != 'none' else None,
305 f.get('format_note'),
306 delim=', ')
a1ddaa89 307
6ff34542
AG
308 formats.extend(current_formats)
309 subs = self._merge_subtitles(subs, current_subs)
a1ddaa89 310
2533f5b6 311 if not formats and geo_restricted:
b7da73eb 312 self.raise_geo_restricted(countries=['IN'], metadata_available=True)
e74a3c6d 313 self._remove_duplicate_formats(formats)
d7def23d
RA
314 for f in formats:
315 f.setdefault('http_headers', {}).update(headers)
316
fb8e402a 317 return {
318 'id': video_id,
a1ddaa89 319 'title': video_data.get('title'),
fb8e402a 320 'description': video_data.get('description'),
321 'duration': int_or_none(video_data.get('duration')),
e74a3c6d 322 'timestamp': int_or_none(traverse_obj(video_data, 'broadcastDate', 'startDate')),
7237c8dc 323 'release_year': int_or_none(video_data.get('year')),
fb8e402a 324 'formats': formats,
b6a35ad8 325 'subtitles': subs,
85cd69ad 326 'channel': video_data.get('channelName'),
f4f9f6d0 327 'channel_id': str_or_none(video_data.get('channelId')),
85cd69ad
RA
328 'series': video_data.get('showName'),
329 'season': video_data.get('seasonName'),
330 'season_number': int_or_none(video_data.get('seasonNo')),
f4f9f6d0 331 'season_id': str_or_none(video_data.get('seasonId')),
a1ddaa89 332 'episode': video_data.get('title'),
85cd69ad 333 'episode_number': int_or_none(video_data.get('episodeNo')),
fb8e402a 334 }
477c97f8
AV
335
336
a1ddaa89 337class HotStarPrefixIE(InfoExtractor):
338 """ The "hotstar:" prefix is no longer in use, but this is kept for backward compatibility """
339 IE_DESC = False
340 _VALID_URL = r'hotstar:(?:(?P<type>\w+):)?(?P<id>\d+)$'
341 _TESTS = [{
342 'url': 'hotstar:1000076273',
343 'only_matching': True,
344 }, {
db6fa696 345 'url': 'hotstar:movies:1260009879',
a1ddaa89 346 'info_dict': {
db6fa696 347 'id': '1260009879',
a1ddaa89 348 'ext': 'mp4',
db6fa696 349 'title': 'Nuvvu Naaku Nachav',
350 'description': 'md5:d43701b1314e6f8233ce33523c043b7d',
351 'timestamp': 1567525674,
352 'upload_date': '20190903',
353 'duration': 10787,
354 'episode': 'Nuvvu Naaku Nachav',
a1ddaa89 355 },
356 }, {
357 'url': 'hotstar:episode:1000234847',
358 'only_matching': True,
359 }, {
360 # contentData
361 'url': 'hotstar:sports:1260065956',
362 'only_matching': True,
363 }, {
364 # contentData
365 'url': 'hotstar:sports:1260066104',
366 'only_matching': True,
367 }]
368
369 def _real_extract(self, url):
370 video_id, video_type = self._match_valid_url(url).group('id', 'type')
371 return self.url_result(HotStarIE._video_url(video_id, video_type), HotStarIE, video_id)
372
373
909191de 374class HotStarPlaylistIE(HotStarBaseIE):
477c97f8 375 IE_NAME = 'hotstar:playlist'
7f8ddebb 376 _VALID_URL = r'https?://(?:www\.)?hotstar\.com(?:/in)?/(?:tv|shows)(?:/[^/]+){2}/list/[^/]+/t-(?P<id>\w+)'
477c97f8 377 _TESTS = [{
85cd69ad 378 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
477c97f8 379 'info_dict': {
85cd69ad 380 'id': '3_2_26',
477c97f8 381 },
85cd69ad 382 'playlist_mincount': 20,
7f8ddebb 383 }, {
384 'url': 'https://www.hotstar.com/shows/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
385 'only_matching': True,
477c97f8 386 }, {
85cd69ad 387 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
477c97f8 388 'only_matching': True,
db6fa696 389 }, {
390 'url': 'https://www.hotstar.com/in/tv/karthika-deepam/15457/list/popular-clips/t-3_2_1272',
391 'only_matching': True,
477c97f8 392 }]
477c97f8
AV
393
394 def _real_extract(self, url):
fad689c7 395 id_ = self._match_id(url)
396 return self.playlist_result(
397 self._playlist_entries('tray/find', id_, query={'tas': 10000, 'uqId': id_}), id_)
6e639032
A
398
399
db6fa696 400class HotStarSeasonIE(HotStarBaseIE):
401 IE_NAME = 'hotstar:season'
7f8ddebb 402 _VALID_URL = r'(?P<url>https?://(?:www\.)?hotstar\.com(?:/in)?/(?:tv|shows)/[^/]+/\w+)/seasons/[^/]+/ss-(?P<id>\w+)'
db6fa696 403 _TESTS = [{
404 'url': 'https://www.hotstar.com/tv/radhakrishn/1260000646/seasons/season-2/ss-8028',
405 'info_dict': {
406 'id': '8028',
407 },
408 'playlist_mincount': 35,
409 }, {
410 'url': 'https://www.hotstar.com/in/tv/ishqbaaz/9567/seasons/season-2/ss-4357',
411 'info_dict': {
412 'id': '4357',
413 },
414 'playlist_mincount': 30,
415 }, {
416 'url': 'https://www.hotstar.com/in/tv/bigg-boss/14714/seasons/season-4/ss-8208/',
417 'info_dict': {
418 'id': '8208',
419 },
420 'playlist_mincount': 19,
7f8ddebb 421 }, {
422 'url': 'https://www.hotstar.com/in/shows/bigg-boss/14714/seasons/season-4/ss-8208/',
423 'only_matching': True,
db6fa696 424 }]
425
426 def _real_extract(self, url):
427 url, season_id = self._match_valid_url(url).groups()
fad689c7 428 return self.playlist_result(self._playlist_entries(
429 'season/asset', season_id, url, query={'tao': 0, 'tas': 0, 'size': 10000, 'id': season_id}), season_id)
db6fa696 430
431
6e639032
A
432class HotStarSeriesIE(HotStarBaseIE):
433 IE_NAME = 'hotstar:series'
7f8ddebb 434 _VALID_URL = r'(?P<url>https?://(?:www\.)?hotstar\.com(?:/in)?/(?:tv|shows)/[^/]+/(?P<id>\d+))/?(?:[#?]|$)'
6e639032
A
435 _TESTS = [{
436 'url': 'https://www.hotstar.com/in/tv/radhakrishn/1260000646',
437 'info_dict': {
438 'id': '1260000646',
439 },
440 'playlist_mincount': 690,
441 }, {
442 'url': 'https://www.hotstar.com/tv/dancee-/1260050431',
443 'info_dict': {
444 'id': '1260050431',
445 },
446 'playlist_mincount': 43,
8242bf22
A
447 }, {
448 'url': 'https://www.hotstar.com/in/tv/mahabharat/435/',
449 'info_dict': {
450 'id': '435',
451 },
db6fa696 452 'playlist_mincount': 267,
7f8ddebb 453 }, {
454 'url': 'https://www.hotstar.com/in/shows/anupama/1260022017/',
455 'info_dict': {
456 'id': '1260022017',
457 },
458 'playlist_mincount': 940,
6e639032
A
459 }]
460
461 def _real_extract(self, url):
81bcd43a 462 url, series_id = self._match_valid_url(url).groups()
fad689c7 463 id_ = self._call_api_v1(
464 'show/detail', series_id, query={'contentId': series_id})['body']['results']['item']['id']
465
466 return self.playlist_result(self._playlist_entries(
467 'tray/g/1/items', series_id, url, query={'tao': 0, 'tas': 10000, 'etid': 0, 'eid': id_}), series_id)