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