]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/viki.py
Completely change project name to yt-dlp (#85)
[yt-dlp.git] / yt_dlp / extractor / viki.py
CommitLineData
accf79b1 1# coding: utf-8
cb9722cb
PH
2from __future__ import unicode_literals
3
a0566bbf 4import base64
1a83c731 5import hashlib
9338a0ea 6import hmac
bc56355e 7import itertools
9338a0ea
S
8import json
9import re
10import time
382ed50e 11
5c2266df 12from .common import InfoExtractor
a0566bbf 13from ..compat import (
14 compat_parse_qs,
15 compat_urllib_parse_urlparse,
16)
382ed50e 17from ..utils import (
6d88bc37 18 ExtractorError,
1a83c731 19 int_or_none,
169bd46b 20 HEADRequest,
1a83c731
S
21 parse_age_limit,
22 parse_iso8601,
5c2266df 23 sanitized_Request,
38d70284 24 std_headers,
bc2ca1bb 25 try_get,
382ed50e 26)
382ed50e
PH
27
28
1a83c731 29class VikiBaseIE(InfoExtractor):
53de95da 30 _VALID_URL_BASE = r'https?://(?:www\.)?viki\.(?:com|net|mx|jp|fr)/'
1a83c731 31 _API_QUERY_TEMPLATE = '/v4/%sapp=%s&t=%s&site=www.viki.com'
26a87972 32 _API_URL_TEMPLATE = 'https://api.viki.io%s&sig=%s'
1a83c731 33
8251af63 34 _APP = '100005a'
5e41dca3 35 _APP_VERSION = '6.0.0'
8251af63 36 _APP_SECRET = 'MM_d*yP@`&1@]@!AVrXf_o-HVEnoTnm$O-ti4[G~$JDI/Dc-&piU&z&5.;:}95=Iad'
1a83c731 37
4248dad9 38 _GEO_BYPASS = False
accf79b1
S
39 _NETRC_MACHINE = 'viki'
40
16d6973f
S
41 _token = None
42
dc016bf5 43 _ERRORS = {
44 'geo': 'Sorry, this content is not available in your region.',
45 'upcoming': 'Sorry, this content is not yet available.',
bc2ca1bb 46 'paywall': 'Sorry, this content is only available to Viki Pass Plus subscribers',
dc016bf5 47 }
48
accf79b1 49 def _prepare_call(self, path, timestamp=None, post_data=None):
1a83c731
S
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)
16d6973f
S
54 if self._token:
55 query += '&token=%s' % self._token
1a83c731
S
56 sig = hmac.new(
57 self._APP_SECRET.encode('ascii'),
58 query.encode('ascii'),
59 hashlib.sha1
60 ).hexdigest()
accf79b1 61 url = self._API_URL_TEMPLATE % (query, sig)
5c2266df 62 return sanitized_Request(
accf79b1 63 url, json.dumps(post_data).encode('utf-8')) if post_data else url
1a83c731 64
accf79b1 65 def _call_api(self, path, video_id, note, timestamp=None, post_data=None):
1a83c731 66 resp = self._download_json(
5e41dca3 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 })
1a83c731
S
74
75 error = resp.get('error')
76 if error:
77 if error == 'invalid timestamp':
78 resp = self._download_json(
accf79b1 79 self._prepare_call(path, int(resp['current_timestamp']), post_data),
5e41dca3 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 })
1a83c731
S
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
dc016bf5 97 def _check_errors(self, data):
bc2ca1bb 98 for reason, status in (data.get('blocking') or {}).items():
dc016bf5 99 if status and reason in self._ERRORS:
5d3fbf77
S
100 message = self._ERRORS[reason]
101 if reason == 'geo':
102 self.raise_geo_restricted(msg=message)
bc2ca1bb 103 elif reason == 'paywall':
104 self.raise_login_required(message)
dc016bf5 105 raise ExtractorError('%s said: %s' % (
5d3fbf77 106 self.IE_NAME, message), expected=True)
dc016bf5 107
accf79b1
S
108 def _real_initialize(self):
109 self._login()
110
111 def _login(self):
68217024 112 username, password = self._get_login_info()
accf79b1
S
113 if username is None:
114 return
115
116 login_form = {
117 'login_id': username,
118 'password': password,
119 }
120
16d6973f 121 login = self._call_api(
accf79b1 122 'sessions.json', None,
e4d95865 123 'Logging in', post_data=login_form)
accf79b1 124
16d6973f
S
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
b73b14f7 129 @staticmethod
6d28c408 130 def dict_selection(dict_obj, preferred_key, allow_fallback=True):
b73b14f7
YCH
131 if preferred_key in dict_obj:
132 return dict_obj.get(preferred_key)
133
6d28c408
YCH
134 if not allow_fallback:
135 return
136
b73b14f7
YCH
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
1a83c731
S
140
141class VikiIE(VikiBaseIE):
cb9722cb 142 IE_NAME = 'viki'
53de95da 143 _VALID_URL = r'%s(?:videos|player)/(?P<id>[0-9]+v)' % VikiBaseIE._VALID_URL_BASE
8e3df9df 144 _TESTS = [{
cb9722cb 145 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
cb9722cb
PH
146 'info_dict': {
147 'id': '1023585v',
148 'ext': 'mp4',
bc2ca1bb 149 'title': 'Heirs - Episode 14',
150 'uploader': 'SBS Contents Hub',
151 'timestamp': 1385047627,
cb9722cb
PH
152 'upload_date': '20131121',
153 'age_limit': 13,
bc2ca1bb 154 'duration': 3570,
155 'episode_number': 14,
156 },
157 'params': {
158 'format': 'bestvideo',
6d88bc37 159 },
cb9722cb 160 'skip': 'Blocked in the US',
bc2ca1bb 161 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
8e3df9df 162 }, {
1a83c731 163 # clip
8e3df9df 164 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
10568217 165 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
8e3df9df
YCH
166 'info_dict': {
167 'id': '1067139v',
168 'ext': 'mp4',
1a83c731 169 'title': "'The Avengers: Age of Ultron' Press Conference",
8e3df9df 170 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
1a83c731
S
171 'duration': 352,
172 'timestamp': 1430380829,
8e3df9df 173 'upload_date': '20150430',
1a83c731
S
174 'uploader': 'Arirang TV',
175 'like_count': int,
176 'age_limit': 0,
bc2ca1bb 177 },
178 'skip': 'Sorry. There was an error loading this video',
d948e09b
YCH
179 }, {
180 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
181 'info_dict': {
182 'id': '1048879v',
183 'ext': 'mp4',
d948e09b 184 'title': 'Ankhon Dekhi',
1a83c731
S
185 'duration': 6512,
186 'timestamp': 1408532356,
187 'upload_date': '20140820',
188 'uploader': 'Spuul',
189 'like_count': int,
190 'age_limit': 13,
d948e09b 191 },
94e5d6ae 192 'skip': 'Blocked in the US',
1a83c731
S
193 }, {
194 # episode
195 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
bc2ca1bb 196 'md5': '0a53dc252e6e690feccd756861495a8c',
1a83c731
S
197 'info_dict': {
198 'id': '44699v',
199 'ext': 'mp4',
200 'title': 'Boys Over Flowers - Episode 1',
c83b35d4 201 'description': 'md5:b89cf50038b480b88b5b3c93589a9076',
a0566bbf 202 'duration': 4172,
1a83c731
S
203 'timestamp': 1270496524,
204 'upload_date': '20100405',
205 'uploader': 'group8',
206 'like_count': int,
207 'age_limit': 13,
bc2ca1bb 208 'episode_number': 1,
209 },
210 'params': {
211 'format': 'bestvideo',
a0566bbf 212 },
213 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
ac20d95f
S
214 }, {
215 # youtube external
216 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
f22ba4bd 217 'md5': '63f8600c1da6f01b7640eee7eca4f1da',
ac20d95f
S
218 'info_dict': {
219 'id': '50562v',
f22ba4bd 220 'ext': 'webm',
ac20d95f
S
221 'title': 'Poor Nastya [COMPLETE] - Episode 1',
222 'description': '',
f22ba4bd 223 'duration': 606,
ac20d95f
S
224 'timestamp': 1274949505,
225 'upload_date': '20101213',
226 'uploader': 'ad14065n',
227 'uploader_id': 'ad14065n',
228 'like_count': int,
229 'age_limit': 13,
a0566bbf 230 },
231 'skip': 'Page not found!',
1a83c731
S
232 }, {
233 'url': 'http://www.viki.com/player/44699v',
234 'only_matching': True,
41597d9b
YCH
235 }, {
236 # non-English description
237 'url': 'http://www.viki.com/videos/158036v-love-in-magic',
bc2ca1bb 238 'md5': '41faaba0de90483fb4848952af7c7d0d',
41597d9b
YCH
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',
dc016bf5 247 'age_limit': 13,
41597d9b 248 },
bc2ca1bb 249 'params': {
250 'format': 'bestvideo',
251 },
252 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
8e3df9df 253 }]
382ed50e
PH
254
255 def _real_extract(self, url):
8ee34150 256 video_id = self._match_id(url)
382ed50e 257
a0566bbf 258 resp = self._download_json(
259 'https://www.viki.com/api/videos/' + video_id,
38d70284 260 video_id, 'Downloading video JSON', headers={
261 'x-client-user-agent': std_headers['User-Agent'],
5e41dca3 262 'x-viki-as-id': self._APP,
263 'x-viki-app-ver': self._APP_VERSION,
38d70284 264 })
a0566bbf 265 video = resp['video']
169bd46b 266
dc016bf5 267 self._check_errors(video)
268
6d28c408 269 title = self.dict_selection(video.get('titles', {}), 'en', allow_fallback=False)
bc2ca1bb 270 episode_number = int_or_none(video.get('number'))
1a83c731 271 if not title:
bc2ca1bb 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 {}
b73b14f7
YCH
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')
1a83c731 278
bc2ca1bb 279 like_count = int_or_none(try_get(video, lambda x: x['likes']['count']))
1a83c731
S
280
281 thumbnails = []
bc2ca1bb 282 for thumbnail_id, thumbnail in (video.get('images') or {}).items():
1a83c731
S
283 thumbnails.append({
284 'id': thumbnail_id,
285 'url': thumbnail.get('url'),
286 })
287
288 subtitles = {}
142f2c8e
RD
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,
5e41dca3 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 })
142f2c8e
RD
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
bc2ca1bb 307 for subtitle_lang, _ in (video.get('subtitle_completions') or {}).items():
142f2c8e
RD
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')]
382ed50e 313
ac20d95f 314 result = {
382ed50e
PH
315 'id': video_id,
316 'title': title,
382ed50e 317 'description': description,
bc2ca1bb 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'),
1a83c731 322 'like_count': like_count,
bc2ca1bb 323 'age_limit': parse_age_limit(video.get('rating')),
1a83c731 324 'thumbnails': thumbnails,
1a83c731 325 'subtitles': subtitles,
bc2ca1bb 326 'episode_number': episode_number,
382ed50e
PH
327 }
328
a0566bbf 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:
63ad4d43 352 if not self._downloader.params.get('allow_unplayable_formats') and '_drm/index_' in f['url']:
a0566bbf 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)
ac20d95f 407
ac20d95f
S
408 result['formats'] = formats
409 return result
410
0d7f0364 411
bc56355e 412class VikiChannelIE(VikiBaseIE):
8da0e0e9 413 IE_NAME = 'viki:channel'
53de95da 414 _VALID_URL = r'%s(?:tv|news|movies|artists)/(?P<id>[0-9]+c)' % VikiBaseIE._VALID_URL_BASE
0d7f0364 415 _TESTS = [{
416 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
417 'info_dict': {
418 'id': '50c',
419 'title': 'Boys Over Flowers',
bc2ca1bb 420 'description': 'md5:804ce6e7837e1fd527ad2f25420f4d59',
0d7f0364 421 },
c83b35d4 422 'playlist_mincount': 71,
1c18de00 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,
bc2ca1bb 431 'skip': 'Page not found',
d01924f4
S
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,
0d7f0364 441 }]
bc56355e 442
8da0e0e9 443 _PER_PAGE = 25
0d7f0364 444
445 def _real_extract(self, url):
b0d619fd 446 channel_id = self._match_id(url)
0d7f0364 447
bc56355e
S
448 channel = self._call_api(
449 'containers/%s.json' % channel_id, channel_id,
450 'Downloading channel JSON')
b0d619fd 451
dc016bf5 452 self._check_errors(channel)
453
b73b14f7 454 title = self.dict_selection(channel['titles'], 'en')
b0d619fd 455
b73b14f7 456 description = self.dict_selection(channel['descriptions'], 'en')
0d7f0364 457
0d7f0364 458 entries = []
d01924f4 459 for video_type in ('episodes', 'clips', 'movies'):
bc56355e
S
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))
b0d619fd 465 for video in page['response']:
1c18de00 466 video_id = video['id']
467 entries.append(self.url_result(
26a87972 468 'https://www.viki.com/videos/%s' % video_id, 'Viki'))
bc56355e
S
469 if not page['pagination']['next']:
470 break
0d7f0364 471
b0d619fd 472 return self.playlist_result(entries, channel_id, title, description)