2 from __future__
import unicode_literals
12 from .common
import InfoExtractor
13 from ..compat
import (
15 compat_urllib_parse_urlparse
,
27 class VikiBaseIE(InfoExtractor
):
28 _VALID_URL_BASE
= r
'https?://(?:www\.)?viki\.(?:com|net|mx|jp|fr)/'
29 _API_QUERY_TEMPLATE
= '/v4/%sapp=%s&t=%s&site=www.viki.com'
30 _API_URL_TEMPLATE
= 'https://api.viki.io%s&sig=%s'
33 _APP_VERSION
= '2.2.5.1428709186'
34 _APP_SECRET
= 'MM_d*yP@`&1@]@!AVrXf_o-HVEnoTnm$O-ti4[G~$JDI/Dc-&piU&z&5.;:}95=Iad'
37 _NETRC_MACHINE
= 'viki'
42 'geo': 'Sorry, this content is not available in your region.',
43 'upcoming': 'Sorry, this content is not yet available.',
44 # 'paywall': 'paywall',
47 def _prepare_call(self
, path
, timestamp
=None, post_data
=None):
48 path
+= '?' if '?' not in path
else '&'
50 timestamp
= int(time
.time())
51 query
= self
._API
_QUERY
_TEMPLATE
% (path
, self
._APP
, timestamp
)
53 query
+= '&token=%s' % self
._token
55 self
._APP
_SECRET
.encode('ascii'),
56 query
.encode('ascii'),
59 url
= self
._API
_URL
_TEMPLATE
% (query
, sig
)
60 return sanitized_Request(
61 url
, json
.dumps(post_data
).encode('utf-8')) if post_data
else url
63 def _call_api(self
, path
, video_id
, note
, timestamp
=None, post_data
=None):
64 resp
= self
._download
_json
(
65 self
._prepare
_call
(path
, timestamp
, post_data
), video_id
, note
, headers
={'x-viki-app-ver': '2.2.5.1428709186'}
, expected_status
=[200, 400, 404])
67 error
= resp
.get('error')
69 if error
== 'invalid timestamp':
70 resp
= self
._download
_json
(
71 self
._prepare
_call
(path
, int(resp
['current_timestamp']), post_data
),
72 video_id
, '%s (retry)' % note
, headers
={'x-viki-app-ver': '2.2.5.1428709186'}
, expected_status
=[200, 400, 404])
73 error
= resp
.get('error')
75 self
._raise
_error
(resp
['error'])
79 def _raise_error(self
, error
):
81 '%s returned error: %s' % (self
.IE_NAME
, error
),
84 def _check_errors(self
, data
):
85 for reason
, status
in data
.get('blocking', {}).items():
86 if status
and reason
in self
._ERRORS
:
87 message
= self
._ERRORS
[reason
]
89 self
.raise_geo_restricted(msg
=message
)
90 raise ExtractorError('%s said: %s' % (
91 self
.IE_NAME
, message
), expected
=True)
93 def _real_initialize(self
):
97 username
, password
= self
._get
_login
_info
()
102 'login_id': username
,
103 'password': password
,
106 login
= self
._call
_api
(
107 'sessions.json', None,
108 'Logging in', post_data
=login_form
)
110 self
._token
= login
.get('token')
112 self
.report_warning('Unable to get session token, login has probably failed')
115 def dict_selection(dict_obj
, preferred_key
, allow_fallback
=True):
116 if preferred_key
in dict_obj
:
117 return dict_obj
.get(preferred_key
)
119 if not allow_fallback
:
122 filtered_dict
= list(filter(None, [dict_obj
.get(k
) for k
in dict_obj
.keys()]))
123 return filtered_dict
[0] if filtered_dict
else None
126 class VikiIE(VikiBaseIE
):
128 _VALID_URL
= r
'%s(?:videos|player)/(?P<id>[0-9]+v)' % VikiBaseIE
._VALID
_URL
_BASE
130 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
134 'title': 'Heirs Episode 14',
136 'description': 'md5:c4b17b9626dd4b143dcc4d855ba3474e',
137 'upload_date': '20131121',
140 'skip': 'Blocked in the US',
143 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
144 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
148 'title': "'The Avengers: Age of Ultron' Press Conference",
149 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
151 'timestamp': 1430380829,
152 'upload_date': '20150430',
153 'uploader': 'Arirang TV',
158 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
162 'title': 'Ankhon Dekhi',
164 'timestamp': 1408532356,
165 'upload_date': '20140820',
170 'skip': 'Blocked in the US',
173 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
174 'md5': '94e0e34fd58f169f40c184f232356cfe',
178 'title': 'Boys Over Flowers - Episode 1',
179 'description': 'md5:b89cf50038b480b88b5b3c93589a9076',
181 'timestamp': 1270496524,
182 'upload_date': '20100405',
183 'uploader': 'group8',
187 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
190 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
191 'md5': '63f8600c1da6f01b7640eee7eca4f1da',
195 'title': 'Poor Nastya [COMPLETE] - Episode 1',
198 'timestamp': 1274949505,
199 'upload_date': '20101213',
200 'uploader': 'ad14065n',
201 'uploader_id': 'ad14065n',
205 'skip': 'Page not found!',
207 'url': 'http://www.viki.com/player/44699v',
208 'only_matching': True,
210 # non-English description
211 'url': 'http://www.viki.com/videos/158036v-love-in-magic',
212 'md5': 'adf9e321a0ae5d0aace349efaaff7691',
216 'uploader': 'I Planet Entertainment',
217 'upload_date': '20111122',
218 'timestamp': 1321985454,
219 'description': 'md5:44b1e46619df3a072294645c770cef36',
220 'title': 'Love In Magic',
225 def _real_extract(self
, url
):
226 video_id
= self
._match
_id
(url
)
228 resp
= self
._download
_json
(
229 'https://www.viki.com/api/videos/' + video_id
,
230 video_id
, 'Downloading video JSON',
231 headers
={'x-viki-app-ver': '4.0.57'}
)
232 video
= resp
['video']
234 self
._check
_errors
(video
)
236 title
= self
.dict_selection(video
.get('titles', {}), 'en', allow_fallback
=False)
238 title
= 'Episode %d' % video
.get('number') if video
.get('type') == 'episode' else video
.get('id') or video_id
239 container_titles
= video
.get('container', {}).get('titles', {}
)
240 container_title
= self
.dict_selection(container_titles
, 'en')
241 title
= '%s - %s' % (container_title
, title
)
243 description
= self
.dict_selection(video
.get('descriptions', {}), 'en')
245 duration
= int_or_none(video
.get('duration'))
246 timestamp
= parse_iso8601(video
.get('created_at'))
247 uploader
= video
.get('author')
248 like_count
= int_or_none(video
.get('likes', {}).get('count'))
249 age_limit
= parse_age_limit(video
.get('rating'))
252 for thumbnail_id
, thumbnail
in video
.get('images', {}).items():
255 'url': thumbnail
.get('url'),
260 # New way to fetch subtitles
261 new_video
= self
._download
_json
(
262 'https://www.viki.com/api/videos/%s' % video_id
, video_id
,
263 'Downloading new video JSON to get subtitles', headers
={'x-viki-app-ver': '2.2.5.1428709186'}
, expected_status
=[200, 400, 404])
264 for sub
in new_video
.get('streamSubtitles').get('dash'):
265 subtitles
[sub
.get('srclang')] = [{
267 'url': sub
.get('src'),
268 'completion': sub
.get('percentage'),
270 except AttributeError:
271 # fall-back to the old way if there isn't a streamSubtitles attribute
272 for subtitle_lang
, _
in video
.get('subtitle_completions', {}).items():
273 subtitles
[subtitle_lang
] = [{
274 'ext': subtitles_format
,
275 'url': self
._prepare
_call
(
276 'videos/%s/subtitles/%s.%s' % (video_id
, subtitle_lang
, subtitles_format
)),
277 } for subtitles_format
in ('srt', 'vtt')]
282 'description': description
,
283 'duration': duration
,
284 'timestamp': timestamp
,
285 'uploader': uploader
,
286 'like_count': like_count
,
287 'age_limit': age_limit
,
288 'thumbnails': thumbnails
,
289 'subtitles': subtitles
,
294 def add_format(format_id
, format_dict
, protocol
='http'):
295 # rtmps URLs does not seem to work
296 if protocol
== 'rtmps':
298 format_url
= format_dict
.get('url')
301 format_drms
= format_dict
.get('drms')
302 format_stream_id
= format_dict
.get('id')
303 qs
= compat_parse_qs(compat_urllib_parse_urlparse(format_url
).query
)
304 stream
= qs
.get('stream', [None])[0]
306 format_url
= base64
.b64decode(stream
).decode()
307 if format_id
in ('m3u8', 'hls'):
308 m3u8_formats
= self
._extract
_m
3u8_formats
(
309 format_url
, video_id
, 'mp4',
310 entry_protocol
='m3u8_native',
311 m3u8_id
='m3u8-%s' % protocol
, fatal
=False)
312 # Despite CODECS metadata in m3u8 all video-only formats
313 # are actually video+audio
314 for f
in m3u8_formats
:
315 if '_drm/index_' in f
['url']:
317 if f
.get('acodec') == 'none' and f
.get('vcodec') != 'none':
320 elif format_id
in ('mpd', 'dash'):
321 formats
.extend(self
._extract
_mpd
_formats
(
322 format_url
, video_id
, 'mpd-%s' % protocol
, fatal
=False))
323 elif format_url
.startswith('rtmp'):
325 r
'^(?P<url>rtmp://[^/]+/(?P<app>.+?))/(?P<playpath>mp4:.+)$',
330 'format_id': 'rtmp-%s' % format_id
,
332 'url': mobj
.group('url'),
333 'play_path': mobj
.group('playpath'),
334 'app': mobj
.group('app'),
337 'stream_id': format_stream_id
,
340 urlh
= self
._request
_webpage
(
341 HEADRequest(format_url
), video_id
, 'Checking file size', fatal
=False)
344 'format_id': '%s-%s' % (format_id
, protocol
),
345 'height': int_or_none(self
._search
_regex
(
346 r
'^(\d+)[pP]$', format_id
, 'height', default
=None)),
348 'stream_id': format_stream_id
,
349 'filesize': int_or_none(urlh
.headers
.get('Content-Length')),
352 for format_id
, format_dict
in (resp
.get('streams') or {}).items():
353 add_format(format_id
, format_dict
)
355 streams
= self
._call
_api
(
356 'videos/%s/streams.json' % video_id
, video_id
,
357 'Downloading video streams JSON')
359 if 'external' in streams
:
361 '_type': 'url_transparent',
362 'url': streams
['external']['url'],
366 for format_id
, stream_dict
in streams
.items():
367 for protocol
, format_dict
in stream_dict
.items():
368 add_format(format_id
, format_dict
, protocol
)
369 self
._sort
_formats
(formats
)
371 result
['formats'] = formats
375 class VikiChannelIE(VikiBaseIE
):
376 IE_NAME
= 'viki:channel'
377 _VALID_URL
= r
'%s(?:tv|news|movies|artists)/(?P<id>[0-9]+c)' % VikiBaseIE
._VALID
_URL
_BASE
379 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
382 'title': 'Boys Over Flowers',
383 'description': 'md5:ecd3cff47967fe193cff37c0bec52790',
385 'playlist_mincount': 71,
387 'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
390 'title': 'Poor Nastya [COMPLETE]',
391 'description': 'md5:05bf5471385aa8b21c18ad450e350525',
393 'playlist_count': 127,
395 'url': 'http://www.viki.com/news/24569c-showbiz-korea',
396 'only_matching': True,
398 'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
399 'only_matching': True,
401 'url': 'http://www.viki.com/artists/2141c-shinee',
402 'only_matching': True,
407 def _real_extract(self
, url
):
408 channel_id
= self
._match
_id
(url
)
410 channel
= self
._call
_api
(
411 'containers/%s.json' % channel_id
, channel_id
,
412 'Downloading channel JSON')
414 self
._check
_errors
(channel
)
416 title
= self
.dict_selection(channel
['titles'], 'en')
418 description
= self
.dict_selection(channel
['descriptions'], 'en')
421 for video_type
in ('episodes', 'clips', 'movies'):
422 for page_num
in itertools
.count(1):
423 page
= self
._call
_api
(
424 'containers/%s/%s.json?per_page=%d&sort=number&direction=asc&with_paging=true&page=%d'
425 % (channel_id
, video_type
, self
._PER
_PAGE
, page_num
), channel_id
,
426 'Downloading %s JSON page #%d' % (video_type
, page_num
))
427 for video
in page
['response']:
428 video_id
= video
['id']
429 entries
.append(self
.url_result(
430 'https://www.viki.com/videos/%s' % video_id
, 'Viki'))
431 if not page
['pagination']['next']:
434 return self
.playlist_result(entries
, channel_id
, title
, description
)