Improve URL extraction
[youtube-dl] / youtube_dl / extractor / twitch.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import re
6 import random
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_HTTPError,
11     compat_kwargs,
12     compat_parse_qs,
13     compat_str,
14     compat_urllib_parse_urlencode,
15     compat_urllib_parse_urlparse,
16 )
17 from ..utils import (
18     clean_html,
19     ExtractorError,
20     float_or_none,
21     int_or_none,
22     orderedSet,
23     parse_duration,
24     parse_iso8601,
25     qualities,
26     try_get,
27     unified_timestamp,
28     update_url_query,
29     urlencode_postdata,
30     url_or_none,
31     urljoin,
32 )
33
34
35 class TwitchBaseIE(InfoExtractor):
36     _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv'
37
38     _API_BASE = 'https://api.twitch.tv'
39     _USHER_BASE = 'https://usher.ttvnw.net'
40     _LOGIN_URL = 'https://www.twitch.tv/login'
41     _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6'
42     _NETRC_MACHINE = 'twitch'
43
44     def _handle_error(self, response):
45         if not isinstance(response, dict):
46             return
47         error = response.get('error')
48         if error:
49             raise ExtractorError(
50                 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
51                 expected=True)
52
53     def _call_api(self, path, item_id, *args, **kwargs):
54         kwargs.setdefault('headers', {})['Client-ID'] = self._CLIENT_ID
55         response = self._download_json(
56             '%s/%s' % (self._API_BASE, path), item_id,
57             *args, **compat_kwargs(kwargs))
58         self._handle_error(response)
59         return response
60
61     def _real_initialize(self):
62         self._login()
63
64     def _login(self):
65         username, password = self._get_login_info()
66         if username is None:
67             return
68
69         def fail(message):
70             raise ExtractorError(
71                 'Unable to login. Twitch said: %s' % message, expected=True)
72
73         def login_step(page, urlh, note, data):
74             form = self._hidden_inputs(page)
75             form.update(data)
76
77             page_url = urlh.geturl()
78             post_url = self._search_regex(
79                 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
80                 'post url', default=page_url, group='url')
81             post_url = urljoin(page_url, post_url)
82
83             headers = {'Referer': page_url}
84
85             try:
86                 response = self._download_json(
87                     post_url, None, note,
88                     data=urlencode_postdata(form),
89                     headers=headers)
90             except ExtractorError as e:
91                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
92                     response = self._parse_json(
93                         e.cause.read().decode('utf-8'), None)
94                     fail(response.get('message') or response['errors'][0])
95                 raise
96
97             if 'Authenticated successfully' in response.get('message', ''):
98                 return None, None
99
100             redirect_url = urljoin(
101                 post_url,
102                 response.get('redirect') or response['redirect_path'])
103             return self._download_webpage_handle(
104                 redirect_url, None, 'Downloading login redirect page',
105                 headers=headers)
106
107         login_page, handle = self._download_webpage_handle(
108             self._LOGIN_URL, None, 'Downloading login page')
109
110         # Some TOR nodes and public proxies are blocked completely
111         if 'blacklist_message' in login_page:
112             fail(clean_html(login_page))
113
114         redirect_page, handle = login_step(
115             login_page, handle, 'Logging in', {
116                 'username': username,
117                 'password': password,
118             })
119
120         # Successful login
121         if not redirect_page:
122             return
123
124         if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
125             # TODO: Add mechanism to request an SMS or phone call
126             tfa_token = self._get_tfa_info('two-factor authentication token')
127             login_step(redirect_page, handle, 'Submitting TFA token', {
128                 'authy_token': tfa_token,
129                 'remember_2fa': 'true',
130             })
131
132     def _prefer_source(self, formats):
133         try:
134             source = next(f for f in formats if f['format_id'] == 'Source')
135             source['preference'] = 10
136         except StopIteration:
137             pass  # No Source stream present
138         self._sort_formats(formats)
139
140
141 class TwitchItemBaseIE(TwitchBaseIE):
142     def _download_info(self, item, item_id):
143         return self._extract_info(self._call_api(
144             'kraken/videos/%s%s' % (item, item_id), item_id,
145             'Downloading %s info JSON' % self._ITEM_TYPE))
146
147     def _extract_media(self, item_id):
148         info = self._download_info(self._ITEM_SHORTCUT, item_id)
149         response = self._call_api(
150             'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
151             'Downloading %s playlist JSON' % self._ITEM_TYPE)
152         entries = []
153         chunks = response['chunks']
154         qualities = list(chunks.keys())
155         for num, fragment in enumerate(zip(*chunks.values()), start=1):
156             formats = []
157             for fmt_num, fragment_fmt in enumerate(fragment):
158                 format_id = qualities[fmt_num]
159                 fmt = {
160                     'url': fragment_fmt['url'],
161                     'format_id': format_id,
162                     'quality': 1 if format_id == 'live' else 0,
163                 }
164                 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
165                 if m:
166                     fmt['height'] = int(m.group('height'))
167                 formats.append(fmt)
168             self._sort_formats(formats)
169             entry = dict(info)
170             entry['id'] = '%s_%d' % (entry['id'], num)
171             entry['title'] = '%s part %d' % (entry['title'], num)
172             entry['formats'] = formats
173             entries.append(entry)
174         return self.playlist_result(entries, info['id'], info['title'])
175
176     def _extract_info(self, info):
177         status = info.get('status')
178         if status == 'recording':
179             is_live = True
180         elif status == 'recorded':
181             is_live = False
182         else:
183             is_live = None
184         return {
185             'id': info['_id'],
186             'title': info.get('title') or 'Untitled Broadcast',
187             'description': info.get('description'),
188             'duration': int_or_none(info.get('length')),
189             'thumbnail': info.get('preview'),
190             'uploader': info.get('channel', {}).get('display_name'),
191             'uploader_id': info.get('channel', {}).get('name'),
192             'timestamp': parse_iso8601(info.get('recorded_at')),
193             'view_count': int_or_none(info.get('views')),
194             'is_live': is_live,
195         }
196
197     def _real_extract(self, url):
198         return self._extract_media(self._match_id(url))
199
200
201 class TwitchVideoIE(TwitchItemBaseIE):
202     IE_NAME = 'twitch:video'
203     _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
204     _ITEM_TYPE = 'video'
205     _ITEM_SHORTCUT = 'a'
206
207     _TEST = {
208         'url': 'http://www.twitch.tv/riotgames/b/577357806',
209         'info_dict': {
210             'id': 'a577357806',
211             'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
212         },
213         'playlist_mincount': 12,
214         'skip': 'HTTP Error 404: Not Found',
215     }
216
217
218 class TwitchChapterIE(TwitchItemBaseIE):
219     IE_NAME = 'twitch:chapter'
220     _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
221     _ITEM_TYPE = 'chapter'
222     _ITEM_SHORTCUT = 'c'
223
224     _TESTS = [{
225         'url': 'http://www.twitch.tv/acracingleague/c/5285812',
226         'info_dict': {
227             'id': 'c5285812',
228             'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
229         },
230         'playlist_mincount': 3,
231         'skip': 'HTTP Error 404: Not Found',
232     }, {
233         'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
234         'only_matching': True,
235     }]
236
237
238 class TwitchVodIE(TwitchItemBaseIE):
239     IE_NAME = 'twitch:vod'
240     _VALID_URL = r'''(?x)
241                     https?://
242                         (?:
243                             (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v|videos)/|
244                             player\.twitch\.tv/\?.*?\bvideo=v
245                         )
246                         (?P<id>\d+)
247                     '''
248     _ITEM_TYPE = 'vod'
249     _ITEM_SHORTCUT = 'v'
250
251     _TESTS = [{
252         'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
253         'info_dict': {
254             'id': 'v6528877',
255             'ext': 'mp4',
256             'title': 'LCK Summer Split - Week 6 Day 1',
257             'thumbnail': r're:^https?://.*\.jpg$',
258             'duration': 17208,
259             'timestamp': 1435131709,
260             'upload_date': '20150624',
261             'uploader': 'Riot Games',
262             'uploader_id': 'riotgames',
263             'view_count': int,
264             'start_time': 310,
265         },
266         'params': {
267             # m3u8 download
268             'skip_download': True,
269         },
270     }, {
271         # Untitled broadcast (title is None)
272         'url': 'http://www.twitch.tv/belkao_o/v/11230755',
273         'info_dict': {
274             'id': 'v11230755',
275             'ext': 'mp4',
276             'title': 'Untitled Broadcast',
277             'thumbnail': r're:^https?://.*\.jpg$',
278             'duration': 1638,
279             'timestamp': 1439746708,
280             'upload_date': '20150816',
281             'uploader': 'BelkAO_o',
282             'uploader_id': 'belkao_o',
283             'view_count': int,
284         },
285         'params': {
286             # m3u8 download
287             'skip_download': True,
288         },
289         'skip': 'HTTP Error 404: Not Found',
290     }, {
291         'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
292         'only_matching': True,
293     }, {
294         'url': 'https://www.twitch.tv/videos/6528877',
295         'only_matching': True,
296     }, {
297         'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
298         'only_matching': True,
299     }]
300
301     def _real_extract(self, url):
302         item_id = self._match_id(url)
303
304         info = self._download_info(self._ITEM_SHORTCUT, item_id)
305         access_token = self._call_api(
306             'api/vods/%s/access_token' % item_id, item_id,
307             'Downloading %s access token' % self._ITEM_TYPE)
308
309         formats = self._extract_m3u8_formats(
310             '%s/vod/%s?%s' % (
311                 self._USHER_BASE, item_id,
312                 compat_urllib_parse_urlencode({
313                     'allow_source': 'true',
314                     'allow_audio_only': 'true',
315                     'allow_spectre': 'true',
316                     'player': 'twitchweb',
317                     'nauth': access_token['token'],
318                     'nauthsig': access_token['sig'],
319                 })),
320             item_id, 'mp4', entry_protocol='m3u8_native')
321
322         self._prefer_source(formats)
323         info['formats'] = formats
324
325         parsed_url = compat_urllib_parse_urlparse(url)
326         query = compat_parse_qs(parsed_url.query)
327         if 't' in query:
328             info['start_time'] = parse_duration(query['t'][0])
329
330         if info.get('timestamp') is not None:
331             info['subtitles'] = {
332                 'rechat': [{
333                     'url': update_url_query(
334                         'https://rechat.twitch.tv/rechat-messages', {
335                             'video_id': 'v%s' % item_id,
336                             'start': info['timestamp'],
337                         }),
338                     'ext': 'json',
339                 }],
340             }
341
342         return info
343
344
345 class TwitchPlaylistBaseIE(TwitchBaseIE):
346     _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
347     _PAGE_LIMIT = 100
348
349     def _extract_playlist(self, channel_id):
350         info = self._call_api(
351             'kraken/channels/%s' % channel_id,
352             channel_id, 'Downloading channel info JSON')
353         channel_name = info.get('display_name') or info.get('name')
354         entries = []
355         offset = 0
356         limit = self._PAGE_LIMIT
357         broken_paging_detected = False
358         counter_override = None
359         for counter in itertools.count(1):
360             response = self._call_api(
361                 self._PLAYLIST_PATH % (channel_id, offset, limit),
362                 channel_id,
363                 'Downloading %s JSON page %s'
364                 % (self._PLAYLIST_TYPE, counter_override or counter))
365             page_entries = self._extract_playlist_page(response)
366             if not page_entries:
367                 break
368             total = int_or_none(response.get('_total'))
369             # Since the beginning of March 2016 twitch's paging mechanism
370             # is completely broken on the twitch side. It simply ignores
371             # a limit and returns the whole offset number of videos.
372             # Working around by just requesting all videos at once.
373             # Upd: pagination bug was fixed by twitch on 15.03.2016.
374             if not broken_paging_detected and total and len(page_entries) > limit:
375                 self.report_warning(
376                     'Twitch pagination is broken on twitch side, requesting all videos at once',
377                     channel_id)
378                 broken_paging_detected = True
379                 offset = total
380                 counter_override = '(all at once)'
381                 continue
382             entries.extend(page_entries)
383             if broken_paging_detected or total and len(page_entries) >= total:
384                 break
385             offset += limit
386         return self.playlist_result(
387             [self._make_url_result(entry) for entry in orderedSet(entries)],
388             channel_id, channel_name)
389
390     def _make_url_result(self, url):
391         try:
392             video_id = 'v%s' % TwitchVodIE._match_id(url)
393             return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
394         except AssertionError:
395             return self.url_result(url)
396
397     def _extract_playlist_page(self, response):
398         videos = response.get('videos')
399         return [video['url'] for video in videos] if videos else []
400
401     def _real_extract(self, url):
402         return self._extract_playlist(self._match_id(url))
403
404
405 class TwitchProfileIE(TwitchPlaylistBaseIE):
406     IE_NAME = 'twitch:profile'
407     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
408     _PLAYLIST_TYPE = 'profile'
409
410     _TESTS = [{
411         'url': 'http://www.twitch.tv/vanillatv/profile',
412         'info_dict': {
413             'id': 'vanillatv',
414             'title': 'VanillaTV',
415         },
416         'playlist_mincount': 412,
417     }, {
418         'url': 'http://m.twitch.tv/vanillatv/profile',
419         'only_matching': True,
420     }]
421
422
423 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
424     _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
425     _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
426
427
428 class TwitchAllVideosIE(TwitchVideosBaseIE):
429     IE_NAME = 'twitch:videos:all'
430     _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
431     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
432     _PLAYLIST_TYPE = 'all videos'
433
434     _TESTS = [{
435         'url': 'https://www.twitch.tv/spamfish/videos/all',
436         'info_dict': {
437             'id': 'spamfish',
438             'title': 'Spamfish',
439         },
440         'playlist_mincount': 869,
441     }, {
442         'url': 'https://m.twitch.tv/spamfish/videos/all',
443         'only_matching': True,
444     }]
445
446
447 class TwitchUploadsIE(TwitchVideosBaseIE):
448     IE_NAME = 'twitch:videos:uploads'
449     _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
450     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
451     _PLAYLIST_TYPE = 'uploads'
452
453     _TESTS = [{
454         'url': 'https://www.twitch.tv/spamfish/videos/uploads',
455         'info_dict': {
456             'id': 'spamfish',
457             'title': 'Spamfish',
458         },
459         'playlist_mincount': 0,
460     }, {
461         'url': 'https://m.twitch.tv/spamfish/videos/uploads',
462         'only_matching': True,
463     }]
464
465
466 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
467     IE_NAME = 'twitch:videos:past-broadcasts'
468     _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
469     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
470     _PLAYLIST_TYPE = 'past broadcasts'
471
472     _TESTS = [{
473         'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
474         'info_dict': {
475             'id': 'spamfish',
476             'title': 'Spamfish',
477         },
478         'playlist_mincount': 0,
479     }, {
480         'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
481         'only_matching': True,
482     }]
483
484
485 class TwitchHighlightsIE(TwitchVideosBaseIE):
486     IE_NAME = 'twitch:videos:highlights'
487     _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
488     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
489     _PLAYLIST_TYPE = 'highlights'
490
491     _TESTS = [{
492         'url': 'https://www.twitch.tv/spamfish/videos/highlights',
493         'info_dict': {
494             'id': 'spamfish',
495             'title': 'Spamfish',
496         },
497         'playlist_mincount': 805,
498     }, {
499         'url': 'https://m.twitch.tv/spamfish/videos/highlights',
500         'only_matching': True,
501     }]
502
503
504 class TwitchStreamIE(TwitchBaseIE):
505     IE_NAME = 'twitch:stream'
506     _VALID_URL = r'''(?x)
507                     https?://
508                         (?:
509                             (?:(?:www|go|m)\.)?twitch\.tv/|
510                             player\.twitch\.tv/\?.*?\bchannel=
511                         )
512                         (?P<id>[^/#?]+)
513                     '''
514
515     _TESTS = [{
516         'url': 'http://www.twitch.tv/shroomztv',
517         'info_dict': {
518             'id': '12772022048',
519             'display_id': 'shroomztv',
520             'ext': 'mp4',
521             'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
522             'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
523             'is_live': True,
524             'timestamp': 1421928037,
525             'upload_date': '20150122',
526             'uploader': 'ShroomzTV',
527             'uploader_id': 'shroomztv',
528             'view_count': int,
529         },
530         'params': {
531             # m3u8 download
532             'skip_download': True,
533         },
534     }, {
535         'url': 'http://www.twitch.tv/miracle_doto#profile-0',
536         'only_matching': True,
537     }, {
538         'url': 'https://player.twitch.tv/?channel=lotsofs',
539         'only_matching': True,
540     }, {
541         'url': 'https://go.twitch.tv/food',
542         'only_matching': True,
543     }, {
544         'url': 'https://m.twitch.tv/food',
545         'only_matching': True,
546     }]
547
548     @classmethod
549     def suitable(cls, url):
550         return (False
551                 if any(ie.suitable(url) for ie in (
552                     TwitchVideoIE,
553                     TwitchChapterIE,
554                     TwitchVodIE,
555                     TwitchProfileIE,
556                     TwitchAllVideosIE,
557                     TwitchUploadsIE,
558                     TwitchPastBroadcastsIE,
559                     TwitchHighlightsIE))
560                 else super(TwitchStreamIE, cls).suitable(url))
561
562     def _real_extract(self, url):
563         channel_id = self._match_id(url)
564
565         stream = self._call_api(
566             'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
567             'Downloading stream JSON').get('stream')
568
569         if not stream:
570             raise ExtractorError('%s is offline' % channel_id, expected=True)
571
572         # Channel name may be typed if different case than the original channel name
573         # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
574         # an invalid m3u8 URL. Working around by use of original channel name from stream
575         # JSON and fallback to lowercase if it's not available.
576         channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
577
578         access_token = self._call_api(
579             'api/channels/%s/access_token' % channel_id, channel_id,
580             'Downloading channel access token')
581
582         query = {
583             'allow_source': 'true',
584             'allow_audio_only': 'true',
585             'allow_spectre': 'true',
586             'p': random.randint(1000000, 10000000),
587             'player': 'twitchweb',
588             'segment_preference': '4',
589             'sig': access_token['sig'].encode('utf-8'),
590             'token': access_token['token'].encode('utf-8'),
591         }
592         formats = self._extract_m3u8_formats(
593             '%s/api/channel/hls/%s.m3u8?%s'
594             % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
595             channel_id, 'mp4')
596         self._prefer_source(formats)
597
598         view_count = stream.get('viewers')
599         timestamp = parse_iso8601(stream.get('created_at'))
600
601         channel = stream['channel']
602         title = self._live_title(channel.get('display_name') or channel.get('name'))
603         description = channel.get('status')
604
605         thumbnails = []
606         for thumbnail_key, thumbnail_url in stream['preview'].items():
607             m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
608             if not m:
609                 continue
610             thumbnails.append({
611                 'url': thumbnail_url,
612                 'width': int(m.group('width')),
613                 'height': int(m.group('height')),
614             })
615
616         return {
617             'id': compat_str(stream['_id']),
618             'display_id': channel_id,
619             'title': title,
620             'description': description,
621             'thumbnails': thumbnails,
622             'uploader': channel.get('display_name'),
623             'uploader_id': channel.get('name'),
624             'timestamp': timestamp,
625             'view_count': view_count,
626             'formats': formats,
627             'is_live': True,
628         }
629
630
631 class TwitchClipsIE(TwitchBaseIE):
632     IE_NAME = 'twitch:clips'
633     _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
634
635     _TESTS = [{
636         'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
637         'md5': '761769e1eafce0ffebfb4089cb3847cd',
638         'info_dict': {
639             'id': '42850523',
640             'ext': 'mp4',
641             'title': 'EA Play 2016 Live from the Novo Theatre',
642             'thumbnail': r're:^https?://.*\.jpg',
643             'timestamp': 1465767393,
644             'upload_date': '20160612',
645             'creator': 'EA',
646             'uploader': 'stereotype_',
647             'uploader_id': '43566419',
648         },
649     }, {
650         # multiple formats
651         'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
652         'only_matching': True,
653     }]
654
655     def _real_extract(self, url):
656         video_id = self._match_id(url)
657
658         status = self._download_json(
659             'https://clips.twitch.tv/api/v2/clips/%s/status' % video_id,
660             video_id)
661
662         formats = []
663
664         for option in status['quality_options']:
665             if not isinstance(option, dict):
666                 continue
667             source = url_or_none(option.get('source'))
668             if not source:
669                 continue
670             formats.append({
671                 'url': source,
672                 'format_id': option.get('quality'),
673                 'height': int_or_none(option.get('quality')),
674                 'fps': int_or_none(option.get('frame_rate')),
675             })
676
677         self._sort_formats(formats)
678
679         info = {
680             'formats': formats,
681         }
682
683         clip = self._call_api(
684             'kraken/clips/%s' % video_id, video_id, fatal=False, headers={
685                 'Accept': 'application/vnd.twitchtv.v5+json',
686             })
687
688         if clip:
689             quality_key = qualities(('tiny', 'small', 'medium'))
690             thumbnails = []
691             thumbnails_dict = clip.get('thumbnails')
692             if isinstance(thumbnails_dict, dict):
693                 for thumbnail_id, thumbnail_url in thumbnails_dict.items():
694                     thumbnails.append({
695                         'id': thumbnail_id,
696                         'url': thumbnail_url,
697                         'preference': quality_key(thumbnail_id),
698                     })
699
700             info.update({
701                 'id': clip.get('tracking_id') or video_id,
702                 'title': clip.get('title') or video_id,
703                 'duration': float_or_none(clip.get('duration')),
704                 'views': int_or_none(clip.get('views')),
705                 'timestamp': unified_timestamp(clip.get('created_at')),
706                 'thumbnails': thumbnails,
707                 'creator': try_get(clip, lambda x: x['broadcaster']['display_name'], compat_str),
708                 'uploader': try_get(clip, lambda x: x['curator']['display_name'], compat_str),
709                 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),
710             })
711         else:
712             info.update({
713                 'title': video_id,
714                 'id': video_id,
715             })
716
717         return info