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