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