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