7 from .common
import InfoExtractor
11 compat_urllib_parse_urlencode
,
12 compat_urllib_parse_urlparse
,
37 class TwitchBaseIE(InfoExtractor
):
38 _VALID_URL_BASE
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv'
40 _API_BASE
= 'https://api.twitch.tv'
41 _USHER_BASE
= 'https://usher.ttvnw.net'
42 _LOGIN_FORM_URL
= 'https://www.twitch.tv/login'
43 _LOGIN_POST_URL
= 'https://passport.twitch.tv/login'
44 _CLIENT_ID
= 'kimne78kx3ncx6brgo4mv6wki5h1ko'
45 _NETRC_MACHINE
= 'twitch'
48 'CollectionSideBar': '27111f1b382effad0b6def325caef1909c733fe6a4fbabf54f8d491ef2cf2f14',
49 'FilterableVideoTower_Videos': 'a937f1d22e269e39a03b509f65a7490f9fc247d7f83d6ac1421523e3b68042cb',
50 'ClipsCards__User': 'b73ad2bfaecfd30a9e6c28fada15bd97032c83ec77a0440766a56fe0bd632777',
51 'ChannelCollectionsContent': '447aec6a0cc1e8d0a8d7732d47eb0762c336a2294fdb009e9c9d854e49d484b9',
52 'StreamMetadata': 'a647c2a13599e5991e175155f798ca7f1ecddde73f7f341f39009c14dbf59962',
53 'ComscoreStreamingQuery': 'e1edae8122517d013405f237ffcc124515dc6ded82480a88daef69c83b53ac01',
54 'VideoAccessToken_Clip': '36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11',
55 'VideoPreviewOverlay': '3006e77e51b128d838fa4e835723ca4dc9a05c5efd4466c1085215c6e437e65c',
56 'VideoMetadata': '49b5b8f268cdeb259d75b58dcb0c1a748e3b575003448a2333dc5cdafd49adad',
57 'VideoPlayer_ChapterSelectButtonVideo': '8d2793384aac3773beab5e59bd5d6f585aedb923d292800119e03d40cd0f9b41',
58 'VideoPlayer_VODSeekbarPreviewVideo': '07e99e4d56c5a7c67117a154777b0baf85a5ffefa393b213f4bc712ccaf85dd6',
61 def _perform_login(self
, username
, password
):
64 'Unable to login. Twitch said: %s' % message
, expected
=True)
66 def login_step(page
, urlh
, note
, data
):
67 form
= self
._hidden
_inputs
(page
)
70 page_url
= urlh
.geturl()
71 post_url
= self
._search
_regex
(
72 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page,
73 'post url
', default=self._LOGIN_POST_URL, group='url
')
74 post_url = urljoin(page_url, post_url)
78 'Origin
': 'https
://www
.twitch
.tv
',
79 'Content
-Type
': 'text
/plain
;charset
=UTF
-8',
82 response = self._download_json(
83 post_url, None, note, data=json.dumps(form).encode(),
84 headers=headers, expected_status=400)
85 error = dict_get(response, ('error
', 'error_description
', 'error_code
'))
89 if 'Authenticated successfully
' in response.get('message
', ''):
92 redirect_url = urljoin(
94 response.get('redirect
') or response['redirect_path
'])
95 return self._download_webpage_handle(
96 redirect_url, None, 'Downloading login redirect page
',
99 login_page, handle = self._download_webpage_handle(
100 self._LOGIN_FORM_URL, None, 'Downloading login page
')
102 # Some TOR nodes and public proxies are blocked completely
103 if 'blacklist_message
' in login_page:
104 fail(clean_html(login_page))
106 redirect_page, handle = login_step(
107 login_page, handle, 'Logging
in', {
108 'username
': username,
109 'password
': password,
110 'client_id
': self._CLIENT_ID,
114 if not redirect_page:
117 if re.search(r'(?i
)<form
[^
>]+id="two-factor-submit"', redirect_page) is not None:
118 # TODO: Add mechanism to request an SMS or phone call
119 tfa_token = self._get_tfa_info('two
-factor authentication token
')
120 login_step(redirect_page, handle, 'Submitting TFA token
', {
121 'authy_token
': tfa_token,
122 'remember_2fa
': 'true
',
125 def _prefer_source(self, formats):
127 source = next(f for f in formats if f['format_id
'] == 'Source
')
128 source['quality
'] = 10
129 except StopIteration:
131 if '/chunked
/' in f['url
']:
134 'format_note
': 'Source
',
137 def _download_base_gql(self, video_id, ops, note, fatal=True):
139 'Content
-Type
': 'text
/plain
;charset
=UTF
-8',
140 'Client
-ID
': self._CLIENT_ID,
142 gql_auth = self._get_cookies('https
://gql
.twitch
.tv
').get('auth
-token
')
144 headers['Authorization
'] = 'OAuth
' + gql_auth.value
145 return self._download_json(
146 'https
://gql
.twitch
.tv
/gql
', video_id, note,
147 data=json.dumps(ops).encode(),
148 headers=headers, fatal=fatal)
150 def _download_gql(self, video_id, ops, note, fatal=True):
155 'sha256Hash
': self._OPERATION_HASHES[op['operationName
']],
158 return self._download_base_gql(video_id, ops, note)
160 def _download_access_token(self, video_id, token_kind, param_name):
161 method = '%sPlaybackAccessToken
' % token_kind
168 playerBackend: "mediaplayer",
176 }''' % (method, param_name, video_id),
178 return self._download_base_gql(
180 'Downloading
%s access token GraphQL
' % token_kind)['data
'][method]
183 class TwitchVodIE(TwitchBaseIE):
184 IE_NAME = 'twitch
:vod
'
185 _VALID_URL = r'''(?x)
188 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
189 player\.twitch\.tv/\?.*?\bvideo=v?
195 'url
': 'http
://www
.twitch
.tv
/riotgames
/v
/6528877?t
=5m10s
',
199 'title
': 'LCK Summer Split
- Week
6 Day
1',
200 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
202 'timestamp
': 1435131734,
203 'upload_date
': '20150624',
204 'uploader
': 'Riot Games
',
205 'uploader_id
': 'riotgames
',
212 'title
': 'League of Legends
'
215 'live_status
': 'was_live
',
219 'skip_download
': True,
222 # Untitled broadcast (title is None)
223 'url
': 'http
://www
.twitch
.tv
/belkao_o
/v
/11230755',
227 'title
': 'Untitled Broadcast
',
228 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
230 'timestamp
': 1439746708,
231 'upload_date
': '20150816',
232 'uploader
': 'BelkAO_o
',
233 'uploader_id
': 'belkao_o
',
238 'skip_download
': True,
240 'skip
': 'HTTP Error
404: Not Found
',
242 'url
': 'http
://player
.twitch
.tv
/?t
=5m10s
&video
=v6528877
',
243 'only_matching
': True,
245 'url
': 'https
://www
.twitch
.tv
/videos
/6528877',
246 'only_matching
': True,
248 'url
': 'https
://m
.twitch
.tv
/beagsandjam
/v
/247478721',
249 'only_matching
': True,
251 'url
': 'https
://www
.twitch
.tv
/northernlion
/video
/291940395',
252 'only_matching
': True,
254 'url
': 'https
://player
.twitch
.tv
/?video
=480452374',
255 'only_matching
': True,
257 'url
': 'https
://www
.twitch
.tv
/videos
/635475444',
261 'title
': 'Riot Games
',
263 'uploader
': 'Riot Games
',
264 'uploader_id
': 'riotgames
',
265 'timestamp
': 1590770569,
266 'upload_date
': '20200529',
271 'title
': 'League of Legends
'
276 'title
': 'Legends of Runeterra
'
284 'live_status
': 'was_live
',
285 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
289 'skip_download
': True
292 'note
': 'Storyboards
',
293 'url
': 'https
://www
.twitch
.tv
/videos
/635475444',
298 'title
': 'Riot Games
',
300 'uploader
': 'Riot Games
',
301 'uploader_id
': 'riotgames
',
302 'timestamp
': 1590770569,
303 'upload_date
': '20200529',
308 'title
': 'League of Legends
'
313 'title
': 'Legends of Runeterra
'
321 'live_status
': 'was_live
',
322 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
329 'skip_download
': True
332 'note
': 'VOD
with single chapter
',
333 'url
': 'https
://www
.twitch
.tv
/videos
/1536751224',
337 'title
': 'Porter Robinson Star Guardian Stream Tour
with LilyPichu
',
339 'uploader
': 'Riot Games
',
340 'uploader_id
': 'riotgames
',
341 'timestamp
': 1658267731,
342 'upload_date
': '20220719',
347 'title
': 'League of Legends
'
350 'live_status
': 'was_live
',
351 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
355 'skip_download
': True
357 'expected_warnings
': ['Unable to download JSON metadata
: HTTP Error
403: Forbidden
']
360 def _download_info(self, item_id):
361 data = self._download_gql(
363 'operationName
': 'VideoMetadata
',
369 'operationName
': 'VideoPlayer_ChapterSelectButtonVideo
',
371 'includePrivate
': False,
375 'operationName
': 'VideoPlayer_VODSeekbarPreviewVideo
',
377 'includePrivate
': False,
381 'Downloading stream metadata GraphQL
')
383 video = traverse_obj(data, (..., 'data
', 'video
'), get_all=False)
385 raise ExtractorError(f'Video {item_id} does
not exist
', expected=True)
387 video['moments
'] = traverse_obj(data, (..., 'data
', 'video
', 'moments
', 'edges
', ..., 'node
'))
388 video['storyboard
'] = traverse_obj(
389 data, (..., 'data
', 'video
', 'seekPreviewsURL
', {url_or_none}), get_all=False)
393 def _extract_info(self, info):
394 status = info.get('status
')
395 if status == 'recording
':
397 elif status == 'recorded
':
401 _QUALITIES = ('small
', 'medium
', 'large
')
402 quality_key = qualities(_QUALITIES)
404 preview = info.get('preview
')
405 if isinstance(preview, dict):
406 for thumbnail_id, thumbnail_url in preview.items():
407 thumbnail_url = url_or_none(thumbnail_url)
408 if not thumbnail_url:
410 if thumbnail_id not in _QUALITIES:
413 'url
': thumbnail_url,
414 'preference
': quality_key(thumbnail_id),
418 'title
': info.get('title
') or 'Untitled Broadcast
',
419 'description
': info.get('description
'),
420 'duration
': int_or_none(info.get('length
')),
421 'thumbnails
': thumbnails,
422 'uploader
': info.get('channel
', {}).get('display_name
'),
423 'uploader_id
': info.get('channel
', {}).get('name
'),
424 'timestamp
': parse_iso8601(info.get('recorded_at
')),
425 'view_count
': int_or_none(info.get('views
')),
430 def _extract_chapters(self, info, item_id):
431 if not info.get('moments
'):
432 game = traverse_obj(info, ('game
', 'displayName
'))
434 yield {'title': game}
437 for moment in info['moments
']:
438 start_time = int_or_none(moment.get('positionMilliseconds
'), 1000)
439 duration = int_or_none(moment.get('durationMilliseconds
'), 1000)
440 name = str_or_none(moment.get('description
'))
442 if start_time is None or duration is None:
443 self.report_warning(f'Important chapter information missing
for chapter {name}
', item_id)
446 'start_time
': start_time,
447 'end_time
': start_time + duration,
451 def _extract_info_gql(self, info, item_id):
452 vod_id = info.get('id') or item_id
453 # id backward compatibility for download archives
455 vod_id = 'v
%s' % vod_id
456 thumbnail = url_or_none(info.get('previewThumbnailURL
'))
459 if re.findall(r'/404_processing
_[^
.?
#]+\.png', thumbnail):
460 is_live
, thumbnail
= True, None
463 for p
in ('width', 'height'):
464 thumbnail
= thumbnail
.replace('{%s}' % p
, '0')
468 'title': info
.get('title') or 'Untitled Broadcast',
469 'description': info
.get('description'),
470 'duration': int_or_none(info
.get('lengthSeconds')),
471 'thumbnail': thumbnail
,
472 'uploader': try_get(info
, lambda x
: x
['owner']['displayName'], compat_str
),
473 'uploader_id': try_get(info
, lambda x
: x
['owner']['login'], compat_str
),
474 'timestamp': unified_timestamp(info
.get('publishedAt')),
475 'view_count': int_or_none(info
.get('viewCount')),
476 'chapters': list(self
._extract
_chapters
(info
, item_id
)),
481 def _extract_storyboard(self
, item_id
, storyboard_json_url
, duration
):
482 if not duration
or not storyboard_json_url
:
484 spec
= self
._download
_json
(storyboard_json_url
, item_id
, 'Downloading storyboard metadata JSON', fatal
=False) or []
485 # sort from highest quality to lowest
486 # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
487 spec
.sort(key
=lambda x
: int_or_none(x
.get('width')) or 0, reverse
=True)
488 base
= base_url(storyboard_json_url
)
489 for i
, s
in enumerate(spec
):
490 count
= int_or_none(s
.get('count'))
491 images
= s
.get('images')
492 if not (images
and count
):
494 fragment_duration
= duration
/ len(images
)
496 'format_id': f
'sb{i}',
497 'format_note': 'storyboard',
502 'url': urljoin(base
, images
[0]),
503 'width': int_or_none(s
.get('width')),
504 'height': int_or_none(s
.get('height')),
505 'fps': count
/ duration
,
506 'rows': int_or_none(s
.get('rows')),
507 'columns': int_or_none(s
.get('cols')),
509 'url': urljoin(base
, path
),
510 'duration': fragment_duration
,
511 } for path
in images
],
514 def _real_extract(self
, url
):
515 vod_id
= self
._match
_id
(url
)
517 video
= self
._download
_info
(vod_id
)
518 info
= self
._extract
_info
_gql
(video
, vod_id
)
519 access_token
= self
._download
_access
_token
(vod_id
, 'video', 'id')
521 formats
= self
._extract
_m
3u8_formats
(
522 '%s/vod/%s.m3u8?%s' % (
523 self
._USHER
_BASE
, vod_id
,
524 compat_urllib_parse_urlencode({
525 'allow_source': 'true',
526 'allow_audio_only': 'true',
527 'allow_spectre': 'true',
528 'player': 'twitchweb',
529 'playlist_include_framerate': 'true',
530 'nauth': access_token
['value'],
531 'nauthsig': access_token
['signature'],
533 vod_id
, 'mp4', entry_protocol
='m3u8_native')
535 formats
.extend(self
._extract
_storyboard
(vod_id
, video
.get('storyboard'), info
.get('duration')))
537 self
._prefer
_source
(formats
)
538 info
['formats'] = formats
540 parsed_url
= compat_urllib_parse_urlparse(url
)
541 query
= compat_parse_qs(parsed_url
.query
)
543 info
['start_time'] = parse_duration(query
['t'][0])
545 if info
.get('timestamp') is not None:
546 info
['subtitles'] = {
548 'url': update_url_query(
549 'https://api.twitch.tv/v5/videos/%s/comments' % vod_id
, {
550 'client_id': self
._CLIENT
_ID
,
559 def _make_video_result(node
):
560 assert isinstance(node
, dict)
561 video_id
= node
.get('id')
565 '_type': 'url_transparent',
566 'ie_key': TwitchVodIE
.ie_key(),
567 'id': 'v' + video_id
,
568 'url': 'https://www.twitch.tv/videos/%s' % video_id
,
569 'title': node
.get('title'),
570 'thumbnail': node
.get('previewThumbnailURL'),
571 'duration': float_or_none(node
.get('lengthSeconds')),
572 'view_count': int_or_none(node
.get('viewCount')),
576 class TwitchCollectionIE(TwitchBaseIE
):
577 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
580 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
582 'id': 'wlDCoH0zEBZZbQ',
583 'title': 'Overthrow Nook, capitalism for children',
585 'playlist_mincount': 13,
588 _OPERATION_NAME
= 'CollectionSideBar'
590 def _real_extract(self
, url
):
591 collection_id
= self
._match
_id
(url
)
592 collection
= self
._download
_gql
(
594 'operationName': self
._OPERATION
_NAME
,
595 'variables': {'collectionID': collection_id}
,
597 'Downloading collection GraphQL')[0]['data']['collection']
598 title
= collection
.get('title')
600 for edge
in collection
['items']['edges']:
601 if not isinstance(edge
, dict):
603 node
= edge
.get('node')
604 if not isinstance(node
, dict):
606 video
= _make_video_result(node
)
608 entries
.append(video
)
609 return self
.playlist_result(
610 entries
, playlist_id
=collection_id
, playlist_title
=title
)
613 class TwitchPlaylistBaseIE(TwitchBaseIE
):
616 def _entries(self
, channel_name
, *args
):
618 variables_common
= self
._make
_variables
(channel_name
, *args
)
619 entries_key
= '%ss' % self
._ENTRY
_KIND
620 for page_num
in itertools
.count(1):
621 variables
= variables_common
.copy()
622 variables
['limit'] = self
._PAGE
_LIMIT
624 variables
['cursor'] = cursor
625 page
= self
._download
_gql
(
627 'operationName': self
._OPERATION
_NAME
,
628 'variables': variables
,
630 'Downloading %ss GraphQL page %s' % (self
._NODE
_KIND
, page_num
),
635 page
, lambda x
: x
[0]['data']['user'][entries_key
]['edges'], list)
639 if not isinstance(edge
, dict):
641 if edge
.get('__typename') != self
._EDGE
_KIND
:
643 node
= edge
.get('node')
644 if not isinstance(node
, dict):
646 if node
.get('__typename') != self
._NODE
_KIND
:
648 entry
= self
._extract
_entry
(node
)
650 cursor
= edge
.get('cursor')
652 if not cursor
or not isinstance(cursor
, compat_str
):
656 class TwitchVideosIE(TwitchPlaylistBaseIE
):
657 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
660 # All Videos sorted by Date
661 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
664 'title': 'spamfish - All Videos sorted by Date',
666 'playlist_mincount': 924,
668 # All Videos sorted by Popular
669 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
672 'title': 'spamfish - All Videos sorted by Popular',
674 'playlist_mincount': 931,
676 # Past Broadcasts sorted by Date
677 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
680 'title': 'spamfish - Past Broadcasts sorted by Date',
682 'playlist_mincount': 27,
684 # Highlights sorted by Date
685 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
688 'title': 'spamfish - Highlights sorted by Date',
690 'playlist_mincount': 901,
692 # Uploads sorted by Date
693 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
696 'title': 'esl_csgo - Uploads sorted by Date',
698 'playlist_mincount': 5,
700 # Past Premieres sorted by Date
701 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
704 'title': 'spamfish - Past Premieres sorted by Date',
706 'playlist_mincount': 1,
708 'url': 'https://www.twitch.tv/spamfish/videos/all',
709 'only_matching': True,
711 'url': 'https://m.twitch.tv/spamfish/videos/all',
712 'only_matching': True,
714 'url': 'https://www.twitch.tv/spamfish/videos',
715 'only_matching': True,
718 Broadcast
= collections
.namedtuple('Broadcast', ['type', 'label'])
720 _DEFAULT_BROADCAST
= Broadcast(None, 'All Videos')
722 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
723 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
724 'uploads': Broadcast('UPLOAD', 'Uploads'),
725 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
726 'all': _DEFAULT_BROADCAST
,
729 _DEFAULT_SORTED_BY
= 'Date'
731 'time': _DEFAULT_SORTED_BY
,
735 _OPERATION_NAME
= 'FilterableVideoTower_Videos'
736 _ENTRY_KIND
= 'video'
737 _EDGE_KIND
= 'VideoEdge'
741 def suitable(cls
, url
):
743 if any(ie
.suitable(url
) for ie
in (
745 TwitchVideosCollectionsIE
))
746 else super(TwitchVideosIE
, cls
).suitable(url
))
749 def _make_variables(channel_name
, broadcast_type
, sort
):
751 'channelOwnerLogin': channel_name
,
752 'broadcastType': broadcast_type
,
753 'videoSort': sort
.upper(),
757 def _extract_entry(node
):
758 return _make_video_result(node
)
760 def _real_extract(self
, url
):
761 channel_name
= self
._match
_id
(url
)
763 filter = qs
.get('filter', ['all'])[0]
764 sort
= qs
.get('sort', ['time'])[0]
765 broadcast
= self
._BROADCASTS
.get(filter, self
._DEFAULT
_BROADCAST
)
766 return self
.playlist_result(
767 self
._entries
(channel_name
, broadcast
.type, sort
),
768 playlist_id
=channel_name
,
769 playlist_title
='%s - %s sorted by %s'
770 % (channel_name
, broadcast
.label
,
771 self
._SORTED
_BY
.get(sort
, self
._DEFAULT
_SORTED
_BY
)))
774 class TwitchVideosClipsIE(TwitchPlaylistBaseIE
):
775 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
779 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
782 'title': 'vanillatv - Clips Top All',
784 'playlist_mincount': 1,
786 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
787 'only_matching': True,
790 Clip
= collections
.namedtuple('Clip', ['filter', 'label'])
792 _DEFAULT_CLIP
= Clip('LAST_WEEK', 'Top 7D')
794 '24hr': Clip('LAST_DAY', 'Top 24H'),
796 '30d': Clip('LAST_MONTH', 'Top 30D'),
797 'all': Clip('ALL_TIME', 'Top All'),
800 # NB: values other than 20 result in skipped videos
803 _OPERATION_NAME
= 'ClipsCards__User'
805 _EDGE_KIND
= 'ClipEdge'
809 def _make_variables(channel_name
, filter):
811 'login': channel_name
,
818 def _extract_entry(node
):
819 assert isinstance(node
, dict)
820 clip_url
= url_or_none(node
.get('url'))
824 '_type': 'url_transparent',
825 'ie_key': TwitchClipsIE
.ie_key(),
826 'id': node
.get('id'),
828 'title': node
.get('title'),
829 'thumbnail': node
.get('thumbnailURL'),
830 'duration': float_or_none(node
.get('durationSeconds')),
831 'timestamp': unified_timestamp(node
.get('createdAt')),
832 'view_count': int_or_none(node
.get('viewCount')),
833 'language': node
.get('language'),
836 def _real_extract(self
, url
):
837 channel_name
= self
._match
_id
(url
)
839 range = qs
.get('range', ['7d'])[0]
840 clip
= self
._RANGE
.get(range, self
._DEFAULT
_CLIP
)
841 return self
.playlist_result(
842 self
._entries
(channel_name
, clip
.filter),
843 playlist_id
=channel_name
,
844 playlist_title
='%s - Clips %s' % (channel_name
, clip
.label
))
847 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE
):
848 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
852 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
855 'title': 'spamfish - Collections',
857 'playlist_mincount': 3,
859 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
862 'title': 'monstercat - Collections',
864 'playlist_mincount': 13,
867 _OPERATION_NAME
= 'ChannelCollectionsContent'
868 _ENTRY_KIND
= 'collection'
869 _EDGE_KIND
= 'CollectionsItemEdge'
870 _NODE_KIND
= 'Collection'
873 def _make_variables(channel_name
):
875 'ownerLogin': channel_name
,
879 def _extract_entry(node
):
880 assert isinstance(node
, dict)
881 collection_id
= node
.get('id')
882 if not collection_id
:
885 '_type': 'url_transparent',
886 'ie_key': TwitchCollectionIE
.ie_key(),
888 'url': 'https://www.twitch.tv/collections/%s' % collection_id
,
889 'title': node
.get('title'),
890 'thumbnail': node
.get('thumbnailURL'),
891 'duration': float_or_none(node
.get('lengthSeconds')),
892 'timestamp': unified_timestamp(node
.get('updatedAt')),
893 'view_count': int_or_none(node
.get('viewCount')),
896 def _real_extract(self
, url
):
897 channel_name
= self
._match
_id
(url
)
898 return self
.playlist_result(
899 self
._entries
(channel_name
), playlist_id
=channel_name
,
900 playlist_title
='%s - Collections' % channel_name
)
903 class TwitchStreamIE(TwitchBaseIE
):
904 IE_NAME
= 'twitch:stream'
905 _VALID_URL
= r
'''(?x)
908 (?:(?:www|go|m)\.)?twitch\.tv/|
909 player\.twitch\.tv/\?.*?\bchannel=
915 'url': 'http://www.twitch.tv/shroomztv',
918 'display_id': 'shroomztv',
920 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
921 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
923 'timestamp': 1421928037,
924 'upload_date': '20150122',
925 'uploader': 'ShroomzTV',
926 'uploader_id': 'shroomztv',
931 'skip_download': True,
933 'skip': 'User does not exist',
935 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
936 'only_matching': True,
938 'url': 'https://player.twitch.tv/?channel=lotsofs',
939 'only_matching': True,
941 'url': 'https://go.twitch.tv/food',
942 'only_matching': True,
944 'url': 'https://m.twitch.tv/food',
945 'only_matching': True,
947 'url': 'https://www.twitch.tv/monstercat',
950 'display_id': 'monstercat',
951 'title': 're:Monstercat',
952 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
954 'timestamp': 1677107190,
955 'upload_date': '20230222',
956 'uploader': 'Monstercat',
957 'uploader_id': 'monstercat',
958 'live_status': 'is_live',
959 'thumbnail': 're:https://.*.jpg',
963 'skip_download': 'Livestream',
968 def suitable(cls
, url
):
970 if any(ie
.suitable(url
) for ie
in (
975 TwitchVideosCollectionsIE
,
977 else super(TwitchStreamIE
, cls
).suitable(url
))
979 def _real_extract(self
, url
):
980 channel_name
= self
._match
_id
(url
).lower()
982 gql
= self
._download
_gql
(
984 'operationName': 'StreamMetadata',
985 'variables': {'channelLogin': channel_name}
,
987 'operationName': 'ComscoreStreamingQuery',
989 'channel': channel_name
,
993 'isVodOrCollection': False,
997 'operationName': 'VideoPreviewOverlay',
998 'variables': {'login': channel_name}
,
1000 'Downloading stream GraphQL')
1002 user
= gql
[0]['data']['user']
1005 raise ExtractorError(
1006 '%s does not exist' % channel_name
, expected
=True)
1008 stream
= user
['stream']
1011 raise UserNotLive(video_id
=channel_name
)
1013 access_token
= self
._download
_access
_token
(
1014 channel_name
, 'stream', 'channelName')
1015 token
= access_token
['value']
1017 stream_id
= stream
.get('id') or channel_name
1019 'allow_source': 'true',
1020 'allow_audio_only': 'true',
1021 'allow_spectre': 'true',
1022 'p': random
.randint(1000000, 10000000),
1023 'player': 'twitchweb',
1024 'playlist_include_framerate': 'true',
1025 'segment_preference': '4',
1026 'sig': access_token
['signature'].encode('utf-8'),
1027 'token': token
.encode('utf-8'),
1029 formats
= self
._extract
_m
3u8_formats
(
1030 '%s/api/channel/hls/%s.m3u8' % (self
._USHER
_BASE
, channel_name
),
1031 stream_id
, 'mp4', query
=query
)
1032 self
._prefer
_source
(formats
)
1034 view_count
= stream
.get('viewers')
1035 timestamp
= unified_timestamp(stream
.get('createdAt'))
1037 sq_user
= try_get(gql
, lambda x
: x
[1]['data']['user'], dict) or {}
1038 uploader
= sq_user
.get('displayName')
1039 description
= try_get(
1040 sq_user
, lambda x
: x
['broadcastSettings']['title'], compat_str
)
1042 thumbnail
= url_or_none(try_get(
1043 gql
, lambda x
: x
[2]['data']['user']['stream']['previewImageURL'],
1046 title
= uploader
or channel_name
1047 stream_type
= stream
.get('type')
1048 if stream_type
in ['rerun', 'live']:
1049 title
+= ' (%s)' % stream_type
1053 'display_id': channel_name
,
1055 'description': description
,
1056 'thumbnail': thumbnail
,
1057 'uploader': uploader
,
1058 'uploader_id': channel_name
,
1059 'timestamp': timestamp
,
1060 'view_count': view_count
,
1062 'is_live': stream_type
== 'live',
1066 class TwitchClipsIE(TwitchBaseIE
):
1067 IE_NAME
= 'twitch:clips'
1068 _VALID_URL
= r
'''(?x)
1071 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
1072 (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/
1078 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
1079 'md5': '761769e1eafce0ffebfb4089cb3847cd',
1082 'display_id': 'FaintLightGullWholeWheat',
1084 'title': 'EA Play 2016 Live from the Novo Theatre',
1085 'thumbnail': r
're:^https?://.*\.jpg',
1086 'timestamp': 1465767393,
1087 'upload_date': '20160612',
1089 'uploader': 'stereotype_',
1090 'uploader_id': '43566419',
1094 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
1095 'only_matching': True,
1097 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
1098 'only_matching': True,
1100 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
1101 'only_matching': True,
1103 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1104 'only_matching': True,
1106 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1107 'only_matching': True,
1110 def _real_extract(self
, url
):
1111 video_id
= self
._match
_id
(url
)
1113 clip
= self
._download
_gql
(
1115 'operationName': 'VideoAccessToken_Clip',
1120 'Downloading clip access token GraphQL')[0]['data']['clip']
1123 raise ExtractorError(
1124 'This clip is no longer available', expected
=True)
1127 'sig': clip
['playbackAccessToken']['signature'],
1128 'token': clip
['playbackAccessToken']['value'],
1131 data
= self
._download
_base
_gql
(
1145 tiny: thumbnailURL(width: 86, height: 45)
1146 small: thumbnailURL(width: 260, height: 147)
1147 medium: thumbnailURL(width: 480, height: 272)
1156 }''' % video_id
}, 'Downloading clip GraphQL', fatal
=False)
1159 clip
= try_get(data
, lambda x
: x
['data']['clip'], dict) or clip
1162 for option
in clip
.get('videoQualities', []):
1163 if not isinstance(option
, dict):
1165 source
= url_or_none(option
.get('sourceURL'))
1169 'url': update_url_query(source
, access_query
),
1170 'format_id': option
.get('quality'),
1171 'height': int_or_none(option
.get('quality')),
1172 'fps': int_or_none(option
.get('frameRate')),
1176 for thumbnail_id
in ('tiny', 'small', 'medium'):
1177 thumbnail_url
= clip
.get(thumbnail_id
)
1178 if not thumbnail_url
:
1182 'url': thumbnail_url
,
1184 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
1187 'height': int(mobj
.group(2)),
1188 'width': int(mobj
.group(1)),
1190 thumbnails
.append(thumb
)
1192 old_id
= self
._search
_regex
(r
'%7C(\d+)(?:-\d+)?.mp4', formats
[-1]['url'], 'old id', default
=None)
1195 'id': clip
.get('id') or video_id
,
1196 '_old_archive_ids': [make_archive_id(self
, old_id
)] if old_id
else None,
1197 'display_id': video_id
,
1198 'title': clip
.get('title'),
1200 'duration': int_or_none(clip
.get('durationSeconds')),
1201 'view_count': int_or_none(clip
.get('viewCount')),
1202 'timestamp': unified_timestamp(clip
.get('createdAt')),
1203 'thumbnails': thumbnails
,
1204 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], compat_str
),
1205 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], compat_str
),
1206 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], compat_str
),