[hotstar] Extract more formats (closes #22323)
[youtube-dl] / 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', m3u8_id='hls'))
140                 elif 'package:dash' in tags or ext == 'mpd':
141                     formats.extend(self._extract_mpd_formats(
142                         format_url, video_id, mpd_id='dash'))
143                 elif ext == 'f4m':
144                     # produce broken files
145                     pass
146                 else:
147                     formats.append({
148                         'url': format_url,
149                         'width': int_or_none(playback_set.get('width')),
150                         'height': int_or_none(playback_set.get('height')),
151                     })
152             except ExtractorError as e:
153                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
154                     geo_restricted = True
155                 continue
156         if not formats and geo_restricted:
157             self.raise_geo_restricted(countries=['IN'])
158         self._sort_formats(formats)
159
160         return {
161             'id': video_id,
162             'title': title,
163             'description': video_data.get('description'),
164             'duration': int_or_none(video_data.get('duration')),
165             'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
166             'formats': formats,
167             'channel': video_data.get('channelName'),
168             'channel_id': video_data.get('channelId'),
169             'series': video_data.get('showName'),
170             'season': video_data.get('seasonName'),
171             'season_number': int_or_none(video_data.get('seasonNo')),
172             'season_id': video_data.get('seasonId'),
173             'episode': title,
174             'episode_number': int_or_none(video_data.get('episodeNo')),
175         }
176
177
178 class HotStarPlaylistIE(HotStarBaseIE):
179     IE_NAME = 'hotstar:playlist'
180     _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)'
181     _TESTS = [{
182         'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
183         'info_dict': {
184             'id': '3_2_26',
185         },
186         'playlist_mincount': 20,
187     }, {
188         'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
189         'only_matching': True,
190     }]
191
192     def _real_extract(self, url):
193         playlist_id = self._match_id(url)
194
195         collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')
196
197         entries = [
198             self.url_result(
199                 'https://www.hotstar.com/%s' % video['contentId'],
200                 ie=HotStarIE.ie_key(), video_id=video['contentId'])
201             for video in collection['assets']['items']
202             if video.get('contentId')]
203
204         return self.playlist_result(entries, playlist_id)