]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/viki.py
debian/control: Update list of extractors in long description.
[youtubedl] / youtube_dl / extractor / viki.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import hashlib
5 import hmac
6 import itertools
7 import json
8 import re
9 import time
10
11 from .common import InfoExtractor
12 from ..utils import (
13 ExtractorError,
14 int_or_none,
15 parse_age_limit,
16 parse_iso8601,
17 sanitized_Request,
18 )
19
20
21 class VikiBaseIE(InfoExtractor):
22 _VALID_URL_BASE = r'https?://(?:www\.)?viki\.(?:com|net|mx|jp|fr)/'
23 _API_QUERY_TEMPLATE = '/v4/%sapp=%s&t=%s&site=www.viki.com'
24 _API_URL_TEMPLATE = 'http://api.viki.io%s&sig=%s'
25
26 _APP = '100005a'
27 _APP_VERSION = '2.2.5.1428709186'
28 _APP_SECRET = 'MM_d*yP@`&1@]@!AVrXf_o-HVEnoTnm$O-ti4[G~$JDI/Dc-&piU&z&5.;:}95=Iad'
29
30 _GEO_BYPASS = False
31 _NETRC_MACHINE = 'viki'
32
33 _token = None
34
35 _ERRORS = {
36 'geo': 'Sorry, this content is not available in your region.',
37 'upcoming': 'Sorry, this content is not yet available.',
38 # 'paywall': 'paywall',
39 }
40
41 def _prepare_call(self, path, timestamp=None, post_data=None):
42 path += '?' if '?' not in path else '&'
43 if not timestamp:
44 timestamp = int(time.time())
45 query = self._API_QUERY_TEMPLATE % (path, self._APP, timestamp)
46 if self._token:
47 query += '&token=%s' % self._token
48 sig = hmac.new(
49 self._APP_SECRET.encode('ascii'),
50 query.encode('ascii'),
51 hashlib.sha1
52 ).hexdigest()
53 url = self._API_URL_TEMPLATE % (query, sig)
54 return sanitized_Request(
55 url, json.dumps(post_data).encode('utf-8')) if post_data else url
56
57 def _call_api(self, path, video_id, note, timestamp=None, post_data=None):
58 resp = self._download_json(
59 self._prepare_call(path, timestamp, post_data), video_id, note)
60
61 error = resp.get('error')
62 if error:
63 if error == 'invalid timestamp':
64 resp = self._download_json(
65 self._prepare_call(path, int(resp['current_timestamp']), post_data),
66 video_id, '%s (retry)' % note)
67 error = resp.get('error')
68 if error:
69 self._raise_error(resp['error'])
70
71 return resp
72
73 def _raise_error(self, error):
74 raise ExtractorError(
75 '%s returned error: %s' % (self.IE_NAME, error),
76 expected=True)
77
78 def _check_errors(self, data):
79 for reason, status in data.get('blocking', {}).items():
80 if status and reason in self._ERRORS:
81 message = self._ERRORS[reason]
82 if reason == 'geo':
83 self.raise_geo_restricted(msg=message)
84 raise ExtractorError('%s said: %s' % (
85 self.IE_NAME, message), expected=True)
86
87 def _real_initialize(self):
88 self._login()
89
90 def _login(self):
91 username, password = self._get_login_info()
92 if username is None:
93 return
94
95 login_form = {
96 'login_id': username,
97 'password': password,
98 }
99
100 login = self._call_api(
101 'sessions.json', None,
102 'Logging in', post_data=login_form)
103
104 self._token = login.get('token')
105 if not self._token:
106 self.report_warning('Unable to get session token, login has probably failed')
107
108 @staticmethod
109 def dict_selection(dict_obj, preferred_key, allow_fallback=True):
110 if preferred_key in dict_obj:
111 return dict_obj.get(preferred_key)
112
113 if not allow_fallback:
114 return
115
116 filtered_dict = list(filter(None, [dict_obj.get(k) for k in dict_obj.keys()]))
117 return filtered_dict[0] if filtered_dict else None
118
119
120 class VikiIE(VikiBaseIE):
121 IE_NAME = 'viki'
122 _VALID_URL = r'%s(?:videos|player)/(?P<id>[0-9]+v)' % VikiBaseIE._VALID_URL_BASE
123 _TESTS = [{
124 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
125 'info_dict': {
126 'id': '1023585v',
127 'ext': 'mp4',
128 'title': 'Heirs Episode 14',
129 'uploader': 'SBS',
130 'description': 'md5:c4b17b9626dd4b143dcc4d855ba3474e',
131 'upload_date': '20131121',
132 'age_limit': 13,
133 },
134 'skip': 'Blocked in the US',
135 }, {
136 # clip
137 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
138 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
139 'info_dict': {
140 'id': '1067139v',
141 'ext': 'mp4',
142 'title': "'The Avengers: Age of Ultron' Press Conference",
143 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
144 'duration': 352,
145 'timestamp': 1430380829,
146 'upload_date': '20150430',
147 'uploader': 'Arirang TV',
148 'like_count': int,
149 'age_limit': 0,
150 }
151 }, {
152 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
153 'info_dict': {
154 'id': '1048879v',
155 'ext': 'mp4',
156 'title': 'Ankhon Dekhi',
157 'duration': 6512,
158 'timestamp': 1408532356,
159 'upload_date': '20140820',
160 'uploader': 'Spuul',
161 'like_count': int,
162 'age_limit': 13,
163 },
164 'skip': 'Blocked in the US',
165 }, {
166 # episode
167 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
168 'md5': '5fa476a902e902783ac7a4d615cdbc7a',
169 'info_dict': {
170 'id': '44699v',
171 'ext': 'mp4',
172 'title': 'Boys Over Flowers - Episode 1',
173 'description': 'md5:b89cf50038b480b88b5b3c93589a9076',
174 'duration': 4204,
175 'timestamp': 1270496524,
176 'upload_date': '20100405',
177 'uploader': 'group8',
178 'like_count': int,
179 'age_limit': 13,
180 }
181 }, {
182 # youtube external
183 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
184 'md5': '63f8600c1da6f01b7640eee7eca4f1da',
185 'info_dict': {
186 'id': '50562v',
187 'ext': 'webm',
188 'title': 'Poor Nastya [COMPLETE] - Episode 1',
189 'description': '',
190 'duration': 606,
191 'timestamp': 1274949505,
192 'upload_date': '20101213',
193 'uploader': 'ad14065n',
194 'uploader_id': 'ad14065n',
195 'like_count': int,
196 'age_limit': 13,
197 }
198 }, {
199 'url': 'http://www.viki.com/player/44699v',
200 'only_matching': True,
201 }, {
202 # non-English description
203 'url': 'http://www.viki.com/videos/158036v-love-in-magic',
204 'md5': '1713ae35df5a521b31f6dc40730e7c9c',
205 'info_dict': {
206 'id': '158036v',
207 'ext': 'mp4',
208 'uploader': 'I Planet Entertainment',
209 'upload_date': '20111122',
210 'timestamp': 1321985454,
211 'description': 'md5:44b1e46619df3a072294645c770cef36',
212 'title': 'Love In Magic',
213 'age_limit': 13,
214 },
215 }]
216
217 def _real_extract(self, url):
218 video_id = self._match_id(url)
219
220 video = self._call_api(
221 'videos/%s.json' % video_id, video_id, 'Downloading video JSON')
222
223 self._check_errors(video)
224
225 title = self.dict_selection(video.get('titles', {}), 'en', allow_fallback=False)
226 if not title:
227 title = 'Episode %d' % video.get('number') if video.get('type') == 'episode' else video.get('id') or video_id
228 container_titles = video.get('container', {}).get('titles', {})
229 container_title = self.dict_selection(container_titles, 'en')
230 title = '%s - %s' % (container_title, title)
231
232 description = self.dict_selection(video.get('descriptions', {}), 'en')
233
234 duration = int_or_none(video.get('duration'))
235 timestamp = parse_iso8601(video.get('created_at'))
236 uploader = video.get('author')
237 like_count = int_or_none(video.get('likes', {}).get('count'))
238 age_limit = parse_age_limit(video.get('rating'))
239
240 thumbnails = []
241 for thumbnail_id, thumbnail in video.get('images', {}).items():
242 thumbnails.append({
243 'id': thumbnail_id,
244 'url': thumbnail.get('url'),
245 })
246
247 subtitles = {}
248 for subtitle_lang, _ in video.get('subtitle_completions', {}).items():
249 subtitles[subtitle_lang] = [{
250 'ext': subtitles_format,
251 'url': self._prepare_call(
252 'videos/%s/subtitles/%s.%s' % (video_id, subtitle_lang, subtitles_format)),
253 } for subtitles_format in ('srt', 'vtt')]
254
255 result = {
256 'id': video_id,
257 'title': title,
258 'description': description,
259 'duration': duration,
260 'timestamp': timestamp,
261 'uploader': uploader,
262 'like_count': like_count,
263 'age_limit': age_limit,
264 'thumbnails': thumbnails,
265 'subtitles': subtitles,
266 }
267
268 streams = self._call_api(
269 'videos/%s/streams.json' % video_id, video_id,
270 'Downloading video streams JSON')
271
272 if 'external' in streams:
273 result.update({
274 '_type': 'url_transparent',
275 'url': streams['external']['url'],
276 })
277 return result
278
279 formats = []
280 for format_id, stream_dict in streams.items():
281 height = int_or_none(self._search_regex(
282 r'^(\d+)[pP]$', format_id, 'height', default=None))
283 for protocol, format_dict in stream_dict.items():
284 # rtmps URLs does not seem to work
285 if protocol == 'rtmps':
286 continue
287 format_url = format_dict['url']
288 if format_id == 'm3u8':
289 m3u8_formats = self._extract_m3u8_formats(
290 format_url, video_id, 'mp4',
291 entry_protocol='m3u8_native',
292 m3u8_id='m3u8-%s' % protocol, fatal=False)
293 # Despite CODECS metadata in m3u8 all video-only formats
294 # are actually video+audio
295 for f in m3u8_formats:
296 if f.get('acodec') == 'none' and f.get('vcodec') != 'none':
297 f['acodec'] = None
298 formats.extend(m3u8_formats)
299 elif format_url.startswith('rtmp'):
300 mobj = re.search(
301 r'^(?P<url>rtmp://[^/]+/(?P<app>.+?))/(?P<playpath>mp4:.+)$',
302 format_url)
303 if not mobj:
304 continue
305 formats.append({
306 'format_id': 'rtmp-%s' % format_id,
307 'ext': 'flv',
308 'url': mobj.group('url'),
309 'play_path': mobj.group('playpath'),
310 'app': mobj.group('app'),
311 'page_url': url,
312 })
313 else:
314 formats.append({
315 'url': format_url,
316 'format_id': '%s-%s' % (format_id, protocol),
317 'height': height,
318 })
319 self._sort_formats(formats)
320
321 result['formats'] = formats
322 return result
323
324
325 class VikiChannelIE(VikiBaseIE):
326 IE_NAME = 'viki:channel'
327 _VALID_URL = r'%s(?:tv|news|movies|artists)/(?P<id>[0-9]+c)' % VikiBaseIE._VALID_URL_BASE
328 _TESTS = [{
329 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
330 'info_dict': {
331 'id': '50c',
332 'title': 'Boys Over Flowers',
333 'description': 'md5:ecd3cff47967fe193cff37c0bec52790',
334 },
335 'playlist_mincount': 71,
336 }, {
337 'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
338 'info_dict': {
339 'id': '1354c',
340 'title': 'Poor Nastya [COMPLETE]',
341 'description': 'md5:05bf5471385aa8b21c18ad450e350525',
342 },
343 'playlist_count': 127,
344 }, {
345 'url': 'http://www.viki.com/news/24569c-showbiz-korea',
346 'only_matching': True,
347 }, {
348 'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
349 'only_matching': True,
350 }, {
351 'url': 'http://www.viki.com/artists/2141c-shinee',
352 'only_matching': True,
353 }]
354
355 _PER_PAGE = 25
356
357 def _real_extract(self, url):
358 channel_id = self._match_id(url)
359
360 channel = self._call_api(
361 'containers/%s.json' % channel_id, channel_id,
362 'Downloading channel JSON')
363
364 self._check_errors(channel)
365
366 title = self.dict_selection(channel['titles'], 'en')
367
368 description = self.dict_selection(channel['descriptions'], 'en')
369
370 entries = []
371 for video_type in ('episodes', 'clips', 'movies'):
372 for page_num in itertools.count(1):
373 page = self._call_api(
374 'containers/%s/%s.json?per_page=%d&sort=number&direction=asc&with_paging=true&page=%d'
375 % (channel_id, video_type, self._PER_PAGE, page_num), channel_id,
376 'Downloading %s JSON page #%d' % (video_type, page_num))
377 for video in page['response']:
378 video_id = video['id']
379 entries.append(self.url_result(
380 'http://www.viki.com/videos/%s' % video_id, 'Viki'))
381 if not page['pagination']['next']:
382 break
383
384 return self.playlist_result(entries, channel_id, title, description)