[cleanup] Misc (#8968)
[yt-dlp.git] / yt_dlp / extractor / twitch.py
blobc55786a0dce188ea138e87418a452f57e361fbeb
1 import collections
2 import itertools
3 import json
4 import random
5 import re
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_parse_qs,
10 compat_str,
11 compat_urllib_parse_urlparse,
13 from ..utils import (
14 ExtractorError,
15 UserNotLive,
16 base_url,
17 clean_html,
18 dict_get,
19 float_or_none,
20 int_or_none,
21 make_archive_id,
22 parse_duration,
23 parse_iso8601,
24 parse_qs,
25 qualities,
26 str_or_none,
27 traverse_obj,
28 try_get,
29 unified_timestamp,
30 update_url_query,
31 url_or_none,
32 urljoin,
36 class TwitchBaseIE(InfoExtractor):
37 _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv'
39 _API_BASE = 'https://api.twitch.tv'
40 _USHER_BASE = 'https://usher.ttvnw.net'
41 _LOGIN_FORM_URL = 'https://www.twitch.tv/login'
42 _LOGIN_POST_URL = 'https://passport.twitch.tv/login'
43 _NETRC_MACHINE = 'twitch'
45 _OPERATION_HASHES = {
46 'CollectionSideBar': '27111f1b382effad0b6def325caef1909c733fe6a4fbabf54f8d491ef2cf2f14',
47 'FilterableVideoTower_Videos': 'a937f1d22e269e39a03b509f65a7490f9fc247d7f83d6ac1421523e3b68042cb',
48 'ClipsCards__User': 'b73ad2bfaecfd30a9e6c28fada15bd97032c83ec77a0440766a56fe0bd632777',
49 'ChannelCollectionsContent': '447aec6a0cc1e8d0a8d7732d47eb0762c336a2294fdb009e9c9d854e49d484b9',
50 'StreamMetadata': 'a647c2a13599e5991e175155f798ca7f1ecddde73f7f341f39009c14dbf59962',
51 'ComscoreStreamingQuery': 'e1edae8122517d013405f237ffcc124515dc6ded82480a88daef69c83b53ac01',
52 'VideoAccessToken_Clip': '36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11',
53 'VideoPreviewOverlay': '3006e77e51b128d838fa4e835723ca4dc9a05c5efd4466c1085215c6e437e65c',
54 'VideoMetadata': '49b5b8f268cdeb259d75b58dcb0c1a748e3b575003448a2333dc5cdafd49adad',
55 'VideoPlayer_ChapterSelectButtonVideo': '8d2793384aac3773beab5e59bd5d6f585aedb923d292800119e03d40cd0f9b41',
56 'VideoPlayer_VODSeekbarPreviewVideo': '07e99e4d56c5a7c67117a154777b0baf85a5ffefa393b213f4bc712ccaf85dd6',
59 @property
60 def _CLIENT_ID(self):
61 return self._configuration_arg(
62 'client_id', ['ue6666qo983tsx6so1t0vnawi233wa'], ie_key='Twitch', casesense=True)[0]
64 def _perform_login(self, username, password):
65 def fail(message):
66 raise ExtractorError(
67 'Unable to login. Twitch said: %s' % message, expected=True)
69 def login_step(page, urlh, note, data):
70 form = self._hidden_inputs(page)
71 form.update(data)
73 page_url = urlh.url
74 post_url = self._search_regex(
75 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
76 'post url', default=self._LOGIN_POST_URL, group='url')
77 post_url = urljoin(page_url, post_url)
79 headers = {
80 'Referer': page_url,
81 'Origin': 'https://www.twitch.tv',
82 'Content-Type': 'text/plain;charset=UTF-8',
85 response = self._download_json(
86 post_url, None, note, data=json.dumps(form).encode(),
87 headers=headers, expected_status=400)
88 error = dict_get(response, ('error', 'error_description', 'error_code'))
89 if error:
90 fail(error)
92 if 'Authenticated successfully' in response.get('message', ''):
93 return None, None
95 redirect_url = urljoin(
96 post_url,
97 response.get('redirect') or response['redirect_path'])
98 return self._download_webpage_handle(
99 redirect_url, None, 'Downloading login redirect page',
100 headers=headers)
102 login_page, handle = self._download_webpage_handle(
103 self._LOGIN_FORM_URL, None, 'Downloading login page')
105 # Some TOR nodes and public proxies are blocked completely
106 if 'blacklist_message' in login_page:
107 fail(clean_html(login_page))
109 redirect_page, handle = login_step(
110 login_page, handle, 'Logging in', {
111 'username': username,
112 'password': password,
113 'client_id': self._CLIENT_ID,
116 # Successful login
117 if not redirect_page:
118 return
120 if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
121 # TODO: Add mechanism to request an SMS or phone call
122 tfa_token = self._get_tfa_info('two-factor authentication token')
123 login_step(redirect_page, handle, 'Submitting TFA token', {
124 'authy_token': tfa_token,
125 'remember_2fa': 'true',
128 def _prefer_source(self, formats):
129 try:
130 source = next(f for f in formats if f['format_id'] == 'Source')
131 source['quality'] = 10
132 except StopIteration:
133 for f in formats:
134 if '/chunked/' in f['url']:
135 f.update({
136 'quality': 10,
137 'format_note': 'Source',
140 def _download_base_gql(self, video_id, ops, note, fatal=True):
141 headers = {
142 'Content-Type': 'text/plain;charset=UTF-8',
143 'Client-ID': self._CLIENT_ID,
145 gql_auth = self._get_cookies('https://gql.twitch.tv').get('auth-token')
146 if gql_auth:
147 headers['Authorization'] = 'OAuth ' + gql_auth.value
148 return self._download_json(
149 'https://gql.twitch.tv/gql', video_id, note,
150 data=json.dumps(ops).encode(),
151 headers=headers, fatal=fatal)
153 def _download_gql(self, video_id, ops, note, fatal=True):
154 for op in ops:
155 op['extensions'] = {
156 'persistedQuery': {
157 'version': 1,
158 'sha256Hash': self._OPERATION_HASHES[op['operationName']],
161 return self._download_base_gql(video_id, ops, note)
163 def _download_access_token(self, video_id, token_kind, param_name):
164 method = '%sPlaybackAccessToken' % token_kind
165 ops = {
166 'query': '''{
168 %s: "%s",
169 params: {
170 platform: "web",
171 playerBackend: "mediaplayer",
172 playerType: "site"
176 value
177 signature
179 }''' % (method, param_name, video_id),
181 return self._download_base_gql(
182 video_id, ops,
183 'Downloading %s access token GraphQL' % token_kind)['data'][method]
185 def _get_thumbnails(self, thumbnail):
186 return [{
187 'url': re.sub(r'\d+x\d+(\.\w+)($|(?=[?#]))', r'0x0\g<1>', thumbnail),
188 'preference': 1,
189 }, {
190 'url': thumbnail,
191 }] if thumbnail else None
193 def _extract_twitch_m3u8_formats(self, path, video_id, token, signature):
194 return self._extract_m3u8_formats(
195 f'{self._USHER_BASE}/{path}/{video_id}.m3u8', video_id, 'mp4', query={
196 'allow_source': 'true',
197 'allow_audio_only': 'true',
198 'allow_spectre': 'true',
199 'p': random.randint(1000000, 10000000),
200 'player': 'twitchweb',
201 'playlist_include_framerate': 'true',
202 'sig': signature,
203 'token': token,
207 class TwitchVodIE(TwitchBaseIE):
208 IE_NAME = 'twitch:vod'
209 _VALID_URL = r'''(?x)
210 https?://
212 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
213 player\.twitch\.tv/\?.*?\bvideo=v?|
214 www\.twitch\.tv/[^/]+/schedule\?vodID=
216 (?P<id>\d+)
219 _TESTS = [{
220 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
221 'info_dict': {
222 'id': 'v6528877',
223 'ext': 'mp4',
224 'title': 'LCK Summer Split - Week 6 Day 1',
225 'thumbnail': r're:^https?://.*\.jpg$',
226 'duration': 17208,
227 'timestamp': 1435131734,
228 'upload_date': '20150624',
229 'uploader': 'Riot Games',
230 'uploader_id': 'riotgames',
231 'view_count': int,
232 'start_time': 310,
233 'chapters': [
235 'start_time': 0,
236 'end_time': 17208,
237 'title': 'League of Legends'
240 'live_status': 'was_live',
242 'params': {
243 # m3u8 download
244 'skip_download': True,
246 }, {
247 # Untitled broadcast (title is None)
248 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
249 'info_dict': {
250 'id': 'v11230755',
251 'ext': 'mp4',
252 'title': 'Untitled Broadcast',
253 'thumbnail': r're:^https?://.*\.jpg$',
254 'duration': 1638,
255 'timestamp': 1439746708,
256 'upload_date': '20150816',
257 'uploader': 'BelkAO_o',
258 'uploader_id': 'belkao_o',
259 'view_count': int,
261 'params': {
262 # m3u8 download
263 'skip_download': True,
265 'skip': 'HTTP Error 404: Not Found',
266 }, {
267 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
268 'only_matching': True,
269 }, {
270 'url': 'https://www.twitch.tv/videos/6528877',
271 'only_matching': True,
272 }, {
273 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
274 'only_matching': True,
275 }, {
276 'url': 'https://www.twitch.tv/northernlion/video/291940395',
277 'only_matching': True,
278 }, {
279 'url': 'https://player.twitch.tv/?video=480452374',
280 'only_matching': True,
281 }, {
282 'url': 'https://www.twitch.tv/videos/635475444',
283 'info_dict': {
284 'id': 'v635475444',
285 'ext': 'mp4',
286 'title': 'Riot Games',
287 'duration': 11643,
288 'uploader': 'Riot Games',
289 'uploader_id': 'riotgames',
290 'timestamp': 1590770569,
291 'upload_date': '20200529',
292 'chapters': [
294 'start_time': 0,
295 'end_time': 573,
296 'title': 'League of Legends'
299 'start_time': 573,
300 'end_time': 3922,
301 'title': 'Legends of Runeterra'
304 'start_time': 3922,
305 'end_time': 11643,
306 'title': 'Art'
309 'live_status': 'was_live',
310 'thumbnail': r're:^https?://.*\.jpg$',
311 'view_count': int,
313 'params': {
314 'skip_download': True
316 }, {
317 'note': 'Storyboards',
318 'url': 'https://www.twitch.tv/videos/635475444',
319 'info_dict': {
320 'id': 'v635475444',
321 'format_id': 'sb0',
322 'ext': 'mhtml',
323 'title': 'Riot Games',
324 'duration': 11643,
325 'uploader': 'Riot Games',
326 'uploader_id': 'riotgames',
327 'timestamp': 1590770569,
328 'upload_date': '20200529',
329 'chapters': [
331 'start_time': 0,
332 'end_time': 573,
333 'title': 'League of Legends'
336 'start_time': 573,
337 'end_time': 3922,
338 'title': 'Legends of Runeterra'
341 'start_time': 3922,
342 'end_time': 11643,
343 'title': 'Art'
346 'live_status': 'was_live',
347 'thumbnail': r're:^https?://.*\.jpg$',
348 'view_count': int,
349 'columns': int,
350 'rows': int,
352 'params': {
353 'format': 'mhtml',
354 'skip_download': True
356 }, {
357 'note': 'VOD with single chapter',
358 'url': 'https://www.twitch.tv/videos/1536751224',
359 'info_dict': {
360 'id': 'v1536751224',
361 'ext': 'mp4',
362 'title': 'Porter Robinson Star Guardian Stream Tour with LilyPichu',
363 'duration': 8353,
364 'uploader': 'Riot Games',
365 'uploader_id': 'riotgames',
366 'timestamp': 1658267731,
367 'upload_date': '20220719',
368 'chapters': [
370 'start_time': 0,
371 'end_time': 8353,
372 'title': 'League of Legends'
375 'live_status': 'was_live',
376 'thumbnail': r're:^https?://.*\.jpg$',
377 'view_count': int,
379 'params': {
380 'skip_download': True
382 'expected_warnings': ['Unable to download JSON metadata: HTTP Error 403: Forbidden']
383 }, {
384 'url': 'https://www.twitch.tv/tangotek/schedule?vodID=1822395420',
385 'only_matching': True,
388 def _download_info(self, item_id):
389 data = self._download_gql(
390 item_id, [{
391 'operationName': 'VideoMetadata',
392 'variables': {
393 'channelLogin': '',
394 'videoID': item_id,
396 }, {
397 'operationName': 'VideoPlayer_ChapterSelectButtonVideo',
398 'variables': {
399 'includePrivate': False,
400 'videoID': item_id,
402 }, {
403 'operationName': 'VideoPlayer_VODSeekbarPreviewVideo',
404 'variables': {
405 'includePrivate': False,
406 'videoID': item_id,
409 'Downloading stream metadata GraphQL')
411 video = traverse_obj(data, (..., 'data', 'video'), get_all=False)
412 if video is None:
413 raise ExtractorError(f'Video {item_id} does not exist', expected=True)
415 video['moments'] = traverse_obj(data, (..., 'data', 'video', 'moments', 'edges', ..., 'node'))
416 video['storyboard'] = traverse_obj(
417 data, (..., 'data', 'video', 'seekPreviewsURL', {url_or_none}), get_all=False)
419 return video
421 def _extract_info(self, info):
422 status = info.get('status')
423 if status == 'recording':
424 is_live = True
425 elif status == 'recorded':
426 is_live = False
427 else:
428 is_live = None
429 _QUALITIES = ('small', 'medium', 'large')
430 quality_key = qualities(_QUALITIES)
431 thumbnails = []
432 preview = info.get('preview')
433 if isinstance(preview, dict):
434 for thumbnail_id, thumbnail_url in preview.items():
435 thumbnail_url = url_or_none(thumbnail_url)
436 if not thumbnail_url:
437 continue
438 if thumbnail_id not in _QUALITIES:
439 continue
440 thumbnails.append({
441 'url': thumbnail_url,
442 'preference': quality_key(thumbnail_id),
444 return {
445 'id': info['_id'],
446 'title': info.get('title') or 'Untitled Broadcast',
447 'description': info.get('description'),
448 'duration': int_or_none(info.get('length')),
449 'thumbnails': thumbnails,
450 'uploader': info.get('channel', {}).get('display_name'),
451 'uploader_id': info.get('channel', {}).get('name'),
452 'timestamp': parse_iso8601(info.get('recorded_at')),
453 'view_count': int_or_none(info.get('views')),
454 'is_live': is_live,
455 'was_live': True,
458 def _extract_chapters(self, info, item_id):
459 if not info.get('moments'):
460 game = traverse_obj(info, ('game', 'displayName'))
461 if game:
462 yield {'title': game}
463 return
465 for moment in info['moments']:
466 start_time = int_or_none(moment.get('positionMilliseconds'), 1000)
467 duration = int_or_none(moment.get('durationMilliseconds'), 1000)
468 name = str_or_none(moment.get('description'))
470 if start_time is None or duration is None:
471 self.report_warning(f'Important chapter information missing for chapter {name}', item_id)
472 continue
473 yield {
474 'start_time': start_time,
475 'end_time': start_time + duration,
476 'title': name,
479 def _extract_info_gql(self, info, item_id):
480 vod_id = info.get('id') or item_id
481 # id backward compatibility for download archives
482 if vod_id[0] != 'v':
483 vod_id = 'v%s' % vod_id
484 thumbnail = url_or_none(info.get('previewThumbnailURL'))
485 is_live = None
486 if thumbnail:
487 if re.findall(r'/404_processing_[^.?#]+\.png', thumbnail):
488 is_live, thumbnail = True, None
489 else:
490 is_live = False
492 return {
493 'id': vod_id,
494 'title': info.get('title') or 'Untitled Broadcast',
495 'description': info.get('description'),
496 'duration': int_or_none(info.get('lengthSeconds')),
497 'thumbnails': self._get_thumbnails(thumbnail),
498 'uploader': try_get(info, lambda x: x['owner']['displayName'], compat_str),
499 'uploader_id': try_get(info, lambda x: x['owner']['login'], compat_str),
500 'timestamp': unified_timestamp(info.get('publishedAt')),
501 'view_count': int_or_none(info.get('viewCount')),
502 'chapters': list(self._extract_chapters(info, item_id)),
503 'is_live': is_live,
504 'was_live': True,
507 def _extract_storyboard(self, item_id, storyboard_json_url, duration):
508 if not duration or not storyboard_json_url:
509 return
510 spec = self._download_json(storyboard_json_url, item_id, 'Downloading storyboard metadata JSON', fatal=False) or []
511 # sort from highest quality to lowest
512 # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
513 spec.sort(key=lambda x: int_or_none(x.get('width')) or 0, reverse=True)
514 base = base_url(storyboard_json_url)
515 for i, s in enumerate(spec):
516 count = int_or_none(s.get('count'))
517 images = s.get('images')
518 if not (images and count):
519 continue
520 fragment_duration = duration / len(images)
521 yield {
522 'format_id': f'sb{i}',
523 'format_note': 'storyboard',
524 'ext': 'mhtml',
525 'protocol': 'mhtml',
526 'acodec': 'none',
527 'vcodec': 'none',
528 'url': urljoin(base, images[0]),
529 'width': int_or_none(s.get('width')),
530 'height': int_or_none(s.get('height')),
531 'fps': count / duration,
532 'rows': int_or_none(s.get('rows')),
533 'columns': int_or_none(s.get('cols')),
534 'fragments': [{
535 'url': urljoin(base, path),
536 'duration': fragment_duration,
537 } for path in images],
540 def _real_extract(self, url):
541 vod_id = self._match_id(url)
543 video = self._download_info(vod_id)
544 info = self._extract_info_gql(video, vod_id)
545 access_token = self._download_access_token(vod_id, 'video', 'id')
547 formats = self._extract_twitch_m3u8_formats(
548 'vod', vod_id, access_token['value'], access_token['signature'])
549 formats.extend(self._extract_storyboard(vod_id, video.get('storyboard'), info.get('duration')))
551 self._prefer_source(formats)
552 info['formats'] = formats
554 parsed_url = compat_urllib_parse_urlparse(url)
555 query = compat_parse_qs(parsed_url.query)
556 if 't' in query:
557 info['start_time'] = parse_duration(query['t'][0])
559 if info.get('timestamp') is not None:
560 info['subtitles'] = {
561 'rechat': [{
562 'url': update_url_query(
563 'https://api.twitch.tv/v5/videos/%s/comments' % vod_id, {
564 'client_id': self._CLIENT_ID,
566 'ext': 'json',
570 return info
573 def _make_video_result(node):
574 assert isinstance(node, dict)
575 video_id = node.get('id')
576 if not video_id:
577 return
578 return {
579 '_type': 'url_transparent',
580 'ie_key': TwitchVodIE.ie_key(),
581 'id': 'v' + video_id,
582 'url': 'https://www.twitch.tv/videos/%s' % video_id,
583 'title': node.get('title'),
584 'thumbnail': node.get('previewThumbnailURL'),
585 'duration': float_or_none(node.get('lengthSeconds')),
586 'view_count': int_or_none(node.get('viewCount')),
590 class TwitchCollectionIE(TwitchBaseIE):
591 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
593 _TESTS = [{
594 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
595 'info_dict': {
596 'id': 'wlDCoH0zEBZZbQ',
597 'title': 'Overthrow Nook, capitalism for children',
599 'playlist_mincount': 13,
602 _OPERATION_NAME = 'CollectionSideBar'
604 def _real_extract(self, url):
605 collection_id = self._match_id(url)
606 collection = self._download_gql(
607 collection_id, [{
608 'operationName': self._OPERATION_NAME,
609 'variables': {'collectionID': collection_id},
611 'Downloading collection GraphQL')[0]['data']['collection']
612 title = collection.get('title')
613 entries = []
614 for edge in collection['items']['edges']:
615 if not isinstance(edge, dict):
616 continue
617 node = edge.get('node')
618 if not isinstance(node, dict):
619 continue
620 video = _make_video_result(node)
621 if video:
622 entries.append(video)
623 return self.playlist_result(
624 entries, playlist_id=collection_id, playlist_title=title)
627 class TwitchPlaylistBaseIE(TwitchBaseIE):
628 _PAGE_LIMIT = 100
630 def _entries(self, channel_name, *args):
631 cursor = None
632 variables_common = self._make_variables(channel_name, *args)
633 entries_key = '%ss' % self._ENTRY_KIND
634 for page_num in itertools.count(1):
635 variables = variables_common.copy()
636 variables['limit'] = self._PAGE_LIMIT
637 if cursor:
638 variables['cursor'] = cursor
639 page = self._download_gql(
640 channel_name, [{
641 'operationName': self._OPERATION_NAME,
642 'variables': variables,
644 'Downloading %ss GraphQL page %s' % (self._NODE_KIND, page_num),
645 fatal=False)
646 if not page:
647 break
648 edges = try_get(
649 page, lambda x: x[0]['data']['user'][entries_key]['edges'], list)
650 if not edges:
651 break
652 for edge in edges:
653 if not isinstance(edge, dict):
654 continue
655 if edge.get('__typename') != self._EDGE_KIND:
656 continue
657 node = edge.get('node')
658 if not isinstance(node, dict):
659 continue
660 if node.get('__typename') != self._NODE_KIND:
661 continue
662 entry = self._extract_entry(node)
663 if entry:
664 cursor = edge.get('cursor')
665 yield entry
666 if not cursor or not isinstance(cursor, compat_str):
667 break
670 class TwitchVideosIE(TwitchPlaylistBaseIE):
671 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
673 _TESTS = [{
674 # All Videos sorted by Date
675 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
676 'info_dict': {
677 'id': 'spamfish',
678 'title': 'spamfish - All Videos sorted by Date',
680 'playlist_mincount': 924,
681 }, {
682 # All Videos sorted by Popular
683 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
684 'info_dict': {
685 'id': 'spamfish',
686 'title': 'spamfish - All Videos sorted by Popular',
688 'playlist_mincount': 931,
689 }, {
690 # Past Broadcasts sorted by Date
691 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
692 'info_dict': {
693 'id': 'spamfish',
694 'title': 'spamfish - Past Broadcasts sorted by Date',
696 'playlist_mincount': 27,
697 }, {
698 # Highlights sorted by Date
699 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
700 'info_dict': {
701 'id': 'spamfish',
702 'title': 'spamfish - Highlights sorted by Date',
704 'playlist_mincount': 901,
705 }, {
706 # Uploads sorted by Date
707 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
708 'info_dict': {
709 'id': 'esl_csgo',
710 'title': 'esl_csgo - Uploads sorted by Date',
712 'playlist_mincount': 5,
713 }, {
714 # Past Premieres sorted by Date
715 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
716 'info_dict': {
717 'id': 'spamfish',
718 'title': 'spamfish - Past Premieres sorted by Date',
720 'playlist_mincount': 1,
721 }, {
722 'url': 'https://www.twitch.tv/spamfish/videos/all',
723 'only_matching': True,
724 }, {
725 'url': 'https://m.twitch.tv/spamfish/videos/all',
726 'only_matching': True,
727 }, {
728 'url': 'https://www.twitch.tv/spamfish/videos',
729 'only_matching': True,
732 Broadcast = collections.namedtuple('Broadcast', ['type', 'label'])
734 _DEFAULT_BROADCAST = Broadcast(None, 'All Videos')
735 _BROADCASTS = {
736 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
737 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
738 'uploads': Broadcast('UPLOAD', 'Uploads'),
739 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
740 'all': _DEFAULT_BROADCAST,
743 _DEFAULT_SORTED_BY = 'Date'
744 _SORTED_BY = {
745 'time': _DEFAULT_SORTED_BY,
746 'views': 'Popular',
749 _OPERATION_NAME = 'FilterableVideoTower_Videos'
750 _ENTRY_KIND = 'video'
751 _EDGE_KIND = 'VideoEdge'
752 _NODE_KIND = 'Video'
754 @classmethod
755 def suitable(cls, url):
756 return (False
757 if any(ie.suitable(url) for ie in (
758 TwitchVideosClipsIE,
759 TwitchVideosCollectionsIE))
760 else super(TwitchVideosIE, cls).suitable(url))
762 @staticmethod
763 def _make_variables(channel_name, broadcast_type, sort):
764 return {
765 'channelOwnerLogin': channel_name,
766 'broadcastType': broadcast_type,
767 'videoSort': sort.upper(),
770 @staticmethod
771 def _extract_entry(node):
772 return _make_video_result(node)
774 def _real_extract(self, url):
775 channel_name = self._match_id(url)
776 qs = parse_qs(url)
777 filter = qs.get('filter', ['all'])[0]
778 sort = qs.get('sort', ['time'])[0]
779 broadcast = self._BROADCASTS.get(filter, self._DEFAULT_BROADCAST)
780 return self.playlist_result(
781 self._entries(channel_name, broadcast.type, sort),
782 playlist_id=channel_name,
783 playlist_title='%s - %s sorted by %s'
784 % (channel_name, broadcast.label,
785 self._SORTED_BY.get(sort, self._DEFAULT_SORTED_BY)))
788 class TwitchVideosClipsIE(TwitchPlaylistBaseIE):
789 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
791 _TESTS = [{
792 # Clips
793 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
794 'info_dict': {
795 'id': 'vanillatv',
796 'title': 'vanillatv - Clips Top All',
798 'playlist_mincount': 1,
799 }, {
800 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
801 'only_matching': True,
804 Clip = collections.namedtuple('Clip', ['filter', 'label'])
806 _DEFAULT_CLIP = Clip('LAST_WEEK', 'Top 7D')
807 _RANGE = {
808 '24hr': Clip('LAST_DAY', 'Top 24H'),
809 '7d': _DEFAULT_CLIP,
810 '30d': Clip('LAST_MONTH', 'Top 30D'),
811 'all': Clip('ALL_TIME', 'Top All'),
814 # NB: values other than 20 result in skipped videos
815 _PAGE_LIMIT = 20
817 _OPERATION_NAME = 'ClipsCards__User'
818 _ENTRY_KIND = 'clip'
819 _EDGE_KIND = 'ClipEdge'
820 _NODE_KIND = 'Clip'
822 @staticmethod
823 def _make_variables(channel_name, filter):
824 return {
825 'login': channel_name,
826 'criteria': {
827 'filter': filter,
831 @staticmethod
832 def _extract_entry(node):
833 assert isinstance(node, dict)
834 clip_url = url_or_none(node.get('url'))
835 if not clip_url:
836 return
837 return {
838 '_type': 'url_transparent',
839 'ie_key': TwitchClipsIE.ie_key(),
840 'id': node.get('id'),
841 'url': clip_url,
842 'title': node.get('title'),
843 'thumbnail': node.get('thumbnailURL'),
844 'duration': float_or_none(node.get('durationSeconds')),
845 'timestamp': unified_timestamp(node.get('createdAt')),
846 'view_count': int_or_none(node.get('viewCount')),
847 'language': node.get('language'),
850 def _real_extract(self, url):
851 channel_name = self._match_id(url)
852 qs = parse_qs(url)
853 range = qs.get('range', ['7d'])[0]
854 clip = self._RANGE.get(range, self._DEFAULT_CLIP)
855 return self.playlist_result(
856 self._entries(channel_name, clip.filter),
857 playlist_id=channel_name,
858 playlist_title='%s - Clips %s' % (channel_name, clip.label))
861 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE):
862 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
864 _TESTS = [{
865 # Collections
866 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
867 'info_dict': {
868 'id': 'spamfish',
869 'title': 'spamfish - Collections',
871 'playlist_mincount': 3,
872 }, {
873 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
874 'info_dict': {
875 'id': 'monstercat',
876 'title': 'monstercat - Collections',
878 'playlist_mincount': 13,
881 _OPERATION_NAME = 'ChannelCollectionsContent'
882 _ENTRY_KIND = 'collection'
883 _EDGE_KIND = 'CollectionsItemEdge'
884 _NODE_KIND = 'Collection'
886 @staticmethod
887 def _make_variables(channel_name):
888 return {
889 'ownerLogin': channel_name,
892 @staticmethod
893 def _extract_entry(node):
894 assert isinstance(node, dict)
895 collection_id = node.get('id')
896 if not collection_id:
897 return
898 return {
899 '_type': 'url_transparent',
900 'ie_key': TwitchCollectionIE.ie_key(),
901 'id': collection_id,
902 'url': 'https://www.twitch.tv/collections/%s' % collection_id,
903 'title': node.get('title'),
904 'thumbnail': node.get('thumbnailURL'),
905 'duration': float_or_none(node.get('lengthSeconds')),
906 'timestamp': unified_timestamp(node.get('updatedAt')),
907 'view_count': int_or_none(node.get('viewCount')),
910 def _real_extract(self, url):
911 channel_name = self._match_id(url)
912 return self.playlist_result(
913 self._entries(channel_name), playlist_id=channel_name,
914 playlist_title='%s - Collections' % channel_name)
917 class TwitchStreamIE(TwitchBaseIE):
918 IE_NAME = 'twitch:stream'
919 _VALID_URL = r'''(?x)
920 https?://
922 (?:(?:www|go|m)\.)?twitch\.tv/|
923 player\.twitch\.tv/\?.*?\bchannel=
925 (?P<id>[^/#?]+)
928 _TESTS = [{
929 'url': 'http://www.twitch.tv/shroomztv',
930 'info_dict': {
931 'id': '12772022048',
932 'display_id': 'shroomztv',
933 'ext': 'mp4',
934 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
935 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
936 'is_live': True,
937 'timestamp': 1421928037,
938 'upload_date': '20150122',
939 'uploader': 'ShroomzTV',
940 'uploader_id': 'shroomztv',
941 'view_count': int,
943 'params': {
944 # m3u8 download
945 'skip_download': True,
947 'skip': 'User does not exist',
948 }, {
949 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
950 'only_matching': True,
951 }, {
952 'url': 'https://player.twitch.tv/?channel=lotsofs',
953 'only_matching': True,
954 }, {
955 'url': 'https://go.twitch.tv/food',
956 'only_matching': True,
957 }, {
958 'url': 'https://m.twitch.tv/food',
959 'only_matching': True,
960 }, {
961 'url': 'https://www.twitch.tv/monstercat',
962 'info_dict': {
963 'id': '40500071752',
964 'display_id': 'monstercat',
965 'title': 're:Monstercat',
966 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
967 'is_live': True,
968 'timestamp': 1677107190,
969 'upload_date': '20230222',
970 'uploader': 'Monstercat',
971 'uploader_id': 'monstercat',
972 'live_status': 'is_live',
973 'thumbnail': 're:https://.*.jpg',
974 'ext': 'mp4',
976 'params': {
977 'skip_download': 'Livestream',
981 @classmethod
982 def suitable(cls, url):
983 return (False
984 if any(ie.suitable(url) for ie in (
985 TwitchVodIE,
986 TwitchCollectionIE,
987 TwitchVideosIE,
988 TwitchVideosClipsIE,
989 TwitchVideosCollectionsIE,
990 TwitchClipsIE))
991 else super(TwitchStreamIE, cls).suitable(url))
993 def _real_extract(self, url):
994 channel_name = self._match_id(url).lower()
996 gql = self._download_gql(
997 channel_name, [{
998 'operationName': 'StreamMetadata',
999 'variables': {'channelLogin': channel_name},
1000 }, {
1001 'operationName': 'ComscoreStreamingQuery',
1002 'variables': {
1003 'channel': channel_name,
1004 'clipSlug': '',
1005 'isClip': False,
1006 'isLive': True,
1007 'isVodOrCollection': False,
1008 'vodID': '',
1010 }, {
1011 'operationName': 'VideoPreviewOverlay',
1012 'variables': {'login': channel_name},
1014 'Downloading stream GraphQL')
1016 user = gql[0]['data']['user']
1018 if not user:
1019 raise ExtractorError(
1020 '%s does not exist' % channel_name, expected=True)
1022 stream = user['stream']
1024 if not stream:
1025 raise UserNotLive(video_id=channel_name)
1027 access_token = self._download_access_token(
1028 channel_name, 'stream', 'channelName')
1030 stream_id = stream.get('id') or channel_name
1031 formats = self._extract_twitch_m3u8_formats(
1032 'api/channel/hls', channel_name, access_token['value'], access_token['signature'])
1033 self._prefer_source(formats)
1035 view_count = stream.get('viewers')
1036 timestamp = unified_timestamp(stream.get('createdAt'))
1038 sq_user = try_get(gql, lambda x: x[1]['data']['user'], dict) or {}
1039 uploader = sq_user.get('displayName')
1040 description = try_get(
1041 sq_user, lambda x: x['broadcastSettings']['title'], compat_str)
1043 thumbnail = url_or_none(try_get(
1044 gql, lambda x: x[2]['data']['user']['stream']['previewImageURL'],
1045 compat_str))
1047 title = uploader or channel_name
1048 stream_type = stream.get('type')
1049 if stream_type in ['rerun', 'live']:
1050 title += ' (%s)' % stream_type
1052 return {
1053 'id': stream_id,
1054 'display_id': channel_name,
1055 'title': title,
1056 'description': description,
1057 'thumbnails': self._get_thumbnails(thumbnail),
1058 'uploader': uploader,
1059 'uploader_id': channel_name,
1060 'timestamp': timestamp,
1061 'view_count': view_count,
1062 'formats': formats,
1063 'is_live': stream_type == 'live',
1067 class TwitchClipsIE(TwitchBaseIE):
1068 IE_NAME = 'twitch:clips'
1069 _VALID_URL = r'''(?x)
1070 https?://
1072 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
1073 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/)?clip/
1075 (?P<id>[^/?#&]+)
1078 _TESTS = [{
1079 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
1080 'md5': '761769e1eafce0ffebfb4089cb3847cd',
1081 'info_dict': {
1082 'id': '42850523',
1083 'display_id': 'FaintLightGullWholeWheat',
1084 'ext': 'mp4',
1085 'title': 'EA Play 2016 Live from the Novo Theatre',
1086 'thumbnail': r're:^https?://.*\.jpg',
1087 'timestamp': 1465767393,
1088 'upload_date': '20160612',
1089 'creator': 'EA',
1090 'uploader': 'stereotype_',
1091 'uploader_id': '43566419',
1093 }, {
1094 # multiple formats
1095 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
1096 'only_matching': True,
1097 }, {
1098 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
1099 'only_matching': True,
1100 }, {
1101 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
1102 'only_matching': True,
1103 }, {
1104 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1105 'only_matching': True,
1106 }, {
1107 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1108 'only_matching': True,
1109 }, {
1110 'url': 'https://m.twitch.tv/clip/FaintLightGullWholeWheat',
1111 'only_matching': True,
1114 def _real_extract(self, url):
1115 video_id = self._match_id(url)
1117 clip = self._download_gql(
1118 video_id, [{
1119 'operationName': 'VideoAccessToken_Clip',
1120 'variables': {
1121 'slug': video_id,
1124 'Downloading clip access token GraphQL')[0]['data']['clip']
1126 if not clip:
1127 raise ExtractorError(
1128 'This clip is no longer available', expected=True)
1130 access_query = {
1131 'sig': clip['playbackAccessToken']['signature'],
1132 'token': clip['playbackAccessToken']['value'],
1135 data = self._download_base_gql(
1136 video_id, {
1137 'query': '''{
1138 clip(slug: "%s") {
1139 broadcaster {
1140 displayName
1142 createdAt
1143 curator {
1144 displayName
1147 durationSeconds
1149 tiny: thumbnailURL(width: 86, height: 45)
1150 small: thumbnailURL(width: 260, height: 147)
1151 medium: thumbnailURL(width: 480, height: 272)
1152 title
1153 videoQualities {
1154 frameRate
1155 quality
1156 sourceURL
1158 viewCount
1160 }''' % video_id}, 'Downloading clip GraphQL', fatal=False)
1162 if data:
1163 clip = try_get(data, lambda x: x['data']['clip'], dict) or clip
1165 formats = []
1166 for option in clip.get('videoQualities', []):
1167 if not isinstance(option, dict):
1168 continue
1169 source = url_or_none(option.get('sourceURL'))
1170 if not source:
1171 continue
1172 formats.append({
1173 'url': update_url_query(source, access_query),
1174 'format_id': option.get('quality'),
1175 'height': int_or_none(option.get('quality')),
1176 'fps': int_or_none(option.get('frameRate')),
1179 thumbnails = []
1180 for thumbnail_id in ('tiny', 'small', 'medium'):
1181 thumbnail_url = clip.get(thumbnail_id)
1182 if not thumbnail_url:
1183 continue
1184 thumb = {
1185 'id': thumbnail_id,
1186 'url': thumbnail_url,
1188 mobj = re.search(r'-(\d+)x(\d+)\.', thumbnail_url)
1189 if mobj:
1190 thumb.update({
1191 'height': int(mobj.group(2)),
1192 'width': int(mobj.group(1)),
1194 thumbnails.append(thumb)
1196 old_id = self._search_regex(r'%7C(\d+)(?:-\d+)?.mp4', formats[-1]['url'], 'old id', default=None)
1198 return {
1199 'id': clip.get('id') or video_id,
1200 '_old_archive_ids': [make_archive_id(self, old_id)] if old_id else None,
1201 'display_id': video_id,
1202 'title': clip.get('title'),
1203 'formats': formats,
1204 'duration': int_or_none(clip.get('durationSeconds')),
1205 'view_count': int_or_none(clip.get('viewCount')),
1206 'timestamp': unified_timestamp(clip.get('createdAt')),
1207 'thumbnails': thumbnails,
1208 'creator': try_get(clip, lambda x: x['broadcaster']['displayName'], compat_str),
1209 'uploader': try_get(clip, lambda x: x['curator']['displayName'], compat_str),
1210 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),