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