[hotstar] Add support for alternative app state layout (closes #18320)
[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 time
7
8 from .common import InfoExtractor
9 from ..compat import compat_HTTPError
10 from ..utils import (
11     determine_ext,
12     ExtractorError,
13     int_or_none,
14     try_get,
15 )
16
17
18 class HotStarBaseIE(InfoExtractor):
19     _AKAMAI_ENCRYPTION_KEY = b'\x05\xfc\x1a\x01\xca\xc9\x4b\xc4\x12\xfc\x53\x12\x07\x75\xf9\xee'
20
21     def _call_api(self, path, video_id, query_name='contentId'):
22         st = int(time.time())
23         exp = st + 6000
24         auth = 'st=%d~exp=%d~acl=/*' % (st, exp)
25         auth += '~hmac=' + hmac.new(self._AKAMAI_ENCRYPTION_KEY, auth.encode(), hashlib.sha256).hexdigest()
26         response = self._download_json(
27             'https://api.hotstar.com/' + path,
28             video_id, headers={
29                 'hotstarauth': auth,
30                 'x-country-code': 'IN',
31                 'x-platform-code': 'JIO',
32             }, query={
33                 query_name: video_id,
34                 'tas': 10000,
35             })
36         if response['statusCode'] != 'OK':
37             raise ExtractorError(
38                 response['body']['message'], expected=True)
39         return response['body']['results']
40
41
42 class HotStarIE(HotStarBaseIE):
43     IE_NAME = 'hotstar'
44     _VALID_URL = r'https?://(?:www\.)?hotstar\.com/(?:.+?[/-])?(?P<id>\d{10})'
45     _TESTS = [{
46         # contentData
47         'url': 'https://www.hotstar.com/can-you-not-spread-rumours/1000076273',
48         'info_dict': {
49             'id': '1000076273',
50             'ext': 'mp4',
51             'title': 'Can You Not Spread Rumours?',
52             'description': 'md5:c957d8868e9bc793ccb813691cc4c434',
53             'timestamp': 1447248600,
54             'upload_date': '20151111',
55             'duration': 381,
56         },
57         'params': {
58             # m3u8 download
59             'skip_download': True,
60         }
61     }, {
62         # contentDetail
63         'url': 'https://www.hotstar.com/movies/radha-gopalam/1000057157',
64         'only_matching': True,
65     }, {
66         'url': 'http://www.hotstar.com/sports/cricket/rajitha-sizzles-on-debut-with-329/2001477583',
67         'only_matching': True,
68     }, {
69         'url': 'http://www.hotstar.com/1000000515',
70         'only_matching': True,
71     }]
72     _GEO_BYPASS = False
73
74     def _real_extract(self, url):
75         video_id = self._match_id(url)
76
77         webpage = self._download_webpage(url, video_id)
78         app_state = self._parse_json(self._search_regex(
79             r'<script>window\.APP_STATE\s*=\s*({.+?})</script>',
80             webpage, 'app state'), video_id)
81         video_data = {}
82         getters = (
83             lambda x, k=k: x['initialState']['content%s' % k]['content']
84             for k in ('Data', 'Detail')
85         )
86         for v in app_state.values():
87             content = try_get(v, getters, dict)
88             if content and content.get('contentId') == video_id:
89                 video_data = content
90
91         title = video_data['title']
92
93         if video_data.get('drmProtected'):
94             raise ExtractorError('This video is DRM protected.', expected=True)
95
96         formats = []
97         format_data = self._call_api('h/v1/play', video_id)['item']
98         format_url = format_data['playbackUrl']
99         ext = determine_ext(format_url)
100         if ext == 'm3u8':
101             try:
102                 formats.extend(self._extract_m3u8_formats(
103                     format_url, video_id, 'mp4', m3u8_id='hls'))
104             except ExtractorError as e:
105                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
106                     self.raise_geo_restricted(countries=['IN'])
107                 raise
108         elif ext == 'f4m':
109             # produce broken files
110             pass
111         else:
112             formats.append({
113                 'url': format_url,
114                 'width': int_or_none(format_data.get('width')),
115                 'height': int_or_none(format_data.get('height')),
116             })
117         self._sort_formats(formats)
118
119         return {
120             'id': video_id,
121             'title': title,
122             'description': video_data.get('description'),
123             'duration': int_or_none(video_data.get('duration')),
124             'timestamp': int_or_none(video_data.get('broadcastDate') or video_data.get('startDate')),
125             'formats': formats,
126             'channel': video_data.get('channelName'),
127             'channel_id': video_data.get('channelId'),
128             'series': video_data.get('showName'),
129             'season': video_data.get('seasonName'),
130             'season_number': int_or_none(video_data.get('seasonNo')),
131             'season_id': video_data.get('seasonId'),
132             'episode': title,
133             'episode_number': int_or_none(video_data.get('episodeNo')),
134         }
135
136
137 class HotStarPlaylistIE(HotStarBaseIE):
138     IE_NAME = 'hotstar:playlist'
139     _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)'
140     _TESTS = [{
141         'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26',
142         'info_dict': {
143             'id': '3_2_26',
144         },
145         'playlist_mincount': 20,
146     }, {
147         'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/extras/t-2480',
148         'only_matching': True,
149     }]
150
151     def _real_extract(self, url):
152         playlist_id = self._match_id(url)
153
154         collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')
155
156         entries = [
157             self.url_result(
158                 'https://www.hotstar.com/%s' % video['contentId'],
159                 ie=HotStarIE.ie_key(), video_id=video['contentId'])
160             for video in collection['assets']['items']
161             if video.get('contentId')]
162
163         return self.playlist_result(entries, playlist_id)