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