2 from __future__
import unicode_literals
12 from .common
import InfoExtractor
13 from ..compat
import (
15 compat_urllib_parse_urlparse
,
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'
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'
39 _NETRC_MACHINE
= 'viki'
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',
49 def _prepare_call(self
, path
, timestamp
=None, post_data
=None):
50 path
+= '?' if '?' not in path
else '&'
52 timestamp
= int(time
.time())
53 query
= self
._API
_QUERY
_TEMPLATE
% (path
, self
._APP
, timestamp
)
55 query
+= '&token=%s' % self
._token
57 self
._APP
_SECRET
.encode('ascii'),
58 query
.encode('ascii'),
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
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
),
70 'x-client-user-agent': std_headers
['User-Agent'],
71 'x-viki-as-id': self
._APP
,
72 'x-viki-app-ver': self
._APP
_VERSION
,
75 error
= resp
.get('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
,
82 'x-client-user-agent': std_headers
['User-Agent'],
83 'x-viki-as-id': self
._APP
,
84 'x-viki-app-ver': self
._APP
_VERSION
,
86 error
= resp
.get('error')
88 self
._raise
_error
(resp
['error'])
92 def _raise_error(self
, error
):
94 '%s returned error: %s' % (self
.IE_NAME
, error
),
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
]
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)
108 def _real_initialize(self
):
112 username
, password
= self
._get
_login
_info
()
117 'login_id': username
,
118 'password': password
,
121 login
= self
._call
_api
(
122 'sessions.json', None,
123 'Logging in', post_data
=login_form
)
125 self
._token
= login
.get('token')
127 self
.report_warning('Unable to get session token, login has probably failed')
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
)
134 if not allow_fallback
:
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
141 class VikiIE(VikiBaseIE
):
143 _VALID_URL
= r
'%s(?:videos|player)/(?P<id>[0-9]+v)' % VikiBaseIE
._VALID
_URL
_BASE
145 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
149 'title': 'Heirs - Episode 14',
150 'uploader': 'SBS Contents Hub',
151 'timestamp': 1385047627,
152 'upload_date': '20131121',
155 'episode_number': 14,
158 'format': 'bestvideo',
160 'skip': 'Blocked in the US',
161 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
164 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
165 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
169 'title': "'The Avengers: Age of Ultron' Press Conference",
170 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
172 'timestamp': 1430380829,
173 'upload_date': '20150430',
174 'uploader': 'Arirang TV',
178 'skip': 'Sorry. There was an error loading this video',
180 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
184 'title': 'Ankhon Dekhi',
186 'timestamp': 1408532356,
187 'upload_date': '20140820',
192 'skip': 'Blocked in the US',
195 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
196 'md5': '0a53dc252e6e690feccd756861495a8c',
200 'title': 'Boys Over Flowers - Episode 1',
201 'description': 'md5:b89cf50038b480b88b5b3c93589a9076',
203 'timestamp': 1270496524,
204 'upload_date': '20100405',
205 'uploader': 'group8',
211 'format': 'bestvideo',
213 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
216 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
217 'md5': '63f8600c1da6f01b7640eee7eca4f1da',
221 'title': 'Poor Nastya [COMPLETE] - Episode 1',
224 'timestamp': 1274949505,
225 'upload_date': '20101213',
226 'uploader': 'ad14065n',
227 'uploader_id': 'ad14065n',
231 'skip': 'Page not found!',
233 'url': 'http://www.viki.com/player/44699v',
234 'only_matching': True,
236 # non-English description
237 'url': 'http://www.viki.com/videos/158036v-love-in-magic',
238 'md5': '41faaba0de90483fb4848952af7c7d0d',
242 'uploader': 'I Planet Entertainment',
243 'upload_date': '20111122',
244 'timestamp': 1321985454,
245 'description': 'md5:44b1e46619df3a072294645c770cef36',
246 'title': 'Love In Magic',
250 'format': 'bestvideo',
252 'expected_warnings': ['Unknown MIME type image/jpeg in DASH manifest'],
255 def _real_extract(self
, url
):
256 video_id
= self
._match
_id
(url
)
258 video
= self
._call
_api
(
259 'videos/%s.json' % video_id
, video_id
, 'Downloading video JSON')
260 self
._check
_errors
(video
)
262 title
= self
.dict_selection(video
.get('titles', {}), 'en', allow_fallback
=False)
263 episode_number
= int_or_none(video
.get('number'))
265 title
= 'Episode %d' % episode_number
if video
.get('type') == 'episode' else video
.get('id') or video_id
266 container_titles
= try_get(video
, lambda x
: x
['container']['titles'], dict) or {}
267 container_title
= self
.dict_selection(container_titles
, 'en')
268 title
= '%s - %s' % (container_title
, title
)
270 description
= self
.dict_selection(video
.get('descriptions', {}), 'en')
272 like_count
= int_or_none(try_get(video
, lambda x
: x
['likes']['count']))
275 for thumbnail_id
, thumbnail
in (video
.get('images') or {}).items():
278 'url': thumbnail
.get('url'),
282 for subtitle_lang
, _
in (video
.get('subtitle_completions') or {}).items():
283 subtitles
[subtitle_lang
] = [{
284 'ext': subtitles_format
,
285 'url': self
._prepare
_call
(
286 'videos/%s/subtitles/%s.%s' % (video_id
, subtitle_lang
, subtitles_format
)),
287 } for subtitles_format
in ('srt', 'vtt')]
292 'description': description
,
293 'duration': int_or_none(video
.get('duration')),
294 'timestamp': parse_iso8601(video
.get('created_at')),
295 'uploader': video
.get('author'),
296 'uploader_url': video
.get('author_url'),
297 'like_count': like_count
,
298 'age_limit': parse_age_limit(video
.get('rating')),
299 'thumbnails': thumbnails
,
300 'subtitles': subtitles
,
301 'episode_number': episode_number
,
306 def add_format(format_id
, format_dict
, protocol
='http'):
307 # rtmps URLs does not seem to work
308 if protocol
== 'rtmps':
310 format_url
= format_dict
.get('url')
313 format_drms
= format_dict
.get('drms')
314 format_stream_id
= format_dict
.get('id')
315 qs
= compat_parse_qs(compat_urllib_parse_urlparse(format_url
).query
)
316 stream
= qs
.get('stream', [None])[0]
318 format_url
= base64
.b64decode(stream
).decode()
319 if format_id
in ('m3u8', 'hls'):
320 m3u8_formats
= self
._extract
_m
3u8_formats
(
321 format_url
, video_id
, 'mp4',
322 entry_protocol
='m3u8_native',
323 m3u8_id
='m3u8-%s' % protocol
, fatal
=False)
324 # Despite CODECS metadata in m3u8 all video-only formats
325 # are actually video+audio
326 for f
in m3u8_formats
:
327 if not self
._downloader
.params
.get('allow_unplayable_formats') and '_drm/index_' in f
['url']:
329 if f
.get('acodec') == 'none' and f
.get('vcodec') != 'none':
332 elif format_id
in ('mpd', 'dash'):
333 formats
.extend(self
._extract
_mpd
_formats
(
334 format_url
, video_id
, 'mpd-%s' % protocol
, fatal
=False))
335 elif format_url
.startswith('rtmp'):
337 r
'^(?P<url>rtmp://[^/]+/(?P<app>.+?))/(?P<playpath>mp4:.+)$',
342 'format_id': 'rtmp-%s' % format_id
,
344 'url': mobj
.group('url'),
345 'play_path': mobj
.group('playpath'),
346 'app': mobj
.group('app'),
349 'stream_id': format_stream_id
,
352 urlh
= self
._request
_webpage
(
353 HEADRequest(format_url
), video_id
, 'Checking file size', fatal
=False)
356 'format_id': '%s-%s' % (format_id
, protocol
),
357 'height': int_or_none(self
._search
_regex
(
358 r
'^(\d+)[pP]$', format_id
, 'height', default
=None)),
360 'stream_id': format_stream_id
,
361 'filesize': int_or_none(urlh
.headers
.get('Content-Length')),
364 streams
= self
._call
_api
(
365 'videos/%s/streams.json' % video_id
, video_id
,
366 'Downloading video streams JSON')
368 if 'external' in streams
:
370 '_type': 'url_transparent',
371 'url': streams
['external']['url'],
375 for format_id
, stream_dict
in streams
.items():
376 for protocol
, format_dict
in stream_dict
.items():
377 add_format(format_id
, format_dict
, protocol
)
378 self
._sort
_formats
(formats
)
380 result
['formats'] = formats
384 class VikiChannelIE(VikiBaseIE
):
385 IE_NAME
= 'viki:channel'
386 _VALID_URL
= r
'%s(?:tv|news|movies|artists)/(?P<id>[0-9]+c)' % VikiBaseIE
._VALID
_URL
_BASE
388 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
391 'title': 'Boys Over Flowers',
392 'description': 'md5:804ce6e7837e1fd527ad2f25420f4d59',
394 'playlist_mincount': 71,
396 'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
399 'title': 'Poor Nastya [COMPLETE]',
400 'description': 'md5:05bf5471385aa8b21c18ad450e350525',
402 'playlist_count': 127,
403 'skip': 'Page not found',
405 'url': 'http://www.viki.com/news/24569c-showbiz-korea',
406 'only_matching': True,
408 'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
409 'only_matching': True,
411 'url': 'http://www.viki.com/artists/2141c-shinee',
412 'only_matching': True,
417 def _real_extract(self
, url
):
418 channel_id
= self
._match
_id
(url
)
420 channel
= self
._call
_api
(
421 'containers/%s.json' % channel_id
, channel_id
,
422 'Downloading channel JSON')
424 self
._check
_errors
(channel
)
426 title
= self
.dict_selection(channel
['titles'], 'en')
428 description
= self
.dict_selection(channel
['descriptions'], 'en')
431 for video_type
in ('episodes', 'clips', 'movies'):
432 for page_num
in itertools
.count(1):
433 page
= self
._call
_api
(
434 'containers/%s/%s.json?per_page=%d&sort=number&direction=asc&with_paging=true&page=%d'
435 % (channel_id
, video_type
, self
._PER
_PAGE
, page_num
), channel_id
,
436 'Downloading %s JSON page #%d' % (video_type
, page_num
))
437 for video
in page
['response']:
438 video_id
= video
['id']
439 entries
.append(self
.url_result(
440 'https://www.viki.com/videos/%s' % video_id
, 'Viki'))
441 if not page
['pagination']['next']:
444 return self
.playlist_result(entries
, channel_id
, title
, description
)