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