]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/twitch.py
New upstream version 2018.09.10
[youtubedl] / 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_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 url_or_none,
30 urljoin,
31 )
32
33
34 class TwitchBaseIE(InfoExtractor):
35 _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv'
36
37 _API_BASE = 'https://api.twitch.tv'
38 _USHER_BASE = 'https://usher.ttvnw.net'
39 _LOGIN_FORM_URL = 'https://www.twitch.tv/login'
40 _LOGIN_POST_URL = 'https://passport.twitch.tv/login'
41 _CLIENT_ID = 'kimne78kx3ncx6brgo4mv6wki5h1ko'
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=self._LOGIN_POST_URL, group='url')
81 post_url = urljoin(page_url, post_url)
82
83 headers = {
84 'Referer': page_url,
85 'Origin': page_url,
86 'Content-Type': 'text/plain;charset=UTF-8',
87 }
88
89 response = self._download_json(
90 post_url, None, note, data=json.dumps(form).encode(),
91 headers=headers, expected_status=400)
92 error = response.get('error_description') or response.get('error_code')
93 if error:
94 fail(error)
95
96 if 'Authenticated successfully' in response.get('message', ''):
97 return None, None
98
99 redirect_url = urljoin(
100 post_url,
101 response.get('redirect') or response['redirect_path'])
102 return self._download_webpage_handle(
103 redirect_url, None, 'Downloading login redirect page',
104 headers=headers)
105
106 login_page, handle = self._download_webpage_handle(
107 self._LOGIN_FORM_URL, None, 'Downloading login page')
108
109 # Some TOR nodes and public proxies are blocked completely
110 if 'blacklist_message' in login_page:
111 fail(clean_html(login_page))
112
113 redirect_page, handle = login_step(
114 login_page, handle, 'Logging in', {
115 'username': username,
116 'password': password,
117 'client_id': self._CLIENT_ID,
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(?:ideo)?|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 'url': 'https://www.twitch.tv/northernlion/video/291940395',
301 'only_matching': True,
302 }]
303
304 def _real_extract(self, url):
305 item_id = self._match_id(url)
306
307 info = self._download_info(self._ITEM_SHORTCUT, item_id)
308 access_token = self._call_api(
309 'api/vods/%s/access_token' % item_id, item_id,
310 'Downloading %s access token' % self._ITEM_TYPE)
311
312 formats = self._extract_m3u8_formats(
313 '%s/vod/%s?%s' % (
314 self._USHER_BASE, item_id,
315 compat_urllib_parse_urlencode({
316 'allow_source': 'true',
317 'allow_audio_only': 'true',
318 'allow_spectre': 'true',
319 'player': 'twitchweb',
320 'nauth': access_token['token'],
321 'nauthsig': access_token['sig'],
322 })),
323 item_id, 'mp4', entry_protocol='m3u8_native')
324
325 self._prefer_source(formats)
326 info['formats'] = formats
327
328 parsed_url = compat_urllib_parse_urlparse(url)
329 query = compat_parse_qs(parsed_url.query)
330 if 't' in query:
331 info['start_time'] = parse_duration(query['t'][0])
332
333 if info.get('timestamp') is not None:
334 info['subtitles'] = {
335 'rechat': [{
336 'url': update_url_query(
337 'https://rechat.twitch.tv/rechat-messages', {
338 'video_id': 'v%s' % item_id,
339 'start': info['timestamp'],
340 }),
341 'ext': 'json',
342 }],
343 }
344
345 return info
346
347
348 class TwitchPlaylistBaseIE(TwitchBaseIE):
349 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
350 _PAGE_LIMIT = 100
351
352 def _extract_playlist(self, channel_id):
353 info = self._call_api(
354 'kraken/channels/%s' % channel_id,
355 channel_id, 'Downloading channel info JSON')
356 channel_name = info.get('display_name') or info.get('name')
357 entries = []
358 offset = 0
359 limit = self._PAGE_LIMIT
360 broken_paging_detected = False
361 counter_override = None
362 for counter in itertools.count(1):
363 response = self._call_api(
364 self._PLAYLIST_PATH % (channel_id, offset, limit),
365 channel_id,
366 'Downloading %s JSON page %s'
367 % (self._PLAYLIST_TYPE, counter_override or counter))
368 page_entries = self._extract_playlist_page(response)
369 if not page_entries:
370 break
371 total = int_or_none(response.get('_total'))
372 # Since the beginning of March 2016 twitch's paging mechanism
373 # is completely broken on the twitch side. It simply ignores
374 # a limit and returns the whole offset number of videos.
375 # Working around by just requesting all videos at once.
376 # Upd: pagination bug was fixed by twitch on 15.03.2016.
377 if not broken_paging_detected and total and len(page_entries) > limit:
378 self.report_warning(
379 'Twitch pagination is broken on twitch side, requesting all videos at once',
380 channel_id)
381 broken_paging_detected = True
382 offset = total
383 counter_override = '(all at once)'
384 continue
385 entries.extend(page_entries)
386 if broken_paging_detected or total and len(page_entries) >= total:
387 break
388 offset += limit
389 return self.playlist_result(
390 [self._make_url_result(entry) for entry in orderedSet(entries)],
391 channel_id, channel_name)
392
393 def _make_url_result(self, url):
394 try:
395 video_id = 'v%s' % TwitchVodIE._match_id(url)
396 return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
397 except AssertionError:
398 return self.url_result(url)
399
400 def _extract_playlist_page(self, response):
401 videos = response.get('videos')
402 return [video['url'] for video in videos] if videos else []
403
404 def _real_extract(self, url):
405 return self._extract_playlist(self._match_id(url))
406
407
408 class TwitchProfileIE(TwitchPlaylistBaseIE):
409 IE_NAME = 'twitch:profile'
410 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
411 _PLAYLIST_TYPE = 'profile'
412
413 _TESTS = [{
414 'url': 'http://www.twitch.tv/vanillatv/profile',
415 'info_dict': {
416 'id': 'vanillatv',
417 'title': 'VanillaTV',
418 },
419 'playlist_mincount': 412,
420 }, {
421 'url': 'http://m.twitch.tv/vanillatv/profile',
422 'only_matching': True,
423 }]
424
425
426 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
427 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
428 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
429
430
431 class TwitchAllVideosIE(TwitchVideosBaseIE):
432 IE_NAME = 'twitch:videos:all'
433 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
434 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
435 _PLAYLIST_TYPE = 'all videos'
436
437 _TESTS = [{
438 'url': 'https://www.twitch.tv/spamfish/videos/all',
439 'info_dict': {
440 'id': 'spamfish',
441 'title': 'Spamfish',
442 },
443 'playlist_mincount': 869,
444 }, {
445 'url': 'https://m.twitch.tv/spamfish/videos/all',
446 'only_matching': True,
447 }]
448
449
450 class TwitchUploadsIE(TwitchVideosBaseIE):
451 IE_NAME = 'twitch:videos:uploads'
452 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
453 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
454 _PLAYLIST_TYPE = 'uploads'
455
456 _TESTS = [{
457 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
458 'info_dict': {
459 'id': 'spamfish',
460 'title': 'Spamfish',
461 },
462 'playlist_mincount': 0,
463 }, {
464 'url': 'https://m.twitch.tv/spamfish/videos/uploads',
465 'only_matching': True,
466 }]
467
468
469 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
470 IE_NAME = 'twitch:videos:past-broadcasts'
471 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
472 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
473 _PLAYLIST_TYPE = 'past broadcasts'
474
475 _TESTS = [{
476 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
477 'info_dict': {
478 'id': 'spamfish',
479 'title': 'Spamfish',
480 },
481 'playlist_mincount': 0,
482 }, {
483 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
484 'only_matching': True,
485 }]
486
487
488 class TwitchHighlightsIE(TwitchVideosBaseIE):
489 IE_NAME = 'twitch:videos:highlights'
490 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
491 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
492 _PLAYLIST_TYPE = 'highlights'
493
494 _TESTS = [{
495 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
496 'info_dict': {
497 'id': 'spamfish',
498 'title': 'Spamfish',
499 },
500 'playlist_mincount': 805,
501 }, {
502 'url': 'https://m.twitch.tv/spamfish/videos/highlights',
503 'only_matching': True,
504 }]
505
506
507 class TwitchStreamIE(TwitchBaseIE):
508 IE_NAME = 'twitch:stream'
509 _VALID_URL = r'''(?x)
510 https?://
511 (?:
512 (?:(?:www|go|m)\.)?twitch\.tv/|
513 player\.twitch\.tv/\?.*?\bchannel=
514 )
515 (?P<id>[^/#?]+)
516 '''
517
518 _TESTS = [{
519 'url': 'http://www.twitch.tv/shroomztv',
520 'info_dict': {
521 'id': '12772022048',
522 'display_id': 'shroomztv',
523 'ext': 'mp4',
524 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
525 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
526 'is_live': True,
527 'timestamp': 1421928037,
528 'upload_date': '20150122',
529 'uploader': 'ShroomzTV',
530 'uploader_id': 'shroomztv',
531 'view_count': int,
532 },
533 'params': {
534 # m3u8 download
535 'skip_download': True,
536 },
537 }, {
538 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
539 'only_matching': True,
540 }, {
541 'url': 'https://player.twitch.tv/?channel=lotsofs',
542 'only_matching': True,
543 }, {
544 'url': 'https://go.twitch.tv/food',
545 'only_matching': True,
546 }, {
547 'url': 'https://m.twitch.tv/food',
548 'only_matching': True,
549 }]
550
551 @classmethod
552 def suitable(cls, url):
553 return (False
554 if any(ie.suitable(url) for ie in (
555 TwitchVideoIE,
556 TwitchChapterIE,
557 TwitchVodIE,
558 TwitchProfileIE,
559 TwitchAllVideosIE,
560 TwitchUploadsIE,
561 TwitchPastBroadcastsIE,
562 TwitchHighlightsIE))
563 else super(TwitchStreamIE, cls).suitable(url))
564
565 def _real_extract(self, url):
566 channel_id = self._match_id(url)
567
568 stream = self._call_api(
569 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
570 'Downloading stream JSON').get('stream')
571
572 if not stream:
573 raise ExtractorError('%s is offline' % channel_id, expected=True)
574
575 # Channel name may be typed if different case than the original channel name
576 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
577 # an invalid m3u8 URL. Working around by use of original channel name from stream
578 # JSON and fallback to lowercase if it's not available.
579 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
580
581 access_token = self._call_api(
582 'api/channels/%s/access_token' % channel_id, channel_id,
583 'Downloading channel access token')
584
585 query = {
586 'allow_source': 'true',
587 'allow_audio_only': 'true',
588 'allow_spectre': 'true',
589 'p': random.randint(1000000, 10000000),
590 'player': 'twitchweb',
591 'segment_preference': '4',
592 'sig': access_token['sig'].encode('utf-8'),
593 'token': access_token['token'].encode('utf-8'),
594 }
595 formats = self._extract_m3u8_formats(
596 '%s/api/channel/hls/%s.m3u8?%s'
597 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
598 channel_id, 'mp4')
599 self._prefer_source(formats)
600
601 view_count = stream.get('viewers')
602 timestamp = parse_iso8601(stream.get('created_at'))
603
604 channel = stream['channel']
605 title = self._live_title(channel.get('display_name') or channel.get('name'))
606 description = channel.get('status')
607
608 thumbnails = []
609 for thumbnail_key, thumbnail_url in stream['preview'].items():
610 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
611 if not m:
612 continue
613 thumbnails.append({
614 'url': thumbnail_url,
615 'width': int(m.group('width')),
616 'height': int(m.group('height')),
617 })
618
619 return {
620 'id': compat_str(stream['_id']),
621 'display_id': channel_id,
622 'title': title,
623 'description': description,
624 'thumbnails': thumbnails,
625 'uploader': channel.get('display_name'),
626 'uploader_id': channel.get('name'),
627 'timestamp': timestamp,
628 'view_count': view_count,
629 'formats': formats,
630 'is_live': True,
631 }
632
633
634 class TwitchClipsIE(TwitchBaseIE):
635 IE_NAME = 'twitch:clips'
636 _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
637
638 _TESTS = [{
639 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
640 'md5': '761769e1eafce0ffebfb4089cb3847cd',
641 'info_dict': {
642 'id': '42850523',
643 'ext': 'mp4',
644 'title': 'EA Play 2016 Live from the Novo Theatre',
645 'thumbnail': r're:^https?://.*\.jpg',
646 'timestamp': 1465767393,
647 'upload_date': '20160612',
648 'creator': 'EA',
649 'uploader': 'stereotype_',
650 'uploader_id': '43566419',
651 },
652 }, {
653 # multiple formats
654 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
655 'only_matching': True,
656 }]
657
658 def _real_extract(self, url):
659 video_id = self._match_id(url)
660
661 status = self._download_json(
662 'https://clips.twitch.tv/api/v2/clips/%s/status' % video_id,
663 video_id)
664
665 formats = []
666
667 for option in status['quality_options']:
668 if not isinstance(option, dict):
669 continue
670 source = url_or_none(option.get('source'))
671 if not source:
672 continue
673 formats.append({
674 'url': source,
675 'format_id': option.get('quality'),
676 'height': int_or_none(option.get('quality')),
677 'fps': int_or_none(option.get('frame_rate')),
678 })
679
680 self._sort_formats(formats)
681
682 info = {
683 'formats': formats,
684 }
685
686 clip = self._call_api(
687 'kraken/clips/%s' % video_id, video_id, fatal=False, headers={
688 'Accept': 'application/vnd.twitchtv.v5+json',
689 })
690
691 if clip:
692 quality_key = qualities(('tiny', 'small', 'medium'))
693 thumbnails = []
694 thumbnails_dict = clip.get('thumbnails')
695 if isinstance(thumbnails_dict, dict):
696 for thumbnail_id, thumbnail_url in thumbnails_dict.items():
697 thumbnails.append({
698 'id': thumbnail_id,
699 'url': thumbnail_url,
700 'preference': quality_key(thumbnail_id),
701 })
702
703 info.update({
704 'id': clip.get('tracking_id') or video_id,
705 'title': clip.get('title') or video_id,
706 'duration': float_or_none(clip.get('duration')),
707 'views': int_or_none(clip.get('views')),
708 'timestamp': unified_timestamp(clip.get('created_at')),
709 'thumbnails': thumbnails,
710 'creator': try_get(clip, lambda x: x['broadcaster']['display_name'], compat_str),
711 'uploader': try_get(clip, lambda x: x['curator']['display_name'], compat_str),
712 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),
713 })
714 else:
715 info.update({
716 'title': video_id,
717 'id': video_id,
718 })
719
720 return info