8 from .common
import InfoExtractor
32 class TwitchBaseIE(InfoExtractor
):
33 _VALID_URL_BASE
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv'
35 _API_BASE
= 'https://api.twitch.tv'
36 _USHER_BASE
= 'https://usher.ttvnw.net'
37 _LOGIN_FORM_URL
= 'https://www.twitch.tv/login'
38 _LOGIN_POST_URL
= 'https://passport.twitch.tv/login'
39 _NETRC_MACHINE
= 'twitch'
42 'CollectionSideBar': '27111f1b382effad0b6def325caef1909c733fe6a4fbabf54f8d491ef2cf2f14',
43 'FilterableVideoTower_Videos': 'a937f1d22e269e39a03b509f65a7490f9fc247d7f83d6ac1421523e3b68042cb',
44 'ClipsCards__User': 'b73ad2bfaecfd30a9e6c28fada15bd97032c83ec77a0440766a56fe0bd632777',
45 'ChannelCollectionsContent': '447aec6a0cc1e8d0a8d7732d47eb0762c336a2294fdb009e9c9d854e49d484b9',
46 'StreamMetadata': 'a647c2a13599e5991e175155f798ca7f1ecddde73f7f341f39009c14dbf59962',
47 'ComscoreStreamingQuery': 'e1edae8122517d013405f237ffcc124515dc6ded82480a88daef69c83b53ac01',
48 'VideoAccessToken_Clip': '36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11',
49 'VideoPreviewOverlay': '3006e77e51b128d838fa4e835723ca4dc9a05c5efd4466c1085215c6e437e65c',
50 'VideoMetadata': '49b5b8f268cdeb259d75b58dcb0c1a748e3b575003448a2333dc5cdafd49adad',
51 'VideoPlayer_ChapterSelectButtonVideo': '8d2793384aac3773beab5e59bd5d6f585aedb923d292800119e03d40cd0f9b41',
52 'VideoPlayer_VODSeekbarPreviewVideo': '07e99e4d56c5a7c67117a154777b0baf85a5ffefa393b213f4bc712ccaf85dd6',
57 return self
._configuration
_arg
(
58 'client_id', ['ue6666qo983tsx6so1t0vnawi233wa'], ie_key
='Twitch', casesense
=True)[0]
60 def _perform_login(self
, username
, password
):
63 f
'Unable to login. Twitch said: {message}', expected
=True)
65 def login_step(page
, urlh
, note
, data
):
66 form
= self
._hidden
_inputs
(page
)
70 post_url
= self
._search
_regex
(
71 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page,
72 'post url
', default=self._LOGIN_POST_URL, group='url
')
73 post_url = urljoin(page_url, post_url)
77 'Origin
': 'https
://www
.twitch
.tv
',
78 'Content
-Type
': 'text
/plain
;charset
=UTF
-8',
81 response = self._download_json(
82 post_url, None, note, data=json.dumps(form).encode(),
83 headers=headers, expected_status=400)
84 error = dict_get(response, ('error
', 'error_description
', 'error_code
'))
88 if 'Authenticated successfully
' in response.get('message
', ''):
91 redirect_url = urljoin(
93 response.get('redirect
') or response['redirect_path
'])
94 return self._download_webpage_handle(
95 redirect_url, None, 'Downloading login redirect page
',
98 login_page, handle = self._download_webpage_handle(
99 self._LOGIN_FORM_URL, None, 'Downloading login page
')
101 # Some TOR nodes and public proxies are blocked completely
102 if 'blacklist_message
' in login_page:
103 fail(clean_html(login_page))
105 redirect_page, handle = login_step(
106 login_page, handle, 'Logging
in', {
107 'username
': username,
108 'password
': password,
109 'client_id
': self._CLIENT_ID,
113 if not redirect_page:
116 if re.search(r'(?i
)<form
[^
>]+id="two-factor-submit"', redirect_page) is not None:
117 # TODO: Add mechanism to request an SMS or phone call
118 tfa_token = self._get_tfa_info('two
-factor authentication token
')
119 login_step(redirect_page, handle, 'Submitting TFA token
', {
120 'authy_token
': tfa_token,
121 'remember_2fa
': 'true
',
124 def _prefer_source(self, formats):
126 source = next(f for f in formats if f['format_id
'] == 'Source
')
127 source['quality
'] = 10
128 except StopIteration:
130 if '/chunked
/' in f['url
']:
133 'format_note
': 'Source
',
136 def _download_base_gql(self, video_id, ops, note, fatal=True):
138 'Content
-Type
': 'text
/plain
;charset
=UTF
-8',
139 'Client
-ID
': self._CLIENT_ID,
141 gql_auth = self._get_cookies('https
://gql
.twitch
.tv
').get('auth
-token
')
143 headers['Authorization
'] = 'OAuth
' + gql_auth.value
144 return self._download_json(
145 'https
://gql
.twitch
.tv
/gql
', video_id, note,
146 data=json.dumps(ops).encode(),
147 headers=headers, fatal=fatal)
149 def _download_gql(self, video_id, ops, note, fatal=True):
154 'sha256Hash
': self._OPERATION_HASHES[op['operationName
']],
157 return self._download_base_gql(video_id, ops, note)
159 def _download_access_token(self, video_id, token_kind, param_name):
160 method = f'{token_kind}PlaybackAccessToken
'
167 playerBackend: "mediaplayer",
175 }''' % (method, param_name, video_id), # noqa: UP031
177 return self._download_base_gql(
179 f'Downloading {token_kind} access token GraphQL
')['data
'][method]
181 def _get_thumbnails(self, thumbnail):
183 'url
': re.sub(r'\d
+x\d
+(\
.\w
+)($|
(?
=[?
#]))', r'0x0\g<1>', thumbnail),
187 }] if thumbnail
else None
189 def _extract_twitch_m3u8_formats(self
, path
, video_id
, token
, signature
):
190 formats
= self
._extract
_m
3u8_formats
(
191 f
'{self._USHER_BASE}/{path}/{video_id}.m3u8', video_id
, 'mp4', query
={
192 'allow_source': 'true',
193 'allow_audio_only': 'true',
194 'allow_spectre': 'true',
195 'p': random
.randint(1000000, 10000000),
197 'player': 'twitchweb',
198 'supported_codecs': 'av1,h265,h264',
199 'playlist_include_framerate': 'true',
204 if fmt
.get('vcodec') and fmt
['vcodec'].startswith('av01'):
205 # mpegts does not yet have proper support for av1
206 fmt
['downloader_options'] = {'ffmpeg_args_out': ['-f', 'mp4']}
211 class TwitchVodIE(TwitchBaseIE
):
212 IE_NAME
= 'twitch:vod'
213 _VALID_URL
= r
'''(?x)
216 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
217 player\.twitch\.tv/\?.*?\bvideo=v?|
218 www\.twitch\.tv/[^/]+/schedule\?vodID=
224 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
228 'title': 'LCK Summer Split - Week 6 Day 1',
229 'thumbnail': r
're:^https?://.*\.jpg$',
231 'timestamp': 1435131734,
232 'upload_date': '20150624',
233 'uploader': 'Riot Games',
234 'uploader_id': 'riotgames',
241 'title': 'League of Legends',
244 'live_status': 'was_live',
248 'skip_download': True,
251 # Untitled broadcast (title is None)
252 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
256 'title': 'Untitled Broadcast',
257 'thumbnail': r
're:^https?://.*\.jpg$',
259 'timestamp': 1439746708,
260 'upload_date': '20150816',
261 'uploader': 'BelkAO_o',
262 'uploader_id': 'belkao_o',
267 'skip_download': True,
269 'skip': 'HTTP Error 404: Not Found',
271 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
272 'only_matching': True,
274 'url': 'https://www.twitch.tv/videos/6528877',
275 'only_matching': True,
277 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
278 'only_matching': True,
280 'url': 'https://www.twitch.tv/northernlion/video/291940395',
281 'only_matching': True,
283 'url': 'https://player.twitch.tv/?video=480452374',
284 'only_matching': True,
286 'url': 'https://www.twitch.tv/videos/635475444',
290 'title': 'Riot Games',
292 'uploader': 'Riot Games',
293 'uploader_id': 'riotgames',
294 'timestamp': 1590770569,
295 'upload_date': '20200529',
300 'title': 'League of Legends',
305 'title': 'Legends of Runeterra',
313 'live_status': 'was_live',
314 'thumbnail': r
're:^https?://.*\.jpg$',
318 'skip_download': True,
321 'note': 'Storyboards',
322 'url': 'https://www.twitch.tv/videos/635475444',
327 'title': 'Riot Games',
329 'uploader': 'Riot Games',
330 'uploader_id': 'riotgames',
331 'timestamp': 1590770569,
332 'upload_date': '20200529',
337 'title': 'League of Legends',
342 'title': 'Legends of Runeterra',
350 'live_status': 'was_live',
351 'thumbnail': r
're:^https?://.*\.jpg$',
358 'skip_download': True,
361 'note': 'VOD with single chapter',
362 'url': 'https://www.twitch.tv/videos/1536751224',
366 'title': 'Porter Robinson Star Guardian Stream Tour with LilyPichu',
368 'uploader': 'Riot Games',
369 'uploader_id': 'riotgames',
370 'timestamp': 1658267731,
371 'upload_date': '20220719',
376 'title': 'League of Legends',
379 'live_status': 'was_live',
380 'thumbnail': r
're:^https?://.*\.jpg$',
384 'skip_download': True,
386 'expected_warnings': ['Unable to download JSON metadata: HTTP Error 403: Forbidden'],
388 'url': 'https://www.twitch.tv/tangotek/schedule?vodID=1822395420',
389 'only_matching': True,
392 def _download_info(self
, item_id
):
393 data
= self
._download
_gql
(
395 'operationName': 'VideoMetadata',
401 'operationName': 'VideoPlayer_ChapterSelectButtonVideo',
403 'includePrivate': False,
407 'operationName': 'VideoPlayer_VODSeekbarPreviewVideo',
409 'includePrivate': False,
413 'Downloading stream metadata GraphQL')
415 video
= traverse_obj(data
, (..., 'data', 'video'), get_all
=False)
417 raise ExtractorError(f
'Video {item_id} does not exist', expected
=True)
419 video
['moments'] = traverse_obj(data
, (..., 'data', 'video', 'moments', 'edges', ..., 'node'))
420 video
['storyboard'] = traverse_obj(
421 data
, (..., 'data', 'video', 'seekPreviewsURL', {url_or_none}
), get_all
=False)
425 def _extract_info(self
, info
):
426 status
= info
.get('status')
427 if status
== 'recording':
429 elif status
== 'recorded':
433 _QUALITIES
= ('small', 'medium', 'large')
434 quality_key
= qualities(_QUALITIES
)
436 preview
= info
.get('preview')
437 if isinstance(preview
, dict):
438 for thumbnail_id
, thumbnail_url
in preview
.items():
439 thumbnail_url
= url_or_none(thumbnail_url
)
440 if not thumbnail_url
:
442 if thumbnail_id
not in _QUALITIES
:
445 'url': thumbnail_url
,
446 'preference': quality_key(thumbnail_id
),
450 'title': info
.get('title') or 'Untitled Broadcast',
451 'description': info
.get('description'),
452 'duration': int_or_none(info
.get('length')),
453 'thumbnails': thumbnails
,
454 'uploader': info
.get('channel', {}).get('display_name'),
455 'uploader_id': info
.get('channel', {}).get('name'),
456 'timestamp': parse_iso8601(info
.get('recorded_at')),
457 'view_count': int_or_none(info
.get('views')),
462 def _extract_chapters(self
, info
, item_id
):
463 if not info
.get('moments'):
464 game
= traverse_obj(info
, ('game', 'displayName'))
466 yield {'title': game
}
469 for moment
in info
['moments']:
470 start_time
= int_or_none(moment
.get('positionMilliseconds'), 1000)
471 duration
= int_or_none(moment
.get('durationMilliseconds'), 1000)
472 name
= str_or_none(moment
.get('description'))
474 if start_time
is None or duration
is None:
475 self
.report_warning(f
'Important chapter information missing for chapter {name}', item_id
)
478 'start_time': start_time
,
479 'end_time': start_time
+ duration
,
483 def _extract_info_gql(self
, info
, item_id
):
484 vod_id
= info
.get('id') or item_id
485 # id backward compatibility for download archives
487 vod_id
= f
'v{vod_id}'
488 thumbnail
= url_or_none(info
.get('previewThumbnailURL'))
491 if re
.findall(r
'/404_processing_[^.?#]+\.png', thumbnail
):
492 is_live
, thumbnail
= True, None
498 'title': info
.get('title') or 'Untitled Broadcast',
499 'description': info
.get('description'),
500 'duration': int_or_none(info
.get('lengthSeconds')),
501 'thumbnails': self
._get
_thumbnails
(thumbnail
),
502 'uploader': try_get(info
, lambda x
: x
['owner']['displayName'], str),
503 'uploader_id': try_get(info
, lambda x
: x
['owner']['login'], str),
504 'timestamp': unified_timestamp(info
.get('publishedAt')),
505 'view_count': int_or_none(info
.get('viewCount')),
506 'chapters': list(self
._extract
_chapters
(info
, item_id
)),
511 def _extract_storyboard(self
, item_id
, storyboard_json_url
, duration
):
512 if not duration
or not storyboard_json_url
:
514 spec
= self
._download
_json
(storyboard_json_url
, item_id
, 'Downloading storyboard metadata JSON', fatal
=False) or []
515 # sort from highest quality to lowest
516 # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
517 spec
.sort(key
=lambda x
: int_or_none(x
.get('width')) or 0, reverse
=True)
518 base
= base_url(storyboard_json_url
)
519 for i
, s
in enumerate(spec
):
520 count
= int_or_none(s
.get('count'))
521 images
= s
.get('images')
522 if not (images
and count
):
524 fragment_duration
= duration
/ len(images
)
526 'format_id': f
'sb{i}',
527 'format_note': 'storyboard',
532 'url': urljoin(base
, images
[0]),
533 'width': int_or_none(s
.get('width')),
534 'height': int_or_none(s
.get('height')),
535 'fps': count
/ duration
,
536 'rows': int_or_none(s
.get('rows')),
537 'columns': int_or_none(s
.get('cols')),
539 'url': urljoin(base
, path
),
540 'duration': fragment_duration
,
541 } for path
in images
],
544 def _real_extract(self
, url
):
545 vod_id
= self
._match
_id
(url
)
547 video
= self
._download
_info
(vod_id
)
548 info
= self
._extract
_info
_gql
(video
, vod_id
)
549 access_token
= self
._download
_access
_token
(vod_id
, 'video', 'id')
551 formats
= self
._extract
_twitch
_m
3u8_formats
(
552 'vod', vod_id
, access_token
['value'], access_token
['signature'])
553 formats
.extend(self
._extract
_storyboard
(vod_id
, video
.get('storyboard'), info
.get('duration')))
555 self
._prefer
_source
(formats
)
556 info
['formats'] = formats
558 parsed_url
= urllib
.parse
.urlparse(url
)
559 query
= urllib
.parse
.parse_qs(parsed_url
.query
)
561 info
['start_time'] = parse_duration(query
['t'][0])
563 if info
.get('timestamp') is not None:
564 info
['subtitles'] = {
566 'url': update_url_query(
567 f
'https://api.twitch.tv/v5/videos/{vod_id}/comments', {
568 'client_id': self
._CLIENT
_ID
,
577 def _make_video_result(node
):
578 assert isinstance(node
, dict)
579 video_id
= node
.get('id')
583 '_type': 'url_transparent',
584 'ie_key': TwitchVodIE
.ie_key(),
585 'id': 'v' + video_id
,
586 'url': f
'https://www.twitch.tv/videos/{video_id}',
587 'title': node
.get('title'),
588 'thumbnail': node
.get('previewThumbnailURL'),
589 'duration': float_or_none(node
.get('lengthSeconds')),
590 'view_count': int_or_none(node
.get('viewCount')),
594 class TwitchCollectionIE(TwitchBaseIE
):
595 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
598 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
600 'id': 'wlDCoH0zEBZZbQ',
601 'title': 'Overthrow Nook, capitalism for children',
603 'playlist_mincount': 13,
606 _OPERATION_NAME
= 'CollectionSideBar'
608 def _real_extract(self
, url
):
609 collection_id
= self
._match
_id
(url
)
610 collection
= self
._download
_gql
(
612 'operationName': self
._OPERATION
_NAME
,
613 'variables': {'collectionID': collection_id
},
615 'Downloading collection GraphQL')[0]['data']['collection']
616 title
= collection
.get('title')
618 for edge
in collection
['items']['edges']:
619 if not isinstance(edge
, dict):
621 node
= edge
.get('node')
622 if not isinstance(node
, dict):
624 video
= _make_video_result(node
)
626 entries
.append(video
)
627 return self
.playlist_result(
628 entries
, playlist_id
=collection_id
, playlist_title
=title
)
631 class TwitchPlaylistBaseIE(TwitchBaseIE
):
634 def _entries(self
, channel_name
, *args
):
636 variables_common
= self
._make
_variables
(channel_name
, *args
)
637 entries_key
= f
'{self._ENTRY_KIND}s'
638 for page_num
in itertools
.count(1):
639 variables
= variables_common
.copy()
640 variables
['limit'] = self
._PAGE
_LIMIT
642 variables
['cursor'] = cursor
643 page
= self
._download
_gql
(
645 'operationName': self
._OPERATION
_NAME
,
646 'variables': variables
,
648 f
'Downloading {self._NODE_KIND}s GraphQL page {page_num}',
653 page
, lambda x
: x
[0]['data']['user'][entries_key
]['edges'], list)
657 if not isinstance(edge
, dict):
659 if edge
.get('__typename') != self
._EDGE
_KIND
:
661 node
= edge
.get('node')
662 if not isinstance(node
, dict):
664 if node
.get('__typename') != self
._NODE
_KIND
:
666 entry
= self
._extract
_entry
(node
)
668 cursor
= edge
.get('cursor')
670 if not cursor
or not isinstance(cursor
, str):
674 class TwitchVideosIE(TwitchPlaylistBaseIE
):
675 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
678 # All Videos sorted by Date
679 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
682 'title': 'spamfish - All Videos sorted by Date',
684 'playlist_mincount': 924,
686 # All Videos sorted by Popular
687 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
690 'title': 'spamfish - All Videos sorted by Popular',
692 'playlist_mincount': 931,
694 # Past Broadcasts sorted by Date
695 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
698 'title': 'spamfish - Past Broadcasts sorted by Date',
700 'playlist_mincount': 27,
702 # Highlights sorted by Date
703 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
706 'title': 'spamfish - Highlights sorted by Date',
708 'playlist_mincount': 901,
710 # Uploads sorted by Date
711 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
714 'title': 'esl_csgo - Uploads sorted by Date',
716 'playlist_mincount': 5,
718 # Past Premieres sorted by Date
719 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
722 'title': 'spamfish - Past Premieres sorted by Date',
724 'playlist_mincount': 1,
726 'url': 'https://www.twitch.tv/spamfish/videos/all',
727 'only_matching': True,
729 'url': 'https://m.twitch.tv/spamfish/videos/all',
730 'only_matching': True,
732 'url': 'https://www.twitch.tv/spamfish/videos',
733 'only_matching': True,
736 Broadcast
= collections
.namedtuple('Broadcast', ['type', 'label'])
738 _DEFAULT_BROADCAST
= Broadcast(None, 'All Videos')
740 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
741 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
742 'uploads': Broadcast('UPLOAD', 'Uploads'),
743 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
744 'all': _DEFAULT_BROADCAST
,
747 _DEFAULT_SORTED_BY
= 'Date'
749 'time': _DEFAULT_SORTED_BY
,
753 _OPERATION_NAME
= 'FilterableVideoTower_Videos'
754 _ENTRY_KIND
= 'video'
755 _EDGE_KIND
= 'VideoEdge'
759 def suitable(cls
, url
):
761 if any(ie
.suitable(url
) for ie
in (
763 TwitchVideosCollectionsIE
))
764 else super().suitable(url
))
767 def _make_variables(channel_name
, broadcast_type
, sort
):
769 'channelOwnerLogin': channel_name
,
770 'broadcastType': broadcast_type
,
771 'videoSort': sort
.upper(),
775 def _extract_entry(node
):
776 return _make_video_result(node
)
778 def _real_extract(self
, url
):
779 channel_name
= self
._match
_id
(url
)
781 video_filter
= qs
.get('filter', ['all'])[0]
782 sort
= qs
.get('sort', ['time'])[0]
783 broadcast
= self
._BROADCASTS
.get(video_filter
, self
._DEFAULT
_BROADCAST
)
784 return self
.playlist_result(
785 self
._entries
(channel_name
, broadcast
.type, sort
),
786 playlist_id
=channel_name
,
788 f
'{channel_name} - {broadcast.label} '
789 f
'sorted by {self._SORTED_BY.get(sort, self._DEFAULT_SORTED_BY)}'))
792 class TwitchVideosClipsIE(TwitchPlaylistBaseIE
):
793 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
797 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
800 'title': 'vanillatv - Clips Top All',
802 'playlist_mincount': 1,
804 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
805 'only_matching': True,
808 Clip
= collections
.namedtuple('Clip', ['filter', 'label'])
810 _DEFAULT_CLIP
= Clip('LAST_WEEK', 'Top 7D')
812 '24hr': Clip('LAST_DAY', 'Top 24H'),
814 '30d': Clip('LAST_MONTH', 'Top 30D'),
815 'all': Clip('ALL_TIME', 'Top All'),
818 # NB: values other than 20 result in skipped videos
821 _OPERATION_NAME
= 'ClipsCards__User'
823 _EDGE_KIND
= 'ClipEdge'
827 def _make_variables(channel_name
, channel_filter
):
829 'login': channel_name
,
831 'filter': channel_filter
,
836 def _extract_entry(node
):
837 assert isinstance(node
, dict)
838 clip_url
= url_or_none(node
.get('url'))
842 '_type': 'url_transparent',
843 'ie_key': TwitchClipsIE
.ie_key(),
844 'id': node
.get('id'),
846 'title': node
.get('title'),
847 'thumbnail': node
.get('thumbnailURL'),
848 'duration': float_or_none(node
.get('durationSeconds')),
849 'timestamp': unified_timestamp(node
.get('createdAt')),
850 'view_count': int_or_none(node
.get('viewCount')),
851 'language': node
.get('language'),
854 def _real_extract(self
, url
):
855 channel_name
= self
._match
_id
(url
)
857 date_range
= qs
.get('range', ['7d'])[0]
858 clip
= self
._RANGE
.get(date_range
, self
._DEFAULT
_CLIP
)
859 return self
.playlist_result(
860 self
._entries
(channel_name
, clip
.filter),
861 playlist_id
=channel_name
,
862 playlist_title
=f
'{channel_name} - Clips {clip.label}')
865 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE
):
866 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
870 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
873 'title': 'spamfish - Collections',
875 'playlist_mincount': 3,
877 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
880 'title': 'monstercat - Collections',
882 'playlist_mincount': 13,
885 _OPERATION_NAME
= 'ChannelCollectionsContent'
886 _ENTRY_KIND
= 'collection'
887 _EDGE_KIND
= 'CollectionsItemEdge'
888 _NODE_KIND
= 'Collection'
891 def _make_variables(channel_name
):
893 'ownerLogin': channel_name
,
897 def _extract_entry(node
):
898 assert isinstance(node
, dict)
899 collection_id
= node
.get('id')
900 if not collection_id
:
903 '_type': 'url_transparent',
904 'ie_key': TwitchCollectionIE
.ie_key(),
906 'url': f
'https://www.twitch.tv/collections/{collection_id}',
907 'title': node
.get('title'),
908 'thumbnail': node
.get('thumbnailURL'),
909 'duration': float_or_none(node
.get('lengthSeconds')),
910 'timestamp': unified_timestamp(node
.get('updatedAt')),
911 'view_count': int_or_none(node
.get('viewCount')),
914 def _real_extract(self
, url
):
915 channel_name
= self
._match
_id
(url
)
916 return self
.playlist_result(
917 self
._entries
(channel_name
), playlist_id
=channel_name
,
918 playlist_title
=f
'{channel_name} - Collections')
921 class TwitchStreamIE(TwitchBaseIE
):
922 IE_NAME
= 'twitch:stream'
923 _VALID_URL
= r
'''(?x)
926 (?:(?:www|go|m)\.)?twitch\.tv/|
927 player\.twitch\.tv/\?.*?\bchannel=
933 'url': 'http://www.twitch.tv/shroomztv',
936 'display_id': 'shroomztv',
938 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
939 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
941 'timestamp': 1421928037,
942 'upload_date': '20150122',
943 'uploader': 'ShroomzTV',
944 'uploader_id': 'shroomztv',
949 'skip_download': True,
951 'skip': 'User does not exist',
953 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
954 'only_matching': True,
956 'url': 'https://player.twitch.tv/?channel=lotsofs',
957 'only_matching': True,
959 'url': 'https://go.twitch.tv/food',
960 'only_matching': True,
962 'url': 'https://m.twitch.tv/food',
963 'only_matching': True,
965 'url': 'https://www.twitch.tv/monstercat',
968 'display_id': 'monstercat',
969 'title': 're:Monstercat',
970 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
972 'timestamp': 1677107190,
973 'upload_date': '20230222',
974 'uploader': 'Monstercat',
975 'uploader_id': 'monstercat',
976 'live_status': 'is_live',
977 'thumbnail': 're:https://.*.jpg',
981 'skip_download': 'Livestream',
986 def suitable(cls
, url
):
988 if any(ie
.suitable(url
) for ie
in (
993 TwitchVideosCollectionsIE
,
995 else super().suitable(url
))
997 def _real_extract(self
, url
):
998 channel_name
= self
._match
_id
(url
).lower()
1000 gql
= self
._download
_gql
(
1002 'operationName': 'StreamMetadata',
1003 'variables': {'channelLogin': channel_name
},
1005 'operationName': 'ComscoreStreamingQuery',
1007 'channel': channel_name
,
1011 'isVodOrCollection': False,
1015 'operationName': 'VideoPreviewOverlay',
1016 'variables': {'login': channel_name
},
1018 'Downloading stream GraphQL')
1020 user
= gql
[0]['data']['user']
1023 raise ExtractorError(
1024 f
'{channel_name} does not exist', expected
=True)
1026 stream
= user
['stream']
1029 raise UserNotLive(video_id
=channel_name
)
1031 access_token
= self
._download
_access
_token
(
1032 channel_name
, 'stream', 'channelName')
1034 stream_id
= stream
.get('id') or channel_name
1035 formats
= self
._extract
_twitch
_m
3u8_formats
(
1036 'api/channel/hls', channel_name
, access_token
['value'], access_token
['signature'])
1037 self
._prefer
_source
(formats
)
1039 view_count
= stream
.get('viewers')
1040 timestamp
= unified_timestamp(stream
.get('createdAt'))
1042 sq_user
= try_get(gql
, lambda x
: x
[1]['data']['user'], dict) or {}
1043 uploader
= sq_user
.get('displayName')
1044 description
= try_get(
1045 sq_user
, lambda x
: x
['broadcastSettings']['title'], str)
1047 thumbnail
= url_or_none(try_get(
1048 gql
, lambda x
: x
[2]['data']['user']['stream']['previewImageURL'],
1051 title
= uploader
or channel_name
1052 stream_type
= stream
.get('type')
1053 if stream_type
in ['rerun', 'live']:
1054 title
+= f
' ({stream_type})'
1058 'display_id': channel_name
,
1060 'description': description
,
1061 'thumbnails': self
._get
_thumbnails
(thumbnail
),
1062 'uploader': uploader
,
1063 'uploader_id': channel_name
,
1064 'timestamp': timestamp
,
1065 'view_count': view_count
,
1067 'is_live': stream_type
== 'live',
1071 class TwitchClipsIE(TwitchBaseIE
):
1072 IE_NAME
= 'twitch:clips'
1073 _VALID_URL
= r
'''(?x)
1076 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
1077 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/)?clip/
1083 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
1084 'md5': '761769e1eafce0ffebfb4089cb3847cd',
1087 'display_id': 'FaintLightGullWholeWheat',
1089 'title': 'EA Play 2016 Live from the Novo Theatre',
1090 'thumbnail': r
're:^https?://.*\.jpg',
1091 'timestamp': 1465767393,
1092 'upload_date': '20160612',
1094 'uploader': 'stereotype_',
1095 'uploader_id': '43566419',
1099 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
1100 'only_matching': True,
1102 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
1103 'only_matching': True,
1105 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
1106 'only_matching': True,
1108 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1109 'only_matching': True,
1111 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1112 'only_matching': True,
1114 'url': 'https://m.twitch.tv/clip/FaintLightGullWholeWheat',
1115 'only_matching': True,
1118 def _real_extract(self
, url
):
1119 video_id
= self
._match
_id
(url
)
1121 clip
= self
._download
_gql
(
1123 'operationName': 'VideoAccessToken_Clip',
1128 'Downloading clip access token GraphQL')[0]['data']['clip']
1131 raise ExtractorError(
1132 'This clip is no longer available', expected
=True)
1135 'sig': clip
['playbackAccessToken']['signature'],
1136 'token': clip
['playbackAccessToken']['value'],
1139 data
= self
._download
_base
_gql
(
1153 tiny: thumbnailURL(width: 86, height: 45)
1154 small: thumbnailURL(width: 260, height: 147)
1155 medium: thumbnailURL(width: 480, height: 272)
1164 }''' % video_id
}, 'Downloading clip GraphQL', fatal
=False) # noqa: UP031
1167 clip
= try_get(data
, lambda x
: x
['data']['clip'], dict) or clip
1170 for option
in clip
.get('videoQualities', []):
1171 if not isinstance(option
, dict):
1173 source
= url_or_none(option
.get('sourceURL'))
1177 'url': update_url_query(source
, access_query
),
1178 'format_id': option
.get('quality'),
1179 'height': int_or_none(option
.get('quality')),
1180 'fps': int_or_none(option
.get('frameRate')),
1184 for thumbnail_id
in ('tiny', 'small', 'medium'):
1185 thumbnail_url
= clip
.get(thumbnail_id
)
1186 if not thumbnail_url
:
1190 'url': thumbnail_url
,
1192 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
1195 'height': int(mobj
.group(2)),
1196 'width': int(mobj
.group(1)),
1198 thumbnails
.append(thumb
)
1200 old_id
= self
._search
_regex
(r
'%7C(\d+)(?:-\d+)?.mp4', formats
[-1]['url'], 'old id', default
=None)
1203 'id': clip
.get('id') or video_id
,
1204 '_old_archive_ids': [make_archive_id(self
, old_id
)] if old_id
else None,
1205 'display_id': video_id
,
1206 'title': clip
.get('title'),
1208 'duration': int_or_none(clip
.get('durationSeconds')),
1209 'view_count': int_or_none(clip
.get('viewCount')),
1210 'timestamp': unified_timestamp(clip
.get('createdAt')),
1211 'thumbnails': thumbnails
,
1212 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], str),
1213 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], str),
1214 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], str),