]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/hotstar.py
Update README.md
[youtubedl] / youtube_dl / extractor / hotstar.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import hashlib
5 import hmac
6 import re
7 import time
8 import uuid
9
10 from .common import InfoExtractor
11 from ..compat import (
12 compat_HTTPError,
13 compat_str,
14 )
15 from ..utils import (
16 determine_ext,
17 ExtractorError,
18 int_or_none,
19 str_or_none,
20 try_get,
21 url_or_none,
22 )
23
24
25 class HotStarBaseIE(InfoExtractor):
26 _AKAMAI_ENCRYPTION_KEY = b'\x05\xfc\x1a\x01\xca\xc9\x4b\xc4\x12\xfc\x53\x12\x07\x75\xf9\xee'
27
28 def _call_api_impl(self, path, video_id, query):
29 st = int(time.time())
30 exp = st + 6000
31 auth = 'st=%d~exp=%d~acl=/*' % (st, exp)
32 auth += '~hmac=' + hmac.new(self._AKAMAI_ENCRYPTION_KEY, auth.encode(), hashlib.sha256).hexdigest()
33 response = self._download_json(
34 'https://api.hotstar.com/' + path, video_id, headers={
35 'hotstarauth': auth,
36 'x-country-code': 'IN',
37 'x-platform-code': 'JIO',
38 }, query=query)
39 if response['statusCode'] != 'OK':
40 raise ExtractorError(
41 response['body']['message'], expected=True)
42 return response['body']['results']
43
44 def _call_api(self, path, video_id, query_name='contentId'):
45 return self._call_api_impl(path, video_id, {
46 query_name: video_id,
47 'tas': 10000,
48 })
49
50 def _call_api_v2(self, path, video_id):
51 return self._call_api_impl(
52 '%s/in/contents/%s' % (path, video_id), video_id, {
53 'desiredConfig': 'encryption:plain;ladder:phone,tv;package:hls,dash',
54 'client': 'mweb',
55 'clientVersion': '6.18.0',
56 'deviceId': compat_str(uuid.uuid4()),
57 'osName': 'Windows',
58 'osVersion': '10',
59 })
60
61
62 class HotStarIE(HotStarBaseIE):
63 IE_NAME = 'hotstar'
64 _VALID_URL = r'https?://(?:www\.)?hotstar\.com/(?:.+?[/-])?(?P<id>\d{10})'
65 _TESTS = [{
66 # contentData
67 'url': 'https://www.hotstar.com/can-you-not-spread-rumours/1000076273',
68 'info_dict': {
69 'id': '1000076273',
70 'ext': 'mp4',
71 'title': 'Can You Not Spread Rumours?',
72 'description': 'md5:c957d8868e9bc793ccb813691cc4c434',
73 'timestamp': 1447248600,
74 'upload_date': '20151111',
75 'duration': 381,
76 },
77 'params': {
78 # m3u8 download
79 'skip_download': True,
80 }
81 }, {
82 # contentDetail
83 'url': 'https://www.hotstar.com/movies/radha-gopalam/1000057157',
84 'only_matching': True,
85 }, {
86 'url': 'http://www.hotstar.com/sports/cricket/rajitha-sizzles-on-debut-with-329/2001477583',
87 'only_matching': True,
88 }, {
89 'url': 'http://www.hotstar.com/1000000515',
90 'only_matching': True,
91 }, {
92 # only available via api v2
93 'url': 'https://www.hotstar.com/tv/ek-bhram-sarvagun-sampanna/s-2116/janhvi-targets-suman/1000234847',
94 'only_matching': True,
95 }]
96 _GEO_BYPASS = False
97
98 def _real_extract(self, url):
99 video_id = self._match_id(url)
100
101 webpage = self._download_webpage(url, video_id)
102 app_state = self._parse_json(self._search_regex(
103 r'<script>window\.APP_STATE\s*=\s*({.+?})</script>',
104 webpage, 'app state'), video_id)
105 video_data = {}
106 getters = list(
107 lambda x, k=k: x['initialState']['content%s' % k]['content']
108 for k in ('Data', 'Detail')
109 )
110 for v in app_state.values():
111 content = try_get(v, getters, dict)
112 if content and content.get('contentId') == video_id:
113 video_data = content
114 break
115
116 title = video_data['title']
117
118 if video_data.get('drmProtected'):
119 raise ExtractorError('This video is DRM protected.', expected=True)
120
121 headers = {'Referer': url}
122 formats = []
123 geo_restricted = False
124 playback_sets = self._call_api_v2('h/v2/play', video_id)['playBackSets']
125 for playback_set in playback_sets:
126 if not isinstance(playback_set, dict):
127 continue
128 format_url = url_or_none(playback_set.get('playbackUrl'))
129 if not format_url:
130 continue
131 format_url = re.sub(
132 r'(?<=//staragvod)(\d)', r'web\1', format_url)
133 tags = str_or_none(playback_set.get('tagsCombination')) or ''
134 if tags and 'encryption:plain' not in tags:
135 continue
136 ext = determine_ext(format_url)
137 try:
138 if 'package:hls' in tags or ext == 'm3u8':
139 formats.extend(self._extract_m3u8_formats(
140 format_url, video_id, 'mp4',
141 entry_protocol='m3u8_native',
142 m3u8_id='hls', headers=headers))
143 elif 'package:dash' in tags or ext == 'mpd':
144 formats.extend(self._extract_mpd_formats(
145 format_url, video_id, mpd_id='dash', headers=headers))
146 elif ext == 'f4m':
147 # produce broken files
148 pass
149 else:
150 formats.append({
151 'url': format_url,
152 'width': int_or_none(playback_set.get('width')),
153 'height': int_or_none(playback_set.get('height')),
154 })
155 except ExtractorError as e:
156 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
157 geo_restricted = True
158 continue
159 if not formats and geo_restricted:
160 self.raise_geo_restricted(countries=['IN'])
161 self._sort_formats(formats)
162
163 for f in formats:
164 f.setdefault('http_headers', {}).update(headers)
165
166 return {
167 'id': video_id,
168 'title': title,
169 'description': video_data.get('description'),
170 'duration': int_or_none(video_data.get('duration')),
171 'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
172 'formats': formats,
173 'channel': video_data.get('channelName'),
174 'channel_id': video_data.get('channelId'),
175 'series': video_data.get('showName'),
176 'season': video_data.get('seasonName'),
177 'season_number': int_or_none(video_data.get('seasonNo')),
178 'season_id': video_data.get('seasonId'),
179 'episode': title,
180 'episode_number': int_or_none(video_data.get('episodeNo')),
181 }
182
183
184 class HotStarPlaylistIE(HotStarBaseIE):
185 IE_NAME = 'hotstar:playlist'
186 _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)'
187 _TESTS = [{
188 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
189 'info_dict': {
190 'id': '3_2_26',
191 },
192 'playlist_mincount': 20,
193 }, {
194 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
195 'only_matching': True,
196 }]
197
198 def _real_extract(self, url):
199 playlist_id = self._match_id(url)
200
201 collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')
202
203 entries = [
204 self.url_result(
205 'https://www.hotstar.com/%s' % video['contentId'],
206 ie=HotStarIE.ie_key(), video_id=video['contentId'])
207 for video in collection['assets']['items']
208 if video.get('contentId')]
209
210 return self.playlist_result(entries, playlist_id)