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