]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/vrv.py
[yahoo] add support for gyao.yahoo.co.jp
[yt-dlp.git] / youtube_dl / extractor / vrv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import json
6 import hashlib
7 import hmac
8 import random
9 import string
10 import time
11
12 from .common import InfoExtractor
13 from ..compat import (
14 compat_HTTPError,
15 compat_urllib_parse_urlencode,
16 compat_urllib_parse,
17 )
18 from ..utils import (
19 ExtractorError,
20 float_or_none,
21 int_or_none,
22 )
23
24
25 class VRVBaseIE(InfoExtractor):
26 _API_DOMAIN = None
27 _API_PARAMS = {}
28 _CMS_SIGNING = {}
29 _TOKEN = None
30 _TOKEN_SECRET = ''
31
32 def _call_api(self, path, video_id, note, data=None):
33 # https://tools.ietf.org/html/rfc5849#section-3
34 base_url = self._API_DOMAIN + '/core/' + path
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 ]
41 if self._TOKEN:
42 query.append(('oauth_token', self._TOKEN))
43 encoded_query = compat_urllib_parse_urlencode(query)
44 headers = self.geo_verification_headers()
45 if data:
46 data = json.dumps(data).encode()
47 headers['Content-Type'] = 'application/json'
48 base_string = '&'.join([
49 'POST' if data else 'GET',
50 compat_urllib_parse.quote(base_url, ''),
51 compat_urllib_parse.quote(encoded_query, '')])
52 oauth_signature = base64.b64encode(hmac.new(
53 (self._API_PARAMS['oAuthSecret'] + '&' + self._TOKEN_SECRET).encode('ascii'),
54 base_string.encode(), hashlib.sha1).digest()).decode()
55 encoded_query += '&oauth_signature=' + compat_urllib_parse.quote(oauth_signature, '')
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
64
65 def _call_cms(self, path, video_id, note):
66 if not self._CMS_SIGNING:
67 self._CMS_SIGNING = self._call_api('index', video_id, 'CMS Signing')['cms_signing']
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
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
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
88
89 class VRVIE(VRVBaseIE):
90 IE_NAME = 'vrv'
91 _VALID_URL = r'https?://(?:www\.)?vrv\.co/watch/(?P<id>[A-Z0-9]+)'
92 _TESTS = [{
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 },
105 }]
106 _NETRC_MACHINE = 'vrv'
107
108 def _real_initialize(self):
109 super(VRVIE, self)._real_initialize()
110
111 email, password = self._get_login_info()
112 if email is None:
113 return
114
115 token_credentials = self._call_api(
116 'authenticate/by:credentials', None, 'Token Credentials', data={
117 'email': email,
118 'password': password,
119 })
120 self._TOKEN = token_credentials['oauth_token']
121 self._TOKEN_SECRET = token_credentials['oauth_token_secret']
122
123 def _extract_vrv_formats(self, url, video_id, stream_format, audio_lang, hardsub_lang):
124 if not url or stream_format not in ('hls', 'dash'):
125 return []
126 assert audio_lang or hardsub_lang
127 stream_id_list = []
128 if audio_lang:
129 stream_id_list.append('audio-%s' % audio_lang)
130 if hardsub_lang:
131 stream_id_list.append('hardsub-%s' % hardsub_lang)
132 stream_id = '-'.join(stream_id_list)
133 format_id = '%s-%s' % (stream_format, stream_id)
134 if stream_format == 'hls':
135 adaptive_formats = self._extract_m3u8_formats(
136 url, video_id, 'mp4', m3u8_id=format_id,
137 note='Downloading %s m3u8 information' % stream_id,
138 fatal=False)
139 elif stream_format == 'dash':
140 adaptive_formats = self._extract_mpd_formats(
141 url, video_id, mpd_id=format_id,
142 note='Downloading %s MPD information' % stream_id,
143 fatal=False)
144 if audio_lang:
145 for f in adaptive_formats:
146 if f.get('acodec') != 'none':
147 f['language'] = audio_lang
148 return adaptive_formats
149
150 def _real_extract(self, url):
151 video_id = self._match_id(url)
152
153 object_data = self._call_cms(self._get_cms_resource(
154 'cms:/objects/' + video_id, video_id), video_id, 'object')['items'][0]
155 resource_path = object_data['__links__']['resource']['href']
156 video_data = self._call_cms(resource_path, video_id, 'video')
157 title = video_data['title']
158
159 streams_path = video_data['__links__'].get('streams', {}).get('href')
160 if not streams_path:
161 self.raise_login_required()
162 streams_json = self._call_cms(streams_path, video_id, 'streams')
163
164 audio_locale = streams_json.get('audio_locale')
165 formats = []
166 for stream_type, streams in streams_json.get('streams', {}).items():
167 if stream_type in ('adaptive_hls', 'adaptive_dash'):
168 for stream in streams.values():
169 formats.extend(self._extract_vrv_formats(
170 stream.get('url'), video_id, stream_type.split('_')[1],
171 audio_locale, stream.get('hardsub_locale')))
172 self._sort_formats(formats)
173
174 subtitles = {}
175 for subtitle in streams_json.get('subtitles', {}).values():
176 subtitle_url = subtitle.get('url')
177 if not subtitle_url:
178 continue
179 subtitles.setdefault(subtitle.get('locale', 'en-US'), []).append({
180 'url': subtitle_url,
181 'ext': subtitle.get('format', 'ass'),
182 })
183
184 thumbnails = []
185 for thumbnail in video_data.get('images', {}).get('thumbnails', []):
186 thumbnail_url = thumbnail.get('source')
187 if not thumbnail_url:
188 continue
189 thumbnails.append({
190 'url': thumbnail_url,
191 'width': int_or_none(thumbnail.get('width')),
192 'height': int_or_none(thumbnail.get('height')),
193 })
194
195 return {
196 'id': video_id,
197 'title': title,
198 'formats': formats,
199 'subtitles': subtitles,
200 'thumbnails': thumbnails,
201 'description': video_data.get('description'),
202 'duration': float_or_none(video_data.get('duration_ms'), 1000),
203 'uploader_id': video_data.get('channel_id'),
204 'series': video_data.get('series_title'),
205 'season': video_data.get('season_title'),
206 'season_number': int_or_none(video_data.get('season_number')),
207 'season_id': video_data.get('season_id'),
208 'episode': title,
209 'episode_number': int_or_none(video_data.get('episode_number')),
210 'episode_id': video_data.get('production_episode_id'),
211 }
212
213
214 class VRVSeriesIE(VRVBaseIE):
215 IE_NAME = 'vrv:series'
216 _VALID_URL = r'https?://(?:www\.)?vrv\.co/series/(?P<id>[A-Z0-9]+)'
217 _TEST = {
218 'url': 'https://vrv.co/series/G68VXG3G6/The-Perfect-Insider',
219 'info_dict': {
220 'id': 'G68VXG3G6',
221 },
222 'playlist_mincount': 11,
223 }
224
225 def _real_extract(self, url):
226 series_id = self._match_id(url)
227
228 seasons_path = self._get_cms_resource(
229 'cms:/seasons?series_id=' + series_id, series_id)
230 seasons_data = self._call_cms(seasons_path, series_id, 'seasons')
231
232 entries = []
233 for season in seasons_data.get('items', []):
234 episodes_path = season['__links__']['season/episodes']['href']
235 episodes = self._call_cms(episodes_path, series_id, 'episodes')
236 for episode in episodes.get('items', []):
237 episode_id = episode['id']
238 entries.append(self.url_result(
239 'https://vrv.co/watch/' + episode_id,
240 'VRV', episode_id, episode.get('title')))
241
242 return self.playlist_result(entries, series_id)