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]
182 def _get_thumbnails(self, thumbnail):
184 'url
': re.sub(r'\d
+x\d
+(\
.\w
+)($|
(?
=[?
#]))', r'0x0\g<1>', thumbnail),
188 }] if thumbnail
else None
191 class TwitchVodIE(TwitchBaseIE
):
192 IE_NAME
= 'twitch:vod'
193 _VALID_URL
= r
'''(?x)
196 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
197 player\.twitch\.tv/\?.*?\bvideo=v?
203 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
207 'title': 'LCK Summer Split - Week 6 Day 1',
208 'thumbnail': r
're:^https?://.*\.jpg$',
210 'timestamp': 1435131734,
211 'upload_date': '20150624',
212 'uploader': 'Riot Games',
213 'uploader_id': 'riotgames',
220 'title': 'League of Legends'
223 'live_status': 'was_live',
227 'skip_download': True,
230 # Untitled broadcast (title is None)
231 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
235 'title': 'Untitled Broadcast',
236 'thumbnail': r
're:^https?://.*\.jpg$',
238 'timestamp': 1439746708,
239 'upload_date': '20150816',
240 'uploader': 'BelkAO_o',
241 'uploader_id': 'belkao_o',
246 'skip_download': True,
248 'skip': 'HTTP Error 404: Not Found',
250 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
251 'only_matching': True,
253 'url': 'https://www.twitch.tv/videos/6528877',
254 'only_matching': True,
256 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
257 'only_matching': True,
259 'url': 'https://www.twitch.tv/northernlion/video/291940395',
260 'only_matching': True,
262 'url': 'https://player.twitch.tv/?video=480452374',
263 'only_matching': True,
265 'url': 'https://www.twitch.tv/videos/635475444',
269 'title': 'Riot Games',
271 'uploader': 'Riot Games',
272 'uploader_id': 'riotgames',
273 'timestamp': 1590770569,
274 'upload_date': '20200529',
279 'title': 'League of Legends'
284 'title': 'Legends of Runeterra'
292 'live_status': 'was_live',
293 'thumbnail': r
're:^https?://.*\.jpg$',
297 'skip_download': True
300 'note': 'Storyboards',
301 'url': 'https://www.twitch.tv/videos/635475444',
306 'title': 'Riot Games',
308 'uploader': 'Riot Games',
309 'uploader_id': 'riotgames',
310 'timestamp': 1590770569,
311 'upload_date': '20200529',
316 'title': 'League of Legends'
321 'title': 'Legends of Runeterra'
329 'live_status': 'was_live',
330 'thumbnail': r
're:^https?://.*\.jpg$',
337 'skip_download': True
340 'note': 'VOD with single chapter',
341 'url': 'https://www.twitch.tv/videos/1536751224',
345 'title': 'Porter Robinson Star Guardian Stream Tour with LilyPichu',
347 'uploader': 'Riot Games',
348 'uploader_id': 'riotgames',
349 'timestamp': 1658267731,
350 'upload_date': '20220719',
355 'title': 'League of Legends'
358 'live_status': 'was_live',
359 'thumbnail': r
're:^https?://.*\.jpg$',
363 'skip_download': True
365 'expected_warnings': ['Unable to download JSON metadata: HTTP Error 403: Forbidden']
368 def _download_info(self
, item_id
):
369 data
= self
._download
_gql
(
371 'operationName': 'VideoMetadata',
377 'operationName': 'VideoPlayer_ChapterSelectButtonVideo',
379 'includePrivate': False,
383 'operationName': 'VideoPlayer_VODSeekbarPreviewVideo',
385 'includePrivate': False,
389 'Downloading stream metadata GraphQL')
391 video
= traverse_obj(data
, (..., 'data', 'video'), get_all
=False)
393 raise ExtractorError(f
'Video {item_id} does not exist', expected
=True)
395 video
['moments'] = traverse_obj(data
, (..., 'data', 'video', 'moments', 'edges', ..., 'node'))
396 video
['storyboard'] = traverse_obj(
397 data
, (..., 'data', 'video', 'seekPreviewsURL', {url_or_none}
), get_all
=False)
401 def _extract_info(self
, info
):
402 status
= info
.get('status')
403 if status
== 'recording':
405 elif status
== 'recorded':
409 _QUALITIES
= ('small', 'medium', 'large')
410 quality_key
= qualities(_QUALITIES
)
412 preview
= info
.get('preview')
413 if isinstance(preview
, dict):
414 for thumbnail_id
, thumbnail_url
in preview
.items():
415 thumbnail_url
= url_or_none(thumbnail_url
)
416 if not thumbnail_url
:
418 if thumbnail_id
not in _QUALITIES
:
421 'url': thumbnail_url
,
422 'preference': quality_key(thumbnail_id
),
426 'title': info
.get('title') or 'Untitled Broadcast',
427 'description': info
.get('description'),
428 'duration': int_or_none(info
.get('length')),
429 'thumbnails': thumbnails
,
430 'uploader': info
.get('channel', {}).get('display_name'),
431 'uploader_id': info
.get('channel', {}).get('name'),
432 'timestamp': parse_iso8601(info
.get('recorded_at')),
433 'view_count': int_or_none(info
.get('views')),
438 def _extract_chapters(self
, info
, item_id
):
439 if not info
.get('moments'):
440 game
= traverse_obj(info
, ('game', 'displayName'))
442 yield {'title': game}
445 for moment
in info
['moments']:
446 start_time
= int_or_none(moment
.get('positionMilliseconds'), 1000)
447 duration
= int_or_none(moment
.get('durationMilliseconds'), 1000)
448 name
= str_or_none(moment
.get('description'))
450 if start_time
is None or duration
is None:
451 self
.report_warning(f
'Important chapter information missing for chapter {name}', item_id
)
454 'start_time': start_time
,
455 'end_time': start_time
+ duration
,
459 def _extract_info_gql(self
, info
, item_id
):
460 vod_id
= info
.get('id') or item_id
461 # id backward compatibility for download archives
463 vod_id
= 'v%s' % vod_id
464 thumbnail
= url_or_none(info
.get('previewThumbnailURL'))
467 if re
.findall(r
'/404_processing_[^.?#]+\.png', thumbnail
):
468 is_live
, thumbnail
= True, None
474 'title': info
.get('title') or 'Untitled Broadcast',
475 'description': info
.get('description'),
476 'duration': int_or_none(info
.get('lengthSeconds')),
477 'thumbnails': self
._get
_thumbnails
(thumbnail
),
478 'uploader': try_get(info
, lambda x
: x
['owner']['displayName'], compat_str
),
479 'uploader_id': try_get(info
, lambda x
: x
['owner']['login'], compat_str
),
480 'timestamp': unified_timestamp(info
.get('publishedAt')),
481 'view_count': int_or_none(info
.get('viewCount')),
482 'chapters': list(self
._extract
_chapters
(info
, item_id
)),
487 def _extract_storyboard(self
, item_id
, storyboard_json_url
, duration
):
488 if not duration
or not storyboard_json_url
:
490 spec
= self
._download
_json
(storyboard_json_url
, item_id
, 'Downloading storyboard metadata JSON', fatal
=False) or []
491 # sort from highest quality to lowest
492 # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
493 spec
.sort(key
=lambda x
: int_or_none(x
.get('width')) or 0, reverse
=True)
494 base
= base_url(storyboard_json_url
)
495 for i
, s
in enumerate(spec
):
496 count
= int_or_none(s
.get('count'))
497 images
= s
.get('images')
498 if not (images
and count
):
500 fragment_duration
= duration
/ len(images
)
502 'format_id': f
'sb{i}',
503 'format_note': 'storyboard',
508 'url': urljoin(base
, images
[0]),
509 'width': int_or_none(s
.get('width')),
510 'height': int_or_none(s
.get('height')),
511 'fps': count
/ duration
,
512 'rows': int_or_none(s
.get('rows')),
513 'columns': int_or_none(s
.get('cols')),
515 'url': urljoin(base
, path
),
516 'duration': fragment_duration
,
517 } for path
in images
],
520 def _real_extract(self
, url
):
521 vod_id
= self
._match
_id
(url
)
523 video
= self
._download
_info
(vod_id
)
524 info
= self
._extract
_info
_gql
(video
, vod_id
)
525 access_token
= self
._download
_access
_token
(vod_id
, 'video', 'id')
527 formats
= self
._extract
_m
3u8_formats
(
528 '%s/vod/%s.m3u8?%s' % (
529 self
._USHER
_BASE
, vod_id
,
530 compat_urllib_parse_urlencode({
531 'allow_source': 'true',
532 'allow_audio_only': 'true',
533 'allow_spectre': 'true',
534 'player': 'twitchweb',
535 'playlist_include_framerate': 'true',
536 'nauth': access_token
['value'],
537 'nauthsig': access_token
['signature'],
539 vod_id
, 'mp4', entry_protocol
='m3u8_native')
541 formats
.extend(self
._extract
_storyboard
(vod_id
, video
.get('storyboard'), info
.get('duration')))
543 self
._prefer
_source
(formats
)
544 info
['formats'] = formats
546 parsed_url
= compat_urllib_parse_urlparse(url
)
547 query
= compat_parse_qs(parsed_url
.query
)
549 info
['start_time'] = parse_duration(query
['t'][0])
551 if info
.get('timestamp') is not None:
552 info
['subtitles'] = {
554 'url': update_url_query(
555 'https://api.twitch.tv/v5/videos/%s/comments' % vod_id
, {
556 'client_id': self
._CLIENT
_ID
,
565 def _make_video_result(node
):
566 assert isinstance(node
, dict)
567 video_id
= node
.get('id')
571 '_type': 'url_transparent',
572 'ie_key': TwitchVodIE
.ie_key(),
573 'id': 'v' + video_id
,
574 'url': 'https://www.twitch.tv/videos/%s' % video_id
,
575 'title': node
.get('title'),
576 'thumbnail': node
.get('previewThumbnailURL'),
577 'duration': float_or_none(node
.get('lengthSeconds')),
578 'view_count': int_or_none(node
.get('viewCount')),
582 class TwitchCollectionIE(TwitchBaseIE
):
583 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
586 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
588 'id': 'wlDCoH0zEBZZbQ',
589 'title': 'Overthrow Nook, capitalism for children',
591 'playlist_mincount': 13,
594 _OPERATION_NAME
= 'CollectionSideBar'
596 def _real_extract(self
, url
):
597 collection_id
= self
._match
_id
(url
)
598 collection
= self
._download
_gql
(
600 'operationName': self
._OPERATION
_NAME
,
601 'variables': {'collectionID': collection_id}
,
603 'Downloading collection GraphQL')[0]['data']['collection']
604 title
= collection
.get('title')
606 for edge
in collection
['items']['edges']:
607 if not isinstance(edge
, dict):
609 node
= edge
.get('node')
610 if not isinstance(node
, dict):
612 video
= _make_video_result(node
)
614 entries
.append(video
)
615 return self
.playlist_result(
616 entries
, playlist_id
=collection_id
, playlist_title
=title
)
619 class TwitchPlaylistBaseIE(TwitchBaseIE
):
622 def _entries(self
, channel_name
, *args
):
624 variables_common
= self
._make
_variables
(channel_name
, *args
)
625 entries_key
= '%ss' % self
._ENTRY
_KIND
626 for page_num
in itertools
.count(1):
627 variables
= variables_common
.copy()
628 variables
['limit'] = self
._PAGE
_LIMIT
630 variables
['cursor'] = cursor
631 page
= self
._download
_gql
(
633 'operationName': self
._OPERATION
_NAME
,
634 'variables': variables
,
636 'Downloading %ss GraphQL page %s' % (self
._NODE
_KIND
, page_num
),
641 page
, lambda x
: x
[0]['data']['user'][entries_key
]['edges'], list)
645 if not isinstance(edge
, dict):
647 if edge
.get('__typename') != self
._EDGE
_KIND
:
649 node
= edge
.get('node')
650 if not isinstance(node
, dict):
652 if node
.get('__typename') != self
._NODE
_KIND
:
654 entry
= self
._extract
_entry
(node
)
656 cursor
= edge
.get('cursor')
658 if not cursor
or not isinstance(cursor
, compat_str
):
662 class TwitchVideosIE(TwitchPlaylistBaseIE
):
663 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
666 # All Videos sorted by Date
667 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
670 'title': 'spamfish - All Videos sorted by Date',
672 'playlist_mincount': 924,
674 # All Videos sorted by Popular
675 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
678 'title': 'spamfish - All Videos sorted by Popular',
680 'playlist_mincount': 931,
682 # Past Broadcasts sorted by Date
683 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
686 'title': 'spamfish - Past Broadcasts sorted by Date',
688 'playlist_mincount': 27,
690 # Highlights sorted by Date
691 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
694 'title': 'spamfish - Highlights sorted by Date',
696 'playlist_mincount': 901,
698 # Uploads sorted by Date
699 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
702 'title': 'esl_csgo - Uploads sorted by Date',
704 'playlist_mincount': 5,
706 # Past Premieres sorted by Date
707 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
710 'title': 'spamfish - Past Premieres sorted by Date',
712 'playlist_mincount': 1,
714 'url': 'https://www.twitch.tv/spamfish/videos/all',
715 'only_matching': True,
717 'url': 'https://m.twitch.tv/spamfish/videos/all',
718 'only_matching': True,
720 'url': 'https://www.twitch.tv/spamfish/videos',
721 'only_matching': True,
724 Broadcast
= collections
.namedtuple('Broadcast', ['type', 'label'])
726 _DEFAULT_BROADCAST
= Broadcast(None, 'All Videos')
728 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
729 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
730 'uploads': Broadcast('UPLOAD', 'Uploads'),
731 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
732 'all': _DEFAULT_BROADCAST
,
735 _DEFAULT_SORTED_BY
= 'Date'
737 'time': _DEFAULT_SORTED_BY
,
741 _OPERATION_NAME
= 'FilterableVideoTower_Videos'
742 _ENTRY_KIND
= 'video'
743 _EDGE_KIND
= 'VideoEdge'
747 def suitable(cls
, url
):
749 if any(ie
.suitable(url
) for ie
in (
751 TwitchVideosCollectionsIE
))
752 else super(TwitchVideosIE
, cls
).suitable(url
))
755 def _make_variables(channel_name
, broadcast_type
, sort
):
757 'channelOwnerLogin': channel_name
,
758 'broadcastType': broadcast_type
,
759 'videoSort': sort
.upper(),
763 def _extract_entry(node
):
764 return _make_video_result(node
)
766 def _real_extract(self
, url
):
767 channel_name
= self
._match
_id
(url
)
769 filter = qs
.get('filter', ['all'])[0]
770 sort
= qs
.get('sort', ['time'])[0]
771 broadcast
= self
._BROADCASTS
.get(filter, self
._DEFAULT
_BROADCAST
)
772 return self
.playlist_result(
773 self
._entries
(channel_name
, broadcast
.type, sort
),
774 playlist_id
=channel_name
,
775 playlist_title
='%s - %s sorted by %s'
776 % (channel_name
, broadcast
.label
,
777 self
._SORTED
_BY
.get(sort
, self
._DEFAULT
_SORTED
_BY
)))
780 class TwitchVideosClipsIE(TwitchPlaylistBaseIE
):
781 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
785 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
788 'title': 'vanillatv - Clips Top All',
790 'playlist_mincount': 1,
792 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
793 'only_matching': True,
796 Clip
= collections
.namedtuple('Clip', ['filter', 'label'])
798 _DEFAULT_CLIP
= Clip('LAST_WEEK', 'Top 7D')
800 '24hr': Clip('LAST_DAY', 'Top 24H'),
802 '30d': Clip('LAST_MONTH', 'Top 30D'),
803 'all': Clip('ALL_TIME', 'Top All'),
806 # NB: values other than 20 result in skipped videos
809 _OPERATION_NAME
= 'ClipsCards__User'
811 _EDGE_KIND
= 'ClipEdge'
815 def _make_variables(channel_name
, filter):
817 'login': channel_name
,
824 def _extract_entry(node
):
825 assert isinstance(node
, dict)
826 clip_url
= url_or_none(node
.get('url'))
830 '_type': 'url_transparent',
831 'ie_key': TwitchClipsIE
.ie_key(),
832 'id': node
.get('id'),
834 'title': node
.get('title'),
835 'thumbnail': node
.get('thumbnailURL'),
836 'duration': float_or_none(node
.get('durationSeconds')),
837 'timestamp': unified_timestamp(node
.get('createdAt')),
838 'view_count': int_or_none(node
.get('viewCount')),
839 'language': node
.get('language'),
842 def _real_extract(self
, url
):
843 channel_name
= self
._match
_id
(url
)
845 range = qs
.get('range', ['7d'])[0]
846 clip
= self
._RANGE
.get(range, self
._DEFAULT
_CLIP
)
847 return self
.playlist_result(
848 self
._entries
(channel_name
, clip
.filter),
849 playlist_id
=channel_name
,
850 playlist_title
='%s - Clips %s' % (channel_name
, clip
.label
))
853 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE
):
854 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
858 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
861 'title': 'spamfish - Collections',
863 'playlist_mincount': 3,
865 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
868 'title': 'monstercat - Collections',
870 'playlist_mincount': 13,
873 _OPERATION_NAME
= 'ChannelCollectionsContent'
874 _ENTRY_KIND
= 'collection'
875 _EDGE_KIND
= 'CollectionsItemEdge'
876 _NODE_KIND
= 'Collection'
879 def _make_variables(channel_name
):
881 'ownerLogin': channel_name
,
885 def _extract_entry(node
):
886 assert isinstance(node
, dict)
887 collection_id
= node
.get('id')
888 if not collection_id
:
891 '_type': 'url_transparent',
892 'ie_key': TwitchCollectionIE
.ie_key(),
894 'url': 'https://www.twitch.tv/collections/%s' % collection_id
,
895 'title': node
.get('title'),
896 'thumbnail': node
.get('thumbnailURL'),
897 'duration': float_or_none(node
.get('lengthSeconds')),
898 'timestamp': unified_timestamp(node
.get('updatedAt')),
899 'view_count': int_or_none(node
.get('viewCount')),
902 def _real_extract(self
, url
):
903 channel_name
= self
._match
_id
(url
)
904 return self
.playlist_result(
905 self
._entries
(channel_name
), playlist_id
=channel_name
,
906 playlist_title
='%s - Collections' % channel_name
)
909 class TwitchStreamIE(TwitchBaseIE
):
910 IE_NAME
= 'twitch:stream'
911 _VALID_URL
= r
'''(?x)
914 (?:(?:www|go|m)\.)?twitch\.tv/|
915 player\.twitch\.tv/\?.*?\bchannel=
921 'url': 'http://www.twitch.tv/shroomztv',
924 'display_id': 'shroomztv',
926 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
927 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
929 'timestamp': 1421928037,
930 'upload_date': '20150122',
931 'uploader': 'ShroomzTV',
932 'uploader_id': 'shroomztv',
937 'skip_download': True,
939 'skip': 'User does not exist',
941 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
942 'only_matching': True,
944 'url': 'https://player.twitch.tv/?channel=lotsofs',
945 'only_matching': True,
947 'url': 'https://go.twitch.tv/food',
948 'only_matching': True,
950 'url': 'https://m.twitch.tv/food',
951 'only_matching': True,
953 'url': 'https://www.twitch.tv/monstercat',
956 'display_id': 'monstercat',
957 'title': 're:Monstercat',
958 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
960 'timestamp': 1677107190,
961 'upload_date': '20230222',
962 'uploader': 'Monstercat',
963 'uploader_id': 'monstercat',
964 'live_status': 'is_live',
965 'thumbnail': 're:https://.*.jpg',
969 'skip_download': 'Livestream',
974 def suitable(cls
, url
):
976 if any(ie
.suitable(url
) for ie
in (
981 TwitchVideosCollectionsIE
,
983 else super(TwitchStreamIE
, cls
).suitable(url
))
985 def _real_extract(self
, url
):
986 channel_name
= self
._match
_id
(url
).lower()
988 gql
= self
._download
_gql
(
990 'operationName': 'StreamMetadata',
991 'variables': {'channelLogin': channel_name}
,
993 'operationName': 'ComscoreStreamingQuery',
995 'channel': channel_name
,
999 'isVodOrCollection': False,
1003 'operationName': 'VideoPreviewOverlay',
1004 'variables': {'login': channel_name}
,
1006 'Downloading stream GraphQL')
1008 user
= gql
[0]['data']['user']
1011 raise ExtractorError(
1012 '%s does not exist' % channel_name
, expected
=True)
1014 stream
= user
['stream']
1017 raise UserNotLive(video_id
=channel_name
)
1019 access_token
= self
._download
_access
_token
(
1020 channel_name
, 'stream', 'channelName')
1021 token
= access_token
['value']
1023 stream_id
= stream
.get('id') or channel_name
1025 'allow_source': 'true',
1026 'allow_audio_only': 'true',
1027 'allow_spectre': 'true',
1028 'p': random
.randint(1000000, 10000000),
1029 'player': 'twitchweb',
1030 'playlist_include_framerate': 'true',
1031 'segment_preference': '4',
1032 'sig': access_token
['signature'].encode('utf-8'),
1033 'token': token
.encode('utf-8'),
1035 formats
= self
._extract
_m
3u8_formats
(
1036 '%s/api/channel/hls/%s.m3u8' % (self
._USHER
_BASE
, channel_name
),
1037 stream_id
, 'mp4', query
=query
)
1038 self
._prefer
_source
(formats
)
1040 view_count
= stream
.get('viewers')
1041 timestamp
= unified_timestamp(stream
.get('createdAt'))
1043 sq_user
= try_get(gql
, lambda x
: x
[1]['data']['user'], dict) or {}
1044 uploader
= sq_user
.get('displayName')
1045 description
= try_get(
1046 sq_user
, lambda x
: x
['broadcastSettings']['title'], compat_str
)
1048 thumbnail
= url_or_none(try_get(
1049 gql
, lambda x
: x
[2]['data']['user']['stream']['previewImageURL'],
1052 title
= uploader
or channel_name
1053 stream_type
= stream
.get('type')
1054 if stream_type
in ['rerun', 'live']:
1055 title
+= ' (%s)' % stream_type
1059 'display_id': channel_name
,
1061 'description': description
,
1062 'thumbnails': self
._get
_thumbnails
(thumbnail
),
1063 'uploader': uploader
,
1064 'uploader_id': channel_name
,
1065 'timestamp': timestamp
,
1066 'view_count': view_count
,
1068 'is_live': stream_type
== 'live',
1072 class TwitchClipsIE(TwitchBaseIE
):
1073 IE_NAME
= 'twitch:clips'
1074 _VALID_URL
= r
'''(?x)
1077 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
1078 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/)?clip/
1084 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
1085 'md5': '761769e1eafce0ffebfb4089cb3847cd',
1088 'display_id': 'FaintLightGullWholeWheat',
1090 'title': 'EA Play 2016 Live from the Novo Theatre',
1091 'thumbnail': r
're:^https?://.*\.jpg',
1092 'timestamp': 1465767393,
1093 'upload_date': '20160612',
1095 'uploader': 'stereotype_',
1096 'uploader_id': '43566419',
1100 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
1101 'only_matching': True,
1103 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
1104 'only_matching': True,
1106 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
1107 'only_matching': True,
1109 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1110 'only_matching': True,
1112 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1113 'only_matching': True,
1115 'url': 'https://m.twitch.tv/clip/FaintLightGullWholeWheat',
1116 'only_matching': True,
1119 def _real_extract(self
, url
):
1120 video_id
= self
._match
_id
(url
)
1122 clip
= self
._download
_gql
(
1124 'operationName': 'VideoAccessToken_Clip',
1129 'Downloading clip access token GraphQL')[0]['data']['clip']
1132 raise ExtractorError(
1133 'This clip is no longer available', expected
=True)
1136 'sig': clip
['playbackAccessToken']['signature'],
1137 'token': clip
['playbackAccessToken']['value'],
1140 data
= self
._download
_base
_gql
(
1154 tiny: thumbnailURL(width: 86, height: 45)
1155 small: thumbnailURL(width: 260, height: 147)
1156 medium: thumbnailURL(width: 480, height: 272)
1165 }''' % video_id
}, 'Downloading clip GraphQL', fatal
=False)
1168 clip
= try_get(data
, lambda x
: x
['data']['clip'], dict) or clip
1171 for option
in clip
.get('videoQualities', []):
1172 if not isinstance(option
, dict):
1174 source
= url_or_none(option
.get('sourceURL'))
1178 'url': update_url_query(source
, access_query
),
1179 'format_id': option
.get('quality'),
1180 'height': int_or_none(option
.get('quality')),
1181 'fps': int_or_none(option
.get('frameRate')),
1185 for thumbnail_id
in ('tiny', 'small', 'medium'):
1186 thumbnail_url
= clip
.get(thumbnail_id
)
1187 if not thumbnail_url
:
1191 'url': thumbnail_url
,
1193 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
1196 'height': int(mobj
.group(2)),
1197 'width': int(mobj
.group(1)),
1199 thumbnails
.append(thumb
)
1201 old_id
= self
._search
_regex
(r
'%7C(\d+)(?:-\d+)?.mp4', formats
[-1]['url'], 'old id', default
=None)
1204 'id': clip
.get('id') or video_id
,
1205 '_old_archive_ids': [make_archive_id(self
, old_id
)] if old_id
else None,
1206 'display_id': video_id
,
1207 'title': clip
.get('title'),
1209 'duration': int_or_none(clip
.get('durationSeconds')),
1210 'view_count': int_or_none(clip
.get('viewCount')),
1211 'timestamp': unified_timestamp(clip
.get('createdAt')),
1212 'thumbnails': thumbnails
,
1213 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], compat_str
),
1214 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], compat_str
),
1215 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], compat_str
),