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