[viki] Add support for authentication (Closes #6005)
[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 ..utils import (
11     ExtractorError,
12     int_or_none,
13     parse_age_limit,
14     parse_iso8601,
15 )
16 from ..compat import compat_urllib_request
17 from .common import InfoExtractor
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     def _prepare_call(self, path, timestamp=None, post_data=None):
32         path += '?' if '?' not in path else '&'
33         if not timestamp:
34             timestamp = int(time.time())
35         query = self._API_QUERY_TEMPLATE % (path, self._APP, timestamp)
36         sig = hmac.new(
37             self._APP_SECRET.encode('ascii'),
38             query.encode('ascii'),
39             hashlib.sha1
40         ).hexdigest()
41         url = self._API_URL_TEMPLATE % (query, sig)
42         return compat_urllib_request.Request(
43             url, json.dumps(post_data).encode('utf-8')) if post_data else url
44
45     def _call_api(self, path, video_id, note, timestamp=None, post_data=None):
46         resp = self._download_json(
47             self._prepare_call(path, timestamp, post_data), video_id, note)
48
49         error = resp.get('error')
50         if error:
51             if error == 'invalid timestamp':
52                 resp = self._download_json(
53                     self._prepare_call(path, int(resp['current_timestamp']), post_data),
54                     video_id, '%s (retry)' % note)
55                 error = resp.get('error')
56             if error:
57                 self._raise_error(resp['error'])
58
59         return resp
60
61     def _raise_error(self, error):
62         raise ExtractorError(
63             '%s returned error: %s' % (self.IE_NAME, error),
64             expected=True)
65
66     def _real_initialize(self):
67         self._login()
68
69     def _login(self):
70         (username, password) = self._get_login_info()
71         if username is None:
72             return
73
74         login_form = {
75             'login_id': username,
76             'password': password,
77         }
78
79         self._call_api(
80             'sessions.json', None,
81             'Logging in as %s' % username, post_data=login_form)
82
83
84 class VikiIE(VikiBaseIE):
85     IE_NAME = 'viki'
86     _VALID_URL = r'%s(?:videos|player)/(?P<id>[0-9]+v)' % VikiBaseIE._VALID_URL_BASE
87     _TESTS = [{
88         'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
89         'info_dict': {
90             'id': '1023585v',
91             'ext': 'mp4',
92             'title': 'Heirs Episode 14',
93             'uploader': 'SBS',
94             'description': 'md5:c4b17b9626dd4b143dcc4d855ba3474e',
95             'upload_date': '20131121',
96             'age_limit': 13,
97         },
98         'skip': 'Blocked in the US',
99     }, {
100         # clip
101         'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
102         'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
103         'info_dict': {
104             'id': '1067139v',
105             'ext': 'mp4',
106             'title': "'The Avengers: Age of Ultron' Press Conference",
107             'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
108             'duration': 352,
109             'timestamp': 1430380829,
110             'upload_date': '20150430',
111             'uploader': 'Arirang TV',
112             'like_count': int,
113             'age_limit': 0,
114         }
115     }, {
116         'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
117         'info_dict': {
118             'id': '1048879v',
119             'ext': 'mp4',
120             'title': 'Ankhon Dekhi',
121             'duration': 6512,
122             'timestamp': 1408532356,
123             'upload_date': '20140820',
124             'uploader': 'Spuul',
125             'like_count': int,
126             'age_limit': 13,
127         },
128         'params': {
129             # m3u8 download
130             'skip_download': True,
131         }
132     }, {
133         # episode
134         'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
135         'md5': '190f3ef426005ba3a080a63325955bc3',
136         'info_dict': {
137             'id': '44699v',
138             'ext': 'mp4',
139             'title': 'Boys Over Flowers - Episode 1',
140             'description': 'md5:52617e4f729c7d03bfd4bcbbb6e946f2',
141             'duration': 4155,
142             'timestamp': 1270496524,
143             'upload_date': '20100405',
144             'uploader': 'group8',
145             'like_count': int,
146             'age_limit': 13,
147         }
148     }, {
149         # youtube external
150         'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
151         'md5': '216d1afdc0c64d1febc1e9f2bd4b864b',
152         'info_dict': {
153             'id': '50562v',
154             'ext': 'mp4',
155             'title': 'Poor Nastya [COMPLETE] - Episode 1',
156             'description': '',
157             'duration': 607,
158             'timestamp': 1274949505,
159             'upload_date': '20101213',
160             'uploader': 'ad14065n',
161             'uploader_id': 'ad14065n',
162             'like_count': int,
163             'age_limit': 13,
164         }
165     }, {
166         'url': 'http://www.viki.com/player/44699v',
167         'only_matching': True,
168     }]
169
170     def _real_extract(self, url):
171         video_id = self._match_id(url)
172
173         video = self._call_api(
174             'videos/%s.json' % video_id, video_id, 'Downloading video JSON')
175
176         title = None
177         titles = video.get('titles')
178         if titles:
179             title = titles.get('en') or titles[titles.keys()[0]]
180         if not title:
181             title = 'Episode %d' % video.get('number') if video.get('type') == 'episode' else video.get('id') or video_id
182             container_titles = video.get('container', {}).get('titles')
183             if container_titles:
184                 container_title = container_titles.get('en') or container_titles[container_titles.keys()[0]]
185                 title = '%s - %s' % (container_title, title)
186
187         descriptions = video.get('descriptions')
188         description = descriptions.get('en') or descriptions[titles.keys()[0]] if descriptions else None
189
190         duration = int_or_none(video.get('duration'))
191         timestamp = parse_iso8601(video.get('created_at'))
192         uploader = video.get('author')
193         like_count = int_or_none(video.get('likes', {}).get('count'))
194         age_limit = parse_age_limit(video.get('rating'))
195
196         thumbnails = []
197         for thumbnail_id, thumbnail in video.get('images', {}).items():
198             thumbnails.append({
199                 'id': thumbnail_id,
200                 'url': thumbnail.get('url'),
201             })
202
203         subtitles = {}
204         for subtitle_lang, _ in video.get('subtitle_completions', {}).items():
205             subtitles[subtitle_lang] = [{
206                 'ext': subtitles_format,
207                 'url': self._prepare_call(
208                     'videos/%s/subtitles/%s.%s' % (video_id, subtitle_lang, subtitles_format)),
209             } for subtitles_format in ('srt', 'vtt')]
210
211         result = {
212             'id': video_id,
213             'title': title,
214             'description': description,
215             'duration': duration,
216             'timestamp': timestamp,
217             'uploader': uploader,
218             'like_count': like_count,
219             'age_limit': age_limit,
220             'thumbnails': thumbnails,
221             'subtitles': subtitles,
222         }
223
224         streams = self._call_api(
225             'videos/%s/streams.json' % video_id, video_id,
226             'Downloading video streams JSON')
227
228         if 'external' in streams:
229             result.update({
230                 '_type': 'url_transparent',
231                 'url': streams['external']['url'],
232             })
233             return result
234
235         formats = []
236         for format_id, stream_dict in streams.items():
237             height = self._search_regex(
238                 r'^(\d+)[pP]$', format_id, 'height', default=None)
239             for protocol, format_dict in stream_dict.items():
240                 if format_id == 'm3u8':
241                     formats = self._extract_m3u8_formats(
242                         format_dict['url'], video_id, 'mp4', m3u8_id='m3u8-%s' % protocol)
243                 else:
244                     formats.append({
245                         'url': format_dict['url'],
246                         'format_id': '%s-%s' % (format_id, protocol),
247                         'height': height,
248                     })
249         self._sort_formats(formats)
250
251         result['formats'] = formats
252         return result
253
254
255 class VikiChannelIE(VikiBaseIE):
256     IE_NAME = 'viki:channel'
257     _VALID_URL = r'%s(?:tv|news|movies|artists)/(?P<id>[0-9]+c)' % VikiBaseIE._VALID_URL_BASE
258     _TESTS = [{
259         'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
260         'info_dict': {
261             'id': '50c',
262             'title': 'Boys Over Flowers',
263             'description': 'md5:ecd3cff47967fe193cff37c0bec52790',
264         },
265         'playlist_count': 70,
266     }, {
267         'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
268         'info_dict': {
269             'id': '1354c',
270             'title': 'Poor Nastya [COMPLETE]',
271             'description': 'md5:05bf5471385aa8b21c18ad450e350525',
272         },
273         'playlist_count': 127,
274     }, {
275         'url': 'http://www.viki.com/news/24569c-showbiz-korea',
276         'only_matching': True,
277     }, {
278         'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
279         'only_matching': True,
280     }, {
281         'url': 'http://www.viki.com/artists/2141c-shinee',
282         'only_matching': True,
283     }]
284
285     _PER_PAGE = 25
286
287     def _real_extract(self, url):
288         channel_id = self._match_id(url)
289
290         channel = self._call_api(
291             'containers/%s.json' % channel_id, channel_id,
292             'Downloading channel JSON')
293
294         titles = channel['titles']
295         title = titles.get('en') or titles[titles.keys()[0]]
296
297         descriptions = channel['descriptions']
298         description = descriptions.get('en') or descriptions[descriptions.keys()[0]]
299
300         entries = []
301         for video_type in ('episodes', 'clips', 'movies'):
302             for page_num in itertools.count(1):
303                 page = self._call_api(
304                     'containers/%s/%s.json?per_page=%d&sort=number&direction=asc&with_paging=true&page=%d'
305                     % (channel_id, video_type, self._PER_PAGE, page_num), channel_id,
306                     'Downloading %s JSON page #%d' % (video_type, page_num))
307                 for video in page['response']:
308                     video_id = video['id']
309                     entries.append(self.url_result(
310                         'http://www.viki.com/videos/%s' % video_id, 'Viki'))
311                 if not page['pagination']['next']:
312                     break
313
314         return self.playlist_result(entries, channel_id, title, description)