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