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