]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/vrv.py
[extractor] Deprecate `_sort_formats`
[yt-dlp.git] / yt_dlp / extractor / vrv.py
CommitLineData
77c8ebe6 1import base64
77c8ebe6
RA
2import hashlib
3import hmac
ac668111 4import json
77c8ebe6
RA
5import random
6import string
7import time
ac668111 8import urllib.parse
77c8ebe6
RA
9
10from .common import InfoExtractor
ac668111 11from ..compat import compat_HTTPError, compat_urllib_parse_urlencode
77c8ebe6 12from ..utils import (
4b85f0f9 13 ExtractorError,
77c8ebe6
RA
14 float_or_none,
15 int_or_none,
34921b43 16 join_nonempty,
7bb64347 17 traverse_obj,
77c8ebe6
RA
18)
19
20
48ab554f 21class VRVBaseIE(InfoExtractor):
77c8ebe6
RA
22 _API_DOMAIN = None
23 _API_PARAMS = {}
24 _CMS_SIGNING = {}
4b85f0f9
RA
25 _TOKEN = None
26 _TOKEN_SECRET = ''
77c8ebe6
RA
27
28 def _call_api(self, path, video_id, note, data=None):
4b85f0f9 29 # https://tools.ietf.org/html/rfc5849#section-3
77c8ebe6 30 base_url = self._API_DOMAIN + '/core/' + path
503b604a
RA
31 query = [
32 ('oauth_consumer_key', self._API_PARAMS['oAuthKey']),
33 ('oauth_nonce', ''.join([random.choice(string.ascii_letters) for _ in range(32)])),
34 ('oauth_signature_method', 'HMAC-SHA1'),
35 ('oauth_timestamp', int(time.time())),
36 ]
4b85f0f9 37 if self._TOKEN:
503b604a 38 query.append(('oauth_token', self._TOKEN))
4b85f0f9 39 encoded_query = compat_urllib_parse_urlencode(query)
77c8ebe6
RA
40 headers = self.geo_verification_headers()
41 if data:
42 data = json.dumps(data).encode()
43 headers['Content-Type'] = 'application/json'
4b85f0f9
RA
44 base_string = '&'.join([
45 'POST' if data else 'GET',
ac668111 46 urllib.parse.quote(base_url, ''),
47 urllib.parse.quote(encoded_query, '')])
77c8ebe6 48 oauth_signature = base64.b64encode(hmac.new(
4b85f0f9 49 (self._API_PARAMS['oAuthSecret'] + '&' + self._TOKEN_SECRET).encode('ascii'),
77c8ebe6 50 base_string.encode(), hashlib.sha1).digest()).decode()
ac668111 51 encoded_query += '&oauth_signature=' + urllib.parse.quote(oauth_signature, '')
4b85f0f9
RA
52 try:
53 return self._download_json(
54 '?'.join([base_url, encoded_query]), video_id,
55 note='Downloading %s JSON metadata' % note, headers=headers, data=data)
56 except ExtractorError as e:
57 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
58 raise ExtractorError(json.loads(e.cause.read().decode())['message'], expected=True)
59 raise
77c8ebe6
RA
60
61 def _call_cms(self, path, video_id, note):
48ab554f 62 if not self._CMS_SIGNING:
1824bfdc
RA
63 index = self._call_api('index', video_id, 'CMS Signing')
64 self._CMS_SIGNING = index.get('cms_signing') or {}
65 if not self._CMS_SIGNING:
66 for signing_policy in index.get('signing_policies', []):
67 signing_path = signing_policy.get('path')
68 if signing_path and signing_path.startswith('/cms/'):
69 name, value = signing_policy.get('name'), signing_policy.get('value')
70 if name and value:
71 self._CMS_SIGNING[name] = value
77c8ebe6
RA
72 return self._download_json(
73 self._API_DOMAIN + path, video_id, query=self._CMS_SIGNING,
74 note='Downloading %s JSON metadata' % note, headers=self.geo_verification_headers())
75
48ab554f
RA
76 def _get_cms_resource(self, resource_key, video_id):
77 return self._call_api(
78 'cms_resource', video_id, 'resource path', data={
79 'resource_key': resource_key,
80 })['__links__']['cms_resource']['href']
81
11078c6d 82 def _extract_vrv_formats(self, url, video_id, stream_format, audio_lang, hardsub_lang):
83 if not url or stream_format not in ('hls', 'dash', 'adaptive_hls'):
84 return []
85 format_id = join_nonempty(
86 stream_format,
87 audio_lang and 'audio-%s' % audio_lang,
88 hardsub_lang and 'hardsub-%s' % hardsub_lang)
89 if 'hls' in stream_format:
90 adaptive_formats = self._extract_m3u8_formats(
91 url, video_id, 'mp4', m3u8_id=format_id,
92 note='Downloading %s information' % format_id,
93 fatal=False)
94 elif stream_format == 'dash':
95 adaptive_formats = self._extract_mpd_formats(
96 url, video_id, mpd_id=format_id,
97 note='Downloading %s information' % format_id,
98 fatal=False)
99 if audio_lang:
100 for f in adaptive_formats:
101 if f.get('acodec') != 'none':
102 f['language'] = audio_lang
103 return adaptive_formats
104
105 def _set_api_params(self):
4b85f0f9
RA
106 webpage = self._download_webpage(
107 'https://vrv.co/', None, headers=self.geo_verification_headers())
108 self._API_PARAMS = self._parse_json(self._search_regex(
109 [
110 r'window\.__APP_CONFIG__\s*=\s*({.+?})(?:</script>|;)',
111 r'window\.__APP_CONFIG__\s*=\s*({.+})'
112 ], webpage, 'app config'), None)['cxApiParams']
113 self._API_DOMAIN = self._API_PARAMS.get('apiDomain', 'https://api.vrv.co')
114
48ab554f
RA
115
116class VRVIE(VRVBaseIE):
117 IE_NAME = 'vrv'
118 _VALID_URL = r'https?://(?:www\.)?vrv\.co/watch/(?P<id>[A-Z0-9]+)'
54a5be4d 119 _TESTS = [{
48ab554f
RA
120 'url': 'https://vrv.co/watch/GR9PNZ396/Hidden-America-with-Jonah-Ray:BOSTON-WHERE-THE-PAST-IS-THE-PRESENT',
121 'info_dict': {
122 'id': 'GR9PNZ396',
123 'ext': 'mp4',
124 'title': 'BOSTON: WHERE THE PAST IS THE PRESENT',
125 'description': 'md5:4ec8844ac262ca2df9e67c0983c6b83f',
126 'uploader_id': 'seeso',
127 },
128 'params': {
129 # m3u8 download
130 'skip_download': True,
131 },
1fa88937
RA
132 }, {
133 # movie listing
134 'url': 'https://vrv.co/watch/G6NQXZ1J6/Lily-CAT',
135 'info_dict': {
136 'id': 'G6NQXZ1J6',
137 'title': 'Lily C.A.T',
138 'description': 'md5:988b031e7809a6aeb60968be4af7db07',
139 },
140 'playlist_count': 2,
54a5be4d 141 }]
4b85f0f9
RA
142 _NETRC_MACHINE = 'vrv'
143
52efa4b3 144 def _perform_login(self, username, password):
4b85f0f9
RA
145 token_credentials = self._call_api(
146 'authenticate/by:credentials', None, 'Token Credentials', data={
52efa4b3 147 'email': username,
4b85f0f9
RA
148 'password': password,
149 })
150 self._TOKEN = token_credentials['oauth_token']
151 self._TOKEN_SECRET = token_credentials['oauth_token_secret']
54a5be4d 152
11078c6d 153 def _initialize_pre_login(self):
154 return self._set_api_params()
77c8ebe6
RA
155
156 def _real_extract(self, url):
157 video_id = self._match_id(url)
4b85f0f9 158
9f182c23
RA
159 object_data = self._call_cms(self._get_cms_resource(
160 'cms:/objects/' + video_id, video_id), video_id, 'object')['items'][0]
161 resource_path = object_data['__links__']['resource']['href']
162 video_data = self._call_cms(resource_path, video_id, 'video')
77c8ebe6 163 title = video_data['title']
1fa88937
RA
164 description = video_data.get('description')
165
166 if video_data.get('__class__') == 'movie_listing':
167 items = self._call_cms(
168 video_data['__links__']['movie_listing/movies']['href'],
169 video_id, 'movie listing').get('items') or []
170 if len(items) != 1:
171 entries = []
172 for item in items:
173 item_id = item.get('id')
174 if not item_id:
175 continue
176 entries.append(self.url_result(
177 'https://vrv.co/watch/' + item_id,
178 self.ie_key(), item_id, item.get('title')))
179 return self.playlist_result(entries, video_id, title, description)
180 video_data = items[0]
77c8ebe6 181
4b85f0f9
RA
182 streams_path = video_data['__links__'].get('streams', {}).get('href')
183 if not streams_path:
184 self.raise_login_required()
185 streams_json = self._call_cms(streams_path, video_id, 'streams')
77c8ebe6
RA
186
187 audio_locale = streams_json.get('audio_locale')
188 formats = []
afa0200b
RA
189 for stream_type, streams in streams_json.get('streams', {}).items():
190 if stream_type in ('adaptive_hls', 'adaptive_dash'):
191 for stream in streams.values():
54a5be4d
RA
192 formats.extend(self._extract_vrv_formats(
193 stream.get('url'), video_id, stream_type.split('_')[1],
194 audio_locale, stream.get('hardsub_locale')))
77c8ebe6 195
afa0200b 196 subtitles = {}
58317428
RA
197 for k in ('captions', 'subtitles'):
198 for subtitle in streams_json.get(k, {}).values():
199 subtitle_url = subtitle.get('url')
200 if not subtitle_url:
201 continue
202 subtitles.setdefault(subtitle.get('locale', 'en-US'), []).append({
203 'url': subtitle_url,
204 'ext': subtitle.get('format', 'ass'),
205 })
afa0200b 206
77c8ebe6 207 thumbnails = []
f7590d47 208 for thumbnail in traverse_obj(video_data, ('images', 'thumbnail', ..., ...)) or []:
77c8ebe6
RA
209 thumbnail_url = thumbnail.get('source')
210 if not thumbnail_url:
211 continue
212 thumbnails.append({
213 'url': thumbnail_url,
214 'width': int_or_none(thumbnail.get('width')),
215 'height': int_or_none(thumbnail.get('height')),
216 })
217
218 return {
219 'id': video_id,
220 'title': title,
221 'formats': formats,
afa0200b 222 'subtitles': subtitles,
77c8ebe6 223 'thumbnails': thumbnails,
1fa88937 224 'description': description,
77c8ebe6
RA
225 'duration': float_or_none(video_data.get('duration_ms'), 1000),
226 'uploader_id': video_data.get('channel_id'),
227 'series': video_data.get('series_title'),
228 'season': video_data.get('season_title'),
229 'season_number': int_or_none(video_data.get('season_number')),
230 'season_id': video_data.get('season_id'),
231 'episode': title,
232 'episode_number': int_or_none(video_data.get('episode_number')),
233 'episode_id': video_data.get('production_episode_id'),
234 }
48ab554f
RA
235
236
237class VRVSeriesIE(VRVBaseIE):
238 IE_NAME = 'vrv:series'
239 _VALID_URL = r'https?://(?:www\.)?vrv\.co/series/(?P<id>[A-Z0-9]+)'
240 _TEST = {
241 'url': 'https://vrv.co/series/G68VXG3G6/The-Perfect-Insider',
242 'info_dict': {
243 'id': 'G68VXG3G6',
244 },
245 'playlist_mincount': 11,
246 }
247
11078c6d 248 def _initialize_pre_login(self):
249 return self._set_api_params()
250
48ab554f
RA
251 def _real_extract(self, url):
252 series_id = self._match_id(url)
48ab554f 253
48ab554f
RA
254 seasons_path = self._get_cms_resource(
255 'cms:/seasons?series_id=' + series_id, series_id)
256 seasons_data = self._call_cms(seasons_path, series_id, 'seasons')
257
258 entries = []
259 for season in seasons_data.get('items', []):
260 episodes_path = season['__links__']['season/episodes']['href']
261 episodes = self._call_cms(episodes_path, series_id, 'episodes')
262 for episode in episodes.get('items', []):
263 episode_id = episode['id']
264 entries.append(self.url_result(
265 'https://vrv.co/watch/' + episode_id,
266 'VRV', episode_id, episode.get('title')))
267
268 return self.playlist_result(entries, series_id)