]> jfr.im git - yt-dlp.git/blob - youtube_dlc/extractor/viki.py
Update to ytdl-2021.01.03
[yt-dlp.git] / youtube_dlc / extractor / viki.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import hashlib
6 import hmac
7 import itertools
8 import json
9 import re
10 import time
11
12 from .common import InfoExtractor
13 from ..compat import (
14 compat_parse_qs,
15 compat_urllib_parse_urlparse,
16 )
17 from ..utils import (
18 ExtractorError,
19 int_or_none,
20 HEADRequest,
21 parse_age_limit,
22 parse_iso8601,
23 sanitized_Request,
24 std_headers,
25 )
26
27
28 class VikiBaseIE(InfoExtractor):
29 _VALID_URL_BASE = r'https?://(?:www\.)?viki\.(?:com|net|mx|jp|fr)/'
30 _API_QUERY_TEMPLATE = '/v4/%sapp=%s&t=%s&site=www.viki.com'
31 _API_URL_TEMPLATE = 'https://api.viki.io%s&sig=%s'
32
33 _APP = '100005a'
34 _APP_VERSION = '2.2.5.1428709186'
35 _APP_SECRET = 'MM_d*yP@`&1@]@!AVrXf_o-HVEnoTnm$O-ti4[G~$JDI/Dc-&piU&z&5.;:}95=Iad'
36
37 _GEO_BYPASS = False
38 _NETRC_MACHINE = 'viki'
39
40 _token = None
41
42 _ERRORS = {
43 'geo': 'Sorry, this content is not available in your region.',
44 'upcoming': 'Sorry, this content is not yet available.',
45 # 'paywall': 'paywall',
46 }
47
48 def _prepare_call(self, path, timestamp=None, post_data=None):
49 path += '?' if '?' not in path else '&'
50 if not timestamp:
51 timestamp = int(time.time())
52 query = self._API_QUERY_TEMPLATE % (path, self._APP, timestamp)
53 if self._token:
54 query += '&token=%s' % self._token
55 sig = hmac.new(
56 self._APP_SECRET.encode('ascii'),
57 query.encode('ascii'),
58 hashlib.sha1
59 ).hexdigest()
60 url = self._API_URL_TEMPLATE % (query, sig)
61 return sanitized_Request(
62 url, json.dumps(post_data).encode('utf-8')) if post_data else url
63
64 def _call_api(self, path, video_id, note, timestamp=None, post_data=None):
65 resp = self._download_json(
66 self._prepare_call(path, timestamp, post_data), video_id, note)
67
68 error = resp.get('error')
69 if error:
70 if error == 'invalid timestamp':
71 resp = self._download_json(
72 self._prepare_call(path, int(resp['current_timestamp']), post_data),
73 video_id, '%s (retry)' % note)
74 error = resp.get('error')
75 if error:
76 self._raise_error(resp['error'])
77
78 return resp
79
80 def _raise_error(self, error):
81 raise ExtractorError(
82 '%s returned error: %s' % (self.IE_NAME, error),
83 expected=True)
84
85 def _check_errors(self, data):
86 for reason, status in data.get('blocking', {}).items():
87 if status and reason in self._ERRORS:
88 message = self._ERRORS[reason]
89 if reason == 'geo':
90 self.raise_geo_restricted(msg=message)
91 raise ExtractorError('%s said: %s' % (
92 self.IE_NAME, message), expected=True)
93
94 def _real_initialize(self):
95 self._login()
96
97 def _login(self):
98 username, password = self._get_login_info()
99 if username is None:
100 return
101
102 login_form = {
103 'login_id': username,
104 'password': password,
105 }
106
107 login = self._call_api(
108 'sessions.json', None,
109 'Logging in', post_data=login_form)
110
111 self._token = login.get('token')
112 if not self._token:
113 self.report_warning('Unable to get session token, login has probably failed')
114
115 @staticmethod
116 def dict_selection(dict_obj, preferred_key, allow_fallback=True):
117 if preferred_key in dict_obj:
118 return dict_obj.get(preferred_key)
119
120 if not allow_fallback:
121 return
122
123 filtered_dict = list(filter(None, [dict_obj.get(k) for k in dict_obj.keys()]))
124 return filtered_dict[0] if filtered_dict else None
125
126
127 class VikiIE(VikiBaseIE):
128 IE_NAME = 'viki'
129 _VALID_URL = r'%s(?:videos|player)/(?P<id>[0-9]+v)' % VikiBaseIE._VALID_URL_BASE
130 _TESTS = [{
131 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
132 'info_dict': {
133 'id': '1023585v',
134 'ext': 'mp4',
135 'title': 'Heirs Episode 14',
136 'uploader': 'SBS',
137 'description': 'md5:c4b17b9626dd4b143dcc4d855ba3474e',
138 'upload_date': '20131121',
139 'age_limit': 13,
140 },
141 'skip': 'Blocked in the US',
142 }, {
143 # clip
144 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
145 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
146 'info_dict': {
147 'id': '1067139v',
148 'ext': 'mp4',
149 'title': "'The Avengers: Age of Ultron' Press Conference",
150 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
151 'duration': 352,
152 'timestamp': 1430380829,
153 'upload_date': '20150430',
154 'uploader': 'Arirang TV',
155 'like_count': int,
156 'age_limit': 0,
157 }
158 }, {
159 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
160 'info_dict': {
161 'id': '1048879v',
162 'ext': 'mp4',
163 'title': 'Ankhon Dekhi',
164 'duration': 6512,
165 'timestamp': 1408532356,
166 'upload_date': '20140820',
167 'uploader': 'Spuul',
168 'like_count': int,
169 'age_limit': 13,
170 },
171 'skip': 'Blocked in the US',
172 }, {
173 # episode
174 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
175 'md5': '94e0e34fd58f169f40c184f232356cfe',
176 'info_dict': {
177 'id': '44699v',
178 'ext': 'mp4',
179 'title': 'Boys Over Flowers - Episode 1',
180 'description': 'md5:b89cf50038b480b88b5b3c93589a9076',
181 'duration': 4172,
182 'timestamp': 1270496524,
183 'upload_date': '20100405',
184 'uploader': 'group8',
185 'like_count': int,
186 'age_limit': 13,
187 },
188 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
189 }, {
190 # youtube external
191 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
192 'md5': '63f8600c1da6f01b7640eee7eca4f1da',
193 'info_dict': {
194 'id': '50562v',
195 'ext': 'webm',
196 'title': 'Poor Nastya [COMPLETE] - Episode 1',
197 'description': '',
198 'duration': 606,
199 'timestamp': 1274949505,
200 'upload_date': '20101213',
201 'uploader': 'ad14065n',
202 'uploader_id': 'ad14065n',
203 'like_count': int,
204 'age_limit': 13,
205 },
206 'skip': 'Page not found!',
207 }, {
208 'url': 'http://www.viki.com/player/44699v',
209 'only_matching': True,
210 }, {
211 # non-English description
212 'url': 'http://www.viki.com/videos/158036v-love-in-magic',
213 'md5': 'adf9e321a0ae5d0aace349efaaff7691',
214 'info_dict': {
215 'id': '158036v',
216 'ext': 'mp4',
217 'uploader': 'I Planet Entertainment',
218 'upload_date': '20111122',
219 'timestamp': 1321985454,
220 'description': 'md5:44b1e46619df3a072294645c770cef36',
221 'title': 'Love In Magic',
222 'age_limit': 13,
223 },
224 }]
225
226 def _real_extract(self, url):
227 video_id = self._match_id(url)
228
229 resp = self._download_json(
230 'https://www.viki.com/api/videos/' + video_id,
231 video_id, 'Downloading video JSON', headers={
232 'x-client-user-agent': std_headers['User-Agent'],
233 'x-viki-app-ver': '4.0.57',
234 })
235 video = resp['video']
236
237 self._check_errors(video)
238
239 title = self.dict_selection(video.get('titles', {}), 'en', allow_fallback=False)
240 if not title:
241 title = 'Episode %d' % video.get('number') if video.get('type') == 'episode' else video.get('id') or video_id
242 container_titles = video.get('container', {}).get('titles', {})
243 container_title = self.dict_selection(container_titles, 'en')
244 title = '%s - %s' % (container_title, title)
245
246 description = self.dict_selection(video.get('descriptions', {}), 'en')
247
248 duration = int_or_none(video.get('duration'))
249 timestamp = parse_iso8601(video.get('created_at'))
250 uploader = video.get('author')
251 like_count = int_or_none(video.get('likes', {}).get('count'))
252 age_limit = parse_age_limit(video.get('rating'))
253
254 thumbnails = []
255 for thumbnail_id, thumbnail in video.get('images', {}).items():
256 thumbnails.append({
257 'id': thumbnail_id,
258 'url': thumbnail.get('url'),
259 })
260
261 subtitles = {}
262 try:
263 # New way to fetch subtitles
264 new_video = self._download_json(
265 'https://www.viki.com/api/videos/%s' % video_id, video_id,
266 'Downloading new video JSON to get subtitles', fatal=False)
267 for sub in new_video.get('streamSubtitles').get('dash'):
268 subtitles[sub.get('srclang')] = [{
269 'ext': 'vtt',
270 'url': sub.get('src'),
271 'completion': sub.get('percentage'),
272 }]
273 except AttributeError:
274 # fall-back to the old way if there isn't a streamSubtitles attribute
275 for subtitle_lang, _ in video.get('subtitle_completions', {}).items():
276 subtitles[subtitle_lang] = [{
277 'ext': subtitles_format,
278 'url': self._prepare_call(
279 'videos/%s/subtitles/%s.%s' % (video_id, subtitle_lang, subtitles_format)),
280 } for subtitles_format in ('srt', 'vtt')]
281
282 result = {
283 'id': video_id,
284 'title': title,
285 'description': description,
286 'duration': duration,
287 'timestamp': timestamp,
288 'uploader': uploader,
289 'like_count': like_count,
290 'age_limit': age_limit,
291 'thumbnails': thumbnails,
292 'subtitles': subtitles,
293 }
294
295 formats = []
296
297 def add_format(format_id, format_dict, protocol='http'):
298 # rtmps URLs does not seem to work
299 if protocol == 'rtmps':
300 return
301 format_url = format_dict.get('url')
302 if not format_url:
303 return
304 format_drms = format_dict.get('drms')
305 format_stream_id = format_dict.get('id')
306 qs = compat_parse_qs(compat_urllib_parse_urlparse(format_url).query)
307 stream = qs.get('stream', [None])[0]
308 if stream:
309 format_url = base64.b64decode(stream).decode()
310 if format_id in ('m3u8', 'hls'):
311 m3u8_formats = self._extract_m3u8_formats(
312 format_url, video_id, 'mp4',
313 entry_protocol='m3u8_native',
314 m3u8_id='m3u8-%s' % protocol, fatal=False)
315 # Despite CODECS metadata in m3u8 all video-only formats
316 # are actually video+audio
317 for f in m3u8_formats:
318 if '_drm/index_' in f['url']:
319 continue
320 if f.get('acodec') == 'none' and f.get('vcodec') != 'none':
321 f['acodec'] = None
322 formats.append(f)
323 elif format_id in ('mpd', 'dash'):
324 formats.extend(self._extract_mpd_formats(
325 format_url, video_id, 'mpd-%s' % protocol, fatal=False))
326 elif format_url.startswith('rtmp'):
327 mobj = re.search(
328 r'^(?P<url>rtmp://[^/]+/(?P<app>.+?))/(?P<playpath>mp4:.+)$',
329 format_url)
330 if not mobj:
331 return
332 formats.append({
333 'format_id': 'rtmp-%s' % format_id,
334 'ext': 'flv',
335 'url': mobj.group('url'),
336 'play_path': mobj.group('playpath'),
337 'app': mobj.group('app'),
338 'page_url': url,
339 'drms': format_drms,
340 'stream_id': format_stream_id,
341 })
342 else:
343 urlh = self._request_webpage(
344 HEADRequest(format_url), video_id, 'Checking file size', fatal=False)
345 formats.append({
346 'url': format_url,
347 'format_id': '%s-%s' % (format_id, protocol),
348 'height': int_or_none(self._search_regex(
349 r'^(\d+)[pP]$', format_id, 'height', default=None)),
350 'drms': format_drms,
351 'stream_id': format_stream_id,
352 'filesize': int_or_none(urlh.headers.get('Content-Length')),
353 })
354
355 for format_id, format_dict in (resp.get('streams') or {}).items():
356 add_format(format_id, format_dict)
357 if not formats:
358 streams = self._call_api(
359 'videos/%s/streams.json' % video_id, video_id,
360 'Downloading video streams JSON')
361
362 if 'external' in streams:
363 result.update({
364 '_type': 'url_transparent',
365 'url': streams['external']['url'],
366 })
367 return result
368
369 for format_id, stream_dict in streams.items():
370 for protocol, format_dict in stream_dict.items():
371 add_format(format_id, format_dict, protocol)
372 self._sort_formats(formats)
373
374 result['formats'] = formats
375 return result
376
377
378 class VikiChannelIE(VikiBaseIE):
379 IE_NAME = 'viki:channel'
380 _VALID_URL = r'%s(?:tv|news|movies|artists)/(?P<id>[0-9]+c)' % VikiBaseIE._VALID_URL_BASE
381 _TESTS = [{
382 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
383 'info_dict': {
384 'id': '50c',
385 'title': 'Boys Over Flowers',
386 'description': 'md5:ecd3cff47967fe193cff37c0bec52790',
387 },
388 'playlist_mincount': 71,
389 }, {
390 'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
391 'info_dict': {
392 'id': '1354c',
393 'title': 'Poor Nastya [COMPLETE]',
394 'description': 'md5:05bf5471385aa8b21c18ad450e350525',
395 },
396 'playlist_count': 127,
397 }, {
398 'url': 'http://www.viki.com/news/24569c-showbiz-korea',
399 'only_matching': True,
400 }, {
401 'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
402 'only_matching': True,
403 }, {
404 'url': 'http://www.viki.com/artists/2141c-shinee',
405 'only_matching': True,
406 }]
407
408 _PER_PAGE = 25
409
410 def _real_extract(self, url):
411 channel_id = self._match_id(url)
412
413 channel = self._call_api(
414 'containers/%s.json' % channel_id, channel_id,
415 'Downloading channel JSON')
416
417 self._check_errors(channel)
418
419 title = self.dict_selection(channel['titles'], 'en')
420
421 description = self.dict_selection(channel['descriptions'], 'en')
422
423 entries = []
424 for video_type in ('episodes', 'clips', 'movies'):
425 for page_num in itertools.count(1):
426 page = self._call_api(
427 'containers/%s/%s.json?per_page=%d&sort=number&direction=asc&with_paging=true&page=%d'
428 % (channel_id, video_type, self._PER_PAGE, page_num), channel_id,
429 'Downloading %s JSON page #%d' % (video_type, page_num))
430 for video in page['response']:
431 video_id = video['id']
432 entries.append(self.url_result(
433 'https://www.viki.com/videos/%s' % video_id, 'Viki'))
434 if not page['pagination']['next']:
435 break
436
437 return self.playlist_result(entries, channel_id, title, description)