2 from __future__
import unicode_literals
11 from .common
import InfoExtractor
22 class VikiBaseIE(InfoExtractor
):
23 _VALID_URL_BASE
= r
'https?://(?:www\.)?viki\.(?:com|net|mx|jp|fr)/'
24 _API_QUERY_TEMPLATE
= '/v4/%sapp=%s&t=%s&site=www.viki.com'
25 _API_URL_TEMPLATE
= 'https://api.viki.io%s&sig=%s'
28 _APP_VERSION
= '2.2.5.1428709186'
29 _APP_SECRET
= 'MM_d*yP@`&1@]@!AVrXf_o-HVEnoTnm$O-ti4[G~$JDI/Dc-&piU&z&5.;:}95=Iad'
32 _NETRC_MACHINE
= 'viki'
37 'geo': 'Sorry, this content is not available in your region.',
38 'upcoming': 'Sorry, this content is not yet available.',
39 # 'paywall': 'paywall',
42 def _prepare_call(self
, path
, timestamp
=None, post_data
=None):
43 path
+= '?' if '?' not in path
else '&'
45 timestamp
= int(time
.time())
46 query
= self
._API
_QUERY
_TEMPLATE
% (path
, self
._APP
, timestamp
)
48 query
+= '&token=%s' % self
._token
50 self
._APP
_SECRET
.encode('ascii'),
51 query
.encode('ascii'),
54 url
= self
._API
_URL
_TEMPLATE
% (query
, sig
)
55 return sanitized_Request(
56 url
, json
.dumps(post_data
).encode('utf-8')) if post_data
else url
58 def _call_api(self
, path
, video_id
, note
, timestamp
=None, post_data
=None):
59 resp
= self
._download
_json
(
60 self
._prepare
_call
(path
, timestamp
, post_data
), video_id
, note
, headers
={'x-viki-app-ver': '2.2.5.1428709186'}
, expected_status
=[200, 400, 404])
62 error
= resp
.get('error')
64 if error
== 'invalid timestamp':
65 resp
= self
._download
_json
(
66 self
._prepare
_call
(path
, int(resp
['current_timestamp']), post_data
),
67 video_id
, '%s (retry)' % note
, headers
={'x-viki-app-ver': '2.2.5.1428709186'}
, expected_status
=[200, 400, 404])
68 error
= resp
.get('error')
70 self
._raise
_error
(resp
['error'])
74 def _raise_error(self
, error
):
76 '%s returned error: %s' % (self
.IE_NAME
, error
),
79 def _check_errors(self
, data
):
80 for reason
, status
in data
.get('blocking', {}).items():
81 if status
and reason
in self
._ERRORS
:
82 message
= self
._ERRORS
[reason
]
84 self
.raise_geo_restricted(msg
=message
)
85 raise ExtractorError('%s said: %s' % (
86 self
.IE_NAME
, message
), expected
=True)
88 def _real_initialize(self
):
92 username
, password
= self
._get
_login
_info
()
101 login
= self
._call
_api
(
102 'sessions.json', None,
103 'Logging in', post_data
=login_form
)
105 self
._token
= login
.get('token')
107 self
.report_warning('Unable to get session token, login has probably failed')
110 def dict_selection(dict_obj
, preferred_key
, allow_fallback
=True):
111 if preferred_key
in dict_obj
:
112 return dict_obj
.get(preferred_key
)
114 if not allow_fallback
:
117 filtered_dict
= list(filter(None, [dict_obj
.get(k
) for k
in dict_obj
.keys()]))
118 return filtered_dict
[0] if filtered_dict
else None
121 class VikiIE(VikiBaseIE
):
123 _VALID_URL
= r
'%s(?:videos|player)/(?P<id>[0-9]+v)' % VikiBaseIE
._VALID
_URL
_BASE
125 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
129 'title': 'Heirs Episode 14',
131 'description': 'md5:c4b17b9626dd4b143dcc4d855ba3474e',
132 'upload_date': '20131121',
135 'skip': 'Blocked in the US',
138 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
139 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
143 'title': "'The Avengers: Age of Ultron' Press Conference",
144 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
146 'timestamp': 1430380829,
147 'upload_date': '20150430',
148 'uploader': 'Arirang TV',
153 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
157 'title': 'Ankhon Dekhi',
159 'timestamp': 1408532356,
160 'upload_date': '20140820',
165 'skip': 'Blocked in the US',
168 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
169 'md5': '5fa476a902e902783ac7a4d615cdbc7a',
173 'title': 'Boys Over Flowers - Episode 1',
174 'description': 'md5:b89cf50038b480b88b5b3c93589a9076',
176 'timestamp': 1270496524,
177 'upload_date': '20100405',
178 'uploader': 'group8',
184 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
185 'md5': '63f8600c1da6f01b7640eee7eca4f1da',
189 'title': 'Poor Nastya [COMPLETE] - Episode 1',
192 'timestamp': 1274949505,
193 'upload_date': '20101213',
194 'uploader': 'ad14065n',
195 'uploader_id': 'ad14065n',
200 'url': 'http://www.viki.com/player/44699v',
201 'only_matching': True,
203 # non-English description
204 'url': 'http://www.viki.com/videos/158036v-love-in-magic',
205 'md5': '1713ae35df5a521b31f6dc40730e7c9c',
209 'uploader': 'I Planet Entertainment',
210 'upload_date': '20111122',
211 'timestamp': 1321985454,
212 'description': 'md5:44b1e46619df3a072294645c770cef36',
213 'title': 'Love In Magic',
218 def _real_extract(self
, url
):
219 video_id
= self
._match
_id
(url
)
221 video
= self
._call
_api
(
222 'videos/%s.json' % video_id
, video_id
, 'Downloading video JSON')
224 streams
= self
._call
_api
(
225 'videos/%s/streams.json' % video_id
, video_id
,
226 'Downloading video streams JSON')
229 for format_id
, stream_dict
in streams
.items():
230 height
= int_or_none(self
._search
_regex
(
231 r
'^(\d+)[pP]$', format_id
, 'height', default
=None))
232 for protocol
, format_dict
in stream_dict
.items():
233 # rtmps URLs does not seem to work
234 if protocol
== 'rtmps':
236 format_url
= format_dict
.get('url')
237 format_drms
= format_dict
.get('drms')
238 format_stream_id
= format_dict
.get('id')
239 if format_id
== 'm3u8':
240 m3u8_formats
= self
._extract
_m
3u8_formats
(
241 format_url
, video_id
, 'mp4',
242 entry_protocol
='m3u8_native',
243 m3u8_id
='m3u8-%s' % protocol
, fatal
=False)
244 # Despite CODECS metadata in m3u8 all video-only formats
245 # are actually video+audio
246 for f
in m3u8_formats
:
247 if f
.get('acodec') == 'none' and f
.get('vcodec') != 'none':
249 formats
.extend(m3u8_formats
)
250 elif format_id
== 'mpd':
251 mpd_formats
= self
._extract
_mpd
_formats
(
252 format_url
, video_id
,
253 mpd_id
='mpd-%s' % protocol
, fatal
=False)
254 formats
.extend(mpd_formats
)
255 elif format_id
== 'mpd':
257 formats
.extend(mpd_formats
)
258 elif format_url
.startswith('rtmp'):
260 r
'^(?P<url>rtmp://[^/]+/(?P<app>.+?))/(?P<playpath>mp4:.+)$',
265 'format_id': 'rtmp-%s' % format_id
,
267 'url': mobj
.group('url'),
268 'play_path': mobj
.group('playpath'),
269 'app': mobj
.group('app'),
272 'stream_id': format_stream_id
,
275 urlh
= self
._request
_webpage
(
276 HEADRequest(format_url
), video_id
, 'Checking file size', fatal
=False)
279 'format_id': '%s-%s' % (format_id
, protocol
),
282 'stream_id': format_stream_id
,
283 'filesize': int_or_none(urlh
.headers
.get('Content-Length')),
285 self
._sort
_formats
(formats
)
287 self
._check
_errors
(video
)
289 title
= self
.dict_selection(video
.get('titles', {}), 'en', allow_fallback
=False)
291 title
= 'Episode %d' % video
.get('number') if video
.get('type') == 'episode' else video
.get('id') or video_id
292 container_titles
= video
.get('container', {}).get('titles', {}
)
293 container_title
= self
.dict_selection(container_titles
, 'en')
294 title
= '%s - %s' % (container_title
, title
)
296 description
= self
.dict_selection(video
.get('descriptions', {}), 'en')
298 duration
= int_or_none(video
.get('duration'))
299 timestamp
= parse_iso8601(video
.get('created_at'))
300 uploader
= video
.get('author')
301 like_count
= int_or_none(video
.get('likes', {}).get('count'))
302 age_limit
= parse_age_limit(video
.get('rating'))
305 for thumbnail_id
, thumbnail
in video
.get('images', {}).items():
308 'url': thumbnail
.get('url'),
311 new_video
= self
._download
_json
(
312 'https://www.viki.com/api/videos/%s' % video_id
, video_id
,
313 'Downloading new video JSON to get subtitles', headers
={'x-viki-app-ver': '2.2.5.1428709186'}
, expected_status
=[200, 400, 404])
316 for sub
in new_video
.get('streamSubtitles').get('dash'):
317 subtitles
[sub
.get('srclang')] = [{
319 'url': sub
.get('src'),
320 'completion': sub
.get('percentage'),
326 'description': description
,
327 'duration': duration
,
328 'timestamp': timestamp
,
329 'uploader': uploader
,
330 'like_count': like_count
,
331 'age_limit': age_limit
,
332 'thumbnails': thumbnails
,
333 'subtitles': subtitles
,
336 if 'external' in streams
:
338 '_type': 'url_transparent',
339 'url': streams
['external']['url'],
343 result
['formats'] = formats
347 class VikiChannelIE(VikiBaseIE
):
348 IE_NAME
= 'viki:channel'
349 _VALID_URL
= r
'%s(?:tv|news|movies|artists)/(?P<id>[0-9]+c)' % VikiBaseIE
._VALID
_URL
_BASE
351 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
354 'title': 'Boys Over Flowers',
355 'description': 'md5:ecd3cff47967fe193cff37c0bec52790',
357 'playlist_mincount': 71,
359 'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
362 'title': 'Poor Nastya [COMPLETE]',
363 'description': 'md5:05bf5471385aa8b21c18ad450e350525',
365 'playlist_count': 127,
367 'url': 'http://www.viki.com/news/24569c-showbiz-korea',
368 'only_matching': True,
370 'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
371 'only_matching': True,
373 'url': 'http://www.viki.com/artists/2141c-shinee',
374 'only_matching': True,
379 def _real_extract(self
, url
):
380 channel_id
= self
._match
_id
(url
)
382 channel
= self
._call
_api
(
383 'containers/%s.json' % channel_id
, channel_id
,
384 'Downloading channel JSON')
386 self
._check
_errors
(channel
)
388 title
= self
.dict_selection(channel
['titles'], 'en')
390 description
= self
.dict_selection(channel
['descriptions'], 'en')
393 for video_type
in ('episodes', 'clips', 'movies'):
394 for page_num
in itertools
.count(1):
395 page
= self
._call
_api
(
396 'containers/%s/%s.json?per_page=%d&sort=number&direction=asc&with_paging=true&page=%d'
397 % (channel_id
, video_type
, self
._PER
_PAGE
, page_num
), channel_id
,
398 'Downloading %s JSON page #%d' % (video_type
, page_num
))
399 for video
in page
['response']:
400 video_id
= video
['id']
401 entries
.append(self
.url_result(
402 'https://www.viki.com/videos/%s' % video_id
, 'Viki'))
403 if not page
['pagination']['next']:
406 return self
.playlist_result(entries
, channel_id
, title
, description
)