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