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