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