]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/hotstar.py
[peertube] Fix videos without description (#639)
[yt-dlp.git] / yt_dlp / extractor / hotstar.py
CommitLineData
fb8e402a 1# coding: utf-8
2from __future__ import unicode_literals
3
85cd69ad
RA
4import hashlib
5import hmac
1cb812d3 6import re
85cd69ad 7import time
2533f5b6 8import uuid
7078ec64 9import json
909191de 10
fb8e402a 11from .common import InfoExtractor
2533f5b6
S
12from ..compat import (
13 compat_HTTPError,
6923b538 14 compat_str
2533f5b6 15)
fb8e402a 16from ..utils import (
fb8e402a 17 determine_ext,
909191de 18 ExtractorError,
fb8e402a 19 int_or_none,
2533f5b6 20 str_or_none,
05e7c184 21 try_get,
2533f5b6 22 url_or_none,
fb8e402a 23)
24
25
909191de 26class HotStarBaseIE(InfoExtractor):
85cd69ad
RA
27 _AKAMAI_ENCRYPTION_KEY = b'\x05\xfc\x1a\x01\xca\xc9\x4b\xc4\x12\xfc\x53\x12\x07\x75\xf9\xee'
28
fe07e2c6 29 def _call_api_impl(self, path, video_id, query, st=None, cookies=None):
9fc0de57 30 st = int_or_none(st) or int(time.time())
85cd69ad
RA
31 exp = st + 6000
32 auth = 'st=%d~exp=%d~acl=/*' % (st, exp)
33 auth += '~hmac=' + hmac.new(self._AKAMAI_ENCRYPTION_KEY, auth.encode(), hashlib.sha256).hexdigest()
6923b538 34
fe07e2c6
A
35 if cookies.get('userUP'):
36 token = cookies.get('userUP').value
37 else:
38 token = self._download_json(
39 'https://api.hotstar.com/um/v3/users',
40 video_id, note='Downloading token',
41 data=json.dumps({"device_ids": [{"id": compat_str(uuid.uuid4()), "type": "device_id"}]}).encode('utf-8'),
42 headers={
43 'hotstarauth': auth,
44 'x-hs-platform': 'PCTV', # or 'web'
45 'Content-Type': 'application/json',
46 })['user_identity']
6923b538 47
85cd69ad 48 response = self._download_json(
2533f5b6 49 'https://api.hotstar.com/' + path, video_id, headers={
85cd69ad 50 'hotstarauth': auth,
7078ec64
N
51 'x-hs-appversion': '6.72.2',
52 'x-hs-platform': 'web',
53 'x-hs-usertoken': token,
2533f5b6 54 }, query=query)
6923b538 55
7078ec64 56 if response['message'] != "Playback URL's fetched successfully":
85cd69ad 57 raise ExtractorError(
7078ec64
N
58 response['message'], expected=True)
59 return response['data']
909191de 60
2533f5b6
S
61 def _call_api(self, path, video_id, query_name='contentId'):
62 return self._call_api_impl(path, video_id, {
63 query_name: video_id,
64 'tas': 10000,
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={
6923b538 70 'desired-config': 'audio_channel:stereo|dynamic_range:sdr|encryption:plain|ladder:tv|package:dash|resolution:hd|subs-tag:HotstarVIP|video_codec:vp9',
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
A
79 _VALID_URL = r'''(?x)
80 https?://(?:www\.)?hotstar\.com(?:/in)?/(?!in/)
81 (?:
82 tv/(?:[^/?#]+/){3}|
83 (?!tv/)[^?#]+/
84 )?
85 (?P<id>\d{10})
86 '''
89d23f37 87 _TESTS = [{
adbbdefc 88 # contentData
85cd69ad 89 'url': 'https://www.hotstar.com/can-you-not-spread-rumours/1000076273',
fb8e402a 90 'info_dict': {
91 'id': '1000076273',
92 'ext': 'mp4',
85cd69ad 93 'title': 'Can You Not Spread Rumours?',
fb8e402a 94 'description': 'md5:c957d8868e9bc793ccb813691cc4c434',
85cd69ad 95 'timestamp': 1447248600,
fb8e402a 96 'upload_date': '20151111',
97 'duration': 381,
98 },
99 'params': {
100 # m3u8 download
101 'skip_download': True,
102 }
adbbdefc
S
103 }, {
104 # contentDetail
105 'url': 'https://www.hotstar.com/movies/radha-gopalam/1000057157',
106 'only_matching': True,
89d23f37
S
107 }, {
108 'url': 'http://www.hotstar.com/sports/cricket/rajitha-sizzles-on-debut-with-329/2001477583',
109 'only_matching': True,
110 }, {
111 'url': 'http://www.hotstar.com/1000000515',
112 'only_matching': True,
2533f5b6
S
113 }, {
114 # only available via api v2
115 'url': 'https://www.hotstar.com/tv/ek-bhram-sarvagun-sampanna/s-2116/janhvi-targets-suman/1000234847',
116 'only_matching': True,
89d23f37 117 }]
85cd69ad 118 _GEO_BYPASS = False
fb8e402a 119
fb8e402a 120 def _real_extract(self, url):
121 video_id = self._match_id(url)
fe07e2c6 122 cookies = self._get_cookies(url)
9fc0de57 123 webpage, urlh = self._download_webpage_handle(url, video_id)
124 st = urlh.headers.get('x-origin-date')
85cd69ad
RA
125 app_state = self._parse_json(self._search_regex(
126 r'<script>window\.APP_STATE\s*=\s*({.+?})</script>',
127 webpage, 'app state'), video_id)
05e7c184 128 video_data = {}
c3c098dc 129 getters = list(
adbbdefc
S
130 lambda x, k=k: x['initialState']['content%s' % k]['content']
131 for k in ('Data', 'Detail')
132 )
05e7c184 133 for v in app_state.values():
adbbdefc 134 content = try_get(v, getters, dict)
05e7c184
RA
135 if content and content.get('contentId') == video_id:
136 video_data = content
c3c098dc 137 break
909191de 138
85cd69ad 139 title = video_data['title']
0dac7cbb 140
a06916d9 141 if not self.get_param('allow_unplayable_formats') and video_data.get('drmProtected'):
0dac7cbb 142 raise ExtractorError('This video is DRM protected.', expected=True)
fb8e402a 143
d7def23d 144 headers = {'Referer': url}
fb8e402a 145 formats = []
2533f5b6 146 geo_restricted = False
6923b538 147 # change to v2 in the future
fe07e2c6 148 playback_sets = self._call_api_v2('play/v1/playback', video_id, st=st, cookies=cookies)['playBackSets']
2533f5b6
S
149 for playback_set in playback_sets:
150 if not isinstance(playback_set, dict):
151 continue
152 format_url = url_or_none(playback_set.get('playbackUrl'))
153 if not format_url:
154 continue
1cb812d3
S
155 format_url = re.sub(
156 r'(?<=//staragvod)(\d)', r'web\1', format_url)
2533f5b6
S
157 tags = str_or_none(playback_set.get('tagsCombination')) or ''
158 if tags and 'encryption:plain' not in tags:
159 continue
160 ext = determine_ext(format_url)
85cd69ad 161 try:
2533f5b6
S
162 if 'package:hls' in tags or ext == 'm3u8':
163 formats.extend(self._extract_m3u8_formats(
d9d30986 164 format_url, video_id, 'mp4',
d7def23d
RA
165 entry_protocol='m3u8_native',
166 m3u8_id='hls', headers=headers))
2533f5b6
S
167 elif 'package:dash' in tags or ext == 'mpd':
168 formats.extend(self._extract_mpd_formats(
d7def23d 169 format_url, video_id, mpd_id='dash', headers=headers))
2533f5b6
S
170 elif ext == 'f4m':
171 # produce broken files
172 pass
173 else:
174 formats.append({
175 'url': format_url,
176 'width': int_or_none(playback_set.get('width')),
177 'height': int_or_none(playback_set.get('height')),
178 })
85cd69ad
RA
179 except ExtractorError as e:
180 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
2533f5b6
S
181 geo_restricted = True
182 continue
183 if not formats and geo_restricted:
b7da73eb 184 self.raise_geo_restricted(countries=['IN'], metadata_available=True)
fb8e402a 185 self._sort_formats(formats)
186
d7def23d
RA
187 for f in formats:
188 f.setdefault('http_headers', {}).update(headers)
189
fb8e402a 190 return {
191 'id': video_id,
0dac7cbb 192 'title': title,
fb8e402a 193 'description': video_data.get('description'),
194 'duration': int_or_none(video_data.get('duration')),
85cd69ad 195 'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
fb8e402a 196 'formats': formats,
85cd69ad
RA
197 'channel': video_data.get('channelName'),
198 'channel_id': video_data.get('channelId'),
199 'series': video_data.get('showName'),
200 'season': video_data.get('seasonName'),
201 'season_number': int_or_none(video_data.get('seasonNo')),
202 'season_id': video_data.get('seasonId'),
0dac7cbb 203 'episode': title,
85cd69ad 204 'episode_number': int_or_none(video_data.get('episodeNo')),
fb8e402a 205 }
477c97f8
AV
206
207
909191de 208class HotStarPlaylistIE(HotStarBaseIE):
477c97f8 209 IE_NAME = 'hotstar:playlist'
85cd69ad 210 _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)'
477c97f8 211 _TESTS = [{
85cd69ad 212 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
477c97f8 213 'info_dict': {
85cd69ad 214 'id': '3_2_26',
477c97f8 215 },
85cd69ad 216 'playlist_mincount': 20,
477c97f8 217 }, {
85cd69ad 218 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
477c97f8
AV
219 'only_matching': True,
220 }]
477c97f8
AV
221
222 def _real_extract(self, url):
85cd69ad
RA
223 playlist_id = self._match_id(url)
224
225 collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')
477c97f8 226
477c97f8 227 entries = [
909191de 228 self.url_result(
85cd69ad 229 'https://www.hotstar.com/%s' % video['contentId'],
909191de 230 ie=HotStarIE.ie_key(), video_id=video['contentId'])
85cd69ad 231 for video in collection['assets']['items']
909191de
S
232 if video.get('contentId')]
233
234 return self.playlist_result(entries, playlist_id)
6e639032
A
235
236
237class HotStarSeriesIE(HotStarBaseIE):
238 IE_NAME = 'hotstar:series'
8242bf22 239 _VALID_URL = r'(?:https?://)(?:www\.)?hotstar\.com(?:/in)?/tv/[^/]+/(?P<id>\d+)'
6e639032
A
240 _TESTS = [{
241 'url': 'https://www.hotstar.com/in/tv/radhakrishn/1260000646',
242 'info_dict': {
243 'id': '1260000646',
244 },
245 'playlist_mincount': 690,
246 }, {
247 'url': 'https://www.hotstar.com/tv/dancee-/1260050431',
248 'info_dict': {
249 'id': '1260050431',
250 },
251 'playlist_mincount': 43,
8242bf22
A
252 }, {
253 'url': 'https://www.hotstar.com/in/tv/mahabharat/435/',
254 'info_dict': {
255 'id': '435',
256 },
257 'playlist_mincount': 269,
6e639032
A
258 }]
259
260 def _real_extract(self, url):
261 series_id = self._match_id(url)
262 headers = {
263 'x-country-code': 'IN',
264 'x-platform-code': 'PCTV',
265 }
266 detail_json = self._download_json('https://api.hotstar.com/o/v1/show/detail?contentId=' + series_id,
267 video_id=series_id, headers=headers)
268 id = compat_str(try_get(detail_json, lambda x: x['body']['results']['item']['id'], int))
269 item_json = self._download_json('https://api.hotstar.com/o/v1/tray/g/1/items?etid=0&tao=0&tas=10000&eid=' + id,
270 video_id=series_id, headers=headers)
271 entries = [
272 self.url_result(
273 'https://www.hotstar.com/%d' % video['contentId'],
274 ie=HotStarIE.ie_key(), video_id=video['contentId'])
275 for video in item_json['body']['results']['items']
276 if video.get('contentId')]
277
278 return self.playlist_result(entries, series_id)