]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/hotstar.py
Update upstream source from tag 'upstream/2019.09.28'
[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 formats = []
122 geo_restricted = False
123 playback_sets = self._call_api_v2('h/v2/play', video_id)['playBackSets']
124 for playback_set in playback_sets:
125 if not isinstance(playback_set, dict):
126 continue
127 format_url = url_or_none(playback_set.get('playbackUrl'))
128 if not format_url:
129 continue
130 format_url = re.sub(
131 r'(?<=//staragvod)(\d)', r'web\1', format_url)
132 tags = str_or_none(playback_set.get('tagsCombination')) or ''
133 if tags and 'encryption:plain' not in tags:
134 continue
135 ext = determine_ext(format_url)
136 try:
137 if 'package:hls' in tags or ext == 'm3u8':
138 formats.extend(self._extract_m3u8_formats(
139 format_url, video_id, 'mp4',
140 entry_protocol='m3u8_native', m3u8_id='hls'))
141 elif 'package:dash' in tags or ext == 'mpd':
142 formats.extend(self._extract_mpd_formats(
143 format_url, video_id, mpd_id='dash'))
144 elif ext == 'f4m':
145 # produce broken files
146 pass
147 else:
148 formats.append({
149 'url': format_url,
150 'width': int_or_none(playback_set.get('width')),
151 'height': int_or_none(playback_set.get('height')),
152 })
153 except ExtractorError as e:
154 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
155 geo_restricted = True
156 continue
157 if not formats and geo_restricted:
158 self.raise_geo_restricted(countries=['IN'])
159 self._sort_formats(formats)
160
161 return {
162 'id': video_id,
163 'title': title,
164 'description': video_data.get('description'),
165 'duration': int_or_none(video_data.get('duration')),
166 'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
167 'formats': formats,
168 'channel': video_data.get('channelName'),
169 'channel_id': video_data.get('channelId'),
170 'series': video_data.get('showName'),
171 'season': video_data.get('seasonName'),
172 'season_number': int_or_none(video_data.get('seasonNo')),
173 'season_id': video_data.get('seasonId'),
174 'episode': title,
175 'episode_number': int_or_none(video_data.get('episodeNo')),
176 }
177
178
179 class HotStarPlaylistIE(HotStarBaseIE):
180 IE_NAME = 'hotstar:playlist'
181 _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)'
182 _TESTS = [{
183 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
184 'info_dict': {
185 'id': '3_2_26',
186 },
187 'playlist_mincount': 20,
188 }, {
189 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
190 'only_matching': True,
191 }]
192
193 def _real_extract(self, url):
194 playlist_id = self._match_id(url)
195
196 collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')
197
198 entries = [
199 self.url_result(
200 'https://www.hotstar.com/%s' % video['contentId'],
201 ie=HotStarIE.ie_key(), video_id=video['contentId'])
202 for video in collection['assets']['items']
203 if video.get('contentId')]
204
205 return self.playlist_result(entries, playlist_id)