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