7 from .common
import InfoExtractor
11 compat_urllib_parse_urlparse
,
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'
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',
61 return self
._configuration
_arg
(
62 'client_id', ['ue6666qo983tsx6so1t0vnawi233wa'], ie_key
='Twitch', casesense
=True)[0]
64 def _perform_login(self
, username
, password
):
67 'Unable to login. Twitch said: %s' % message
, expected
=True)
69 def login_step(page
, urlh
, note
, data
):
70 form
= self
._hidden
_inputs
(page
)
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)
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
'))
92 if 'Authenticated successfully
' in response.get('message
', ''):
95 redirect_url = urljoin(
97 response.get('redirect
') or response['redirect_path
'])
98 return self._download_webpage_handle(
99 redirect_url, None, 'Downloading login redirect page
',
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,
117 if not redirect_page:
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):
130 source = next(f for f in formats if f['format_id
'] == 'Source
')
131 source['quality
'] = 10
132 except StopIteration:
134 if '/chunked
/' in f['url
']:
137 'format_note
': 'Source
',
140 def _download_base_gql(self, video_id, ops, note, fatal=True):
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
')
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):
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
171 playerBackend: "mediaplayer",
179 }''' % (method, param_name, video_id),
181 return self._download_base_gql(
183 'Downloading
%s access token GraphQL
' % token_kind)['data
'][method]
185 def _get_thumbnails(self, thumbnail):
187 'url
': re.sub(r'\d
+x\d
+(\
.\w
+)($|
(?
=[?
#]))', r'0x0\g<1>', thumbnail),
191 }] if thumbnail
else None
193 def _extract_twitch_m3u8_formats(self
, path
, video_id
, token
, signature
):
194 formats
= self
._extract
_m
3u8_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),
201 'player': 'twitchweb',
202 'supported_codecs': 'av1,h265,h264',
203 'playlist_include_framerate': 'true',
208 if fmt
.get('vcodec') and fmt
['vcodec'].startswith('av01'):
209 # mpegts does not yet have proper support for av1
210 fmt
['downloader_options'] = {'ffmpeg_args_out': ['-f', 'mp4']}
215 class TwitchVodIE(TwitchBaseIE
):
216 IE_NAME
= 'twitch:vod'
217 _VALID_URL
= r
'''(?x)
220 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
221 player\.twitch\.tv/\?.*?\bvideo=v?|
222 www\.twitch\.tv/[^/]+/schedule\?vodID=
228 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
232 'title': 'LCK Summer Split - Week 6 Day 1',
233 'thumbnail': r
're:^https?://.*\.jpg$',
235 'timestamp': 1435131734,
236 'upload_date': '20150624',
237 'uploader': 'Riot Games',
238 'uploader_id': 'riotgames',
245 'title': 'League of Legends'
248 'live_status': 'was_live',
252 'skip_download': True,
255 # Untitled broadcast (title is None)
256 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
260 'title': 'Untitled Broadcast',
261 'thumbnail': r
're:^https?://.*\.jpg$',
263 'timestamp': 1439746708,
264 'upload_date': '20150816',
265 'uploader': 'BelkAO_o',
266 'uploader_id': 'belkao_o',
271 'skip_download': True,
273 'skip': 'HTTP Error 404: Not Found',
275 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
276 'only_matching': True,
278 'url': 'https://www.twitch.tv/videos/6528877',
279 'only_matching': True,
281 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
282 'only_matching': True,
284 'url': 'https://www.twitch.tv/northernlion/video/291940395',
285 'only_matching': True,
287 'url': 'https://player.twitch.tv/?video=480452374',
288 'only_matching': True,
290 'url': 'https://www.twitch.tv/videos/635475444',
294 'title': 'Riot Games',
296 'uploader': 'Riot Games',
297 'uploader_id': 'riotgames',
298 'timestamp': 1590770569,
299 'upload_date': '20200529',
304 'title': 'League of Legends'
309 'title': 'Legends of Runeterra'
317 'live_status': 'was_live',
318 'thumbnail': r
're:^https?://.*\.jpg$',
322 'skip_download': True
325 'note': 'Storyboards',
326 'url': 'https://www.twitch.tv/videos/635475444',
331 'title': 'Riot Games',
333 'uploader': 'Riot Games',
334 'uploader_id': 'riotgames',
335 'timestamp': 1590770569,
336 'upload_date': '20200529',
341 'title': 'League of Legends'
346 'title': 'Legends of Runeterra'
354 'live_status': 'was_live',
355 'thumbnail': r
're:^https?://.*\.jpg$',
362 'skip_download': True
365 'note': 'VOD with single chapter',
366 'url': 'https://www.twitch.tv/videos/1536751224',
370 'title': 'Porter Robinson Star Guardian Stream Tour with LilyPichu',
372 'uploader': 'Riot Games',
373 'uploader_id': 'riotgames',
374 'timestamp': 1658267731,
375 'upload_date': '20220719',
380 'title': 'League of Legends'
383 'live_status': 'was_live',
384 'thumbnail': r
're:^https?://.*\.jpg$',
388 'skip_download': True
390 'expected_warnings': ['Unable to download JSON metadata: HTTP Error 403: Forbidden']
392 'url': 'https://www.twitch.tv/tangotek/schedule?vodID=1822395420',
393 'only_matching': True,
396 def _download_info(self
, item_id
):
397 data
= self
._download
_gql
(
399 'operationName': 'VideoMetadata',
405 'operationName': 'VideoPlayer_ChapterSelectButtonVideo',
407 'includePrivate': False,
411 'operationName': 'VideoPlayer_VODSeekbarPreviewVideo',
413 'includePrivate': False,
417 'Downloading stream metadata GraphQL')
419 video
= traverse_obj(data
, (..., 'data', 'video'), get_all
=False)
421 raise ExtractorError(f
'Video {item_id} does not exist', expected
=True)
423 video
['moments'] = traverse_obj(data
, (..., 'data', 'video', 'moments', 'edges', ..., 'node'))
424 video
['storyboard'] = traverse_obj(
425 data
, (..., 'data', 'video', 'seekPreviewsURL', {url_or_none}
), get_all
=False)
429 def _extract_info(self
, info
):
430 status
= info
.get('status')
431 if status
== 'recording':
433 elif status
== 'recorded':
437 _QUALITIES
= ('small', 'medium', 'large')
438 quality_key
= qualities(_QUALITIES
)
440 preview
= info
.get('preview')
441 if isinstance(preview
, dict):
442 for thumbnail_id
, thumbnail_url
in preview
.items():
443 thumbnail_url
= url_or_none(thumbnail_url
)
444 if not thumbnail_url
:
446 if thumbnail_id
not in _QUALITIES
:
449 'url': thumbnail_url
,
450 'preference': quality_key(thumbnail_id
),
454 'title': info
.get('title') or 'Untitled Broadcast',
455 'description': info
.get('description'),
456 'duration': int_or_none(info
.get('length')),
457 'thumbnails': thumbnails
,
458 'uploader': info
.get('channel', {}).get('display_name'),
459 'uploader_id': info
.get('channel', {}).get('name'),
460 'timestamp': parse_iso8601(info
.get('recorded_at')),
461 'view_count': int_or_none(info
.get('views')),
466 def _extract_chapters(self
, info
, item_id
):
467 if not info
.get('moments'):
468 game
= traverse_obj(info
, ('game', 'displayName'))
470 yield {'title': game}
473 for moment
in info
['moments']:
474 start_time
= int_or_none(moment
.get('positionMilliseconds'), 1000)
475 duration
= int_or_none(moment
.get('durationMilliseconds'), 1000)
476 name
= str_or_none(moment
.get('description'))
478 if start_time
is None or duration
is None:
479 self
.report_warning(f
'Important chapter information missing for chapter {name}', item_id
)
482 'start_time': start_time
,
483 'end_time': start_time
+ duration
,
487 def _extract_info_gql(self
, info
, item_id
):
488 vod_id
= info
.get('id') or item_id
489 # id backward compatibility for download archives
491 vod_id
= 'v%s' % vod_id
492 thumbnail
= url_or_none(info
.get('previewThumbnailURL'))
495 if re
.findall(r
'/404_processing_[^.?#]+\.png', thumbnail
):
496 is_live
, thumbnail
= True, None
502 'title': info
.get('title') or 'Untitled Broadcast',
503 'description': info
.get('description'),
504 'duration': int_or_none(info
.get('lengthSeconds')),
505 'thumbnails': self
._get
_thumbnails
(thumbnail
),
506 'uploader': try_get(info
, lambda x
: x
['owner']['displayName'], compat_str
),
507 'uploader_id': try_get(info
, lambda x
: x
['owner']['login'], compat_str
),
508 'timestamp': unified_timestamp(info
.get('publishedAt')),
509 'view_count': int_or_none(info
.get('viewCount')),
510 'chapters': list(self
._extract
_chapters
(info
, item_id
)),
515 def _extract_storyboard(self
, item_id
, storyboard_json_url
, duration
):
516 if not duration
or not storyboard_json_url
:
518 spec
= self
._download
_json
(storyboard_json_url
, item_id
, 'Downloading storyboard metadata JSON', fatal
=False) or []
519 # sort from highest quality to lowest
520 # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
521 spec
.sort(key
=lambda x
: int_or_none(x
.get('width')) or 0, reverse
=True)
522 base
= base_url(storyboard_json_url
)
523 for i
, s
in enumerate(spec
):
524 count
= int_or_none(s
.get('count'))
525 images
= s
.get('images')
526 if not (images
and count
):
528 fragment_duration
= duration
/ len(images
)
530 'format_id': f
'sb{i}',
531 'format_note': 'storyboard',
536 'url': urljoin(base
, images
[0]),
537 'width': int_or_none(s
.get('width')),
538 'height': int_or_none(s
.get('height')),
539 'fps': count
/ duration
,
540 'rows': int_or_none(s
.get('rows')),
541 'columns': int_or_none(s
.get('cols')),
543 'url': urljoin(base
, path
),
544 'duration': fragment_duration
,
545 } for path
in images
],
548 def _real_extract(self
, url
):
549 vod_id
= self
._match
_id
(url
)
551 video
= self
._download
_info
(vod_id
)
552 info
= self
._extract
_info
_gql
(video
, vod_id
)
553 access_token
= self
._download
_access
_token
(vod_id
, 'video', 'id')
555 formats
= self
._extract
_twitch
_m
3u8_formats
(
556 'vod', vod_id
, access_token
['value'], access_token
['signature'])
557 formats
.extend(self
._extract
_storyboard
(vod_id
, video
.get('storyboard'), info
.get('duration')))
559 self
._prefer
_source
(formats
)
560 info
['formats'] = formats
562 parsed_url
= compat_urllib_parse_urlparse(url
)
563 query
= compat_parse_qs(parsed_url
.query
)
565 info
['start_time'] = parse_duration(query
['t'][0])
567 if info
.get('timestamp') is not None:
568 info
['subtitles'] = {
570 'url': update_url_query(
571 'https://api.twitch.tv/v5/videos/%s/comments' % vod_id
, {
572 'client_id': self
._CLIENT
_ID
,
581 def _make_video_result(node
):
582 assert isinstance(node
, dict)
583 video_id
= node
.get('id')
587 '_type': 'url_transparent',
588 'ie_key': TwitchVodIE
.ie_key(),
589 'id': 'v' + video_id
,
590 'url': 'https://www.twitch.tv/videos/%s' % video_id
,
591 'title': node
.get('title'),
592 'thumbnail': node
.get('previewThumbnailURL'),
593 'duration': float_or_none(node
.get('lengthSeconds')),
594 'view_count': int_or_none(node
.get('viewCount')),
598 class TwitchCollectionIE(TwitchBaseIE
):
599 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
602 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
604 'id': 'wlDCoH0zEBZZbQ',
605 'title': 'Overthrow Nook, capitalism for children',
607 'playlist_mincount': 13,
610 _OPERATION_NAME
= 'CollectionSideBar'
612 def _real_extract(self
, url
):
613 collection_id
= self
._match
_id
(url
)
614 collection
= self
._download
_gql
(
616 'operationName': self
._OPERATION
_NAME
,
617 'variables': {'collectionID': collection_id}
,
619 'Downloading collection GraphQL')[0]['data']['collection']
620 title
= collection
.get('title')
622 for edge
in collection
['items']['edges']:
623 if not isinstance(edge
, dict):
625 node
= edge
.get('node')
626 if not isinstance(node
, dict):
628 video
= _make_video_result(node
)
630 entries
.append(video
)
631 return self
.playlist_result(
632 entries
, playlist_id
=collection_id
, playlist_title
=title
)
635 class TwitchPlaylistBaseIE(TwitchBaseIE
):
638 def _entries(self
, channel_name
, *args
):
640 variables_common
= self
._make
_variables
(channel_name
, *args
)
641 entries_key
= '%ss' % self
._ENTRY
_KIND
642 for page_num
in itertools
.count(1):
643 variables
= variables_common
.copy()
644 variables
['limit'] = self
._PAGE
_LIMIT
646 variables
['cursor'] = cursor
647 page
= self
._download
_gql
(
649 'operationName': self
._OPERATION
_NAME
,
650 'variables': variables
,
652 'Downloading %ss GraphQL page %s' % (self
._NODE
_KIND
, page_num
),
657 page
, lambda x
: x
[0]['data']['user'][entries_key
]['edges'], list)
661 if not isinstance(edge
, dict):
663 if edge
.get('__typename') != self
._EDGE
_KIND
:
665 node
= edge
.get('node')
666 if not isinstance(node
, dict):
668 if node
.get('__typename') != self
._NODE
_KIND
:
670 entry
= self
._extract
_entry
(node
)
672 cursor
= edge
.get('cursor')
674 if not cursor
or not isinstance(cursor
, compat_str
):
678 class TwitchVideosIE(TwitchPlaylistBaseIE
):
679 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
682 # All Videos sorted by Date
683 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
686 'title': 'spamfish - All Videos sorted by Date',
688 'playlist_mincount': 924,
690 # All Videos sorted by Popular
691 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
694 'title': 'spamfish - All Videos sorted by Popular',
696 'playlist_mincount': 931,
698 # Past Broadcasts sorted by Date
699 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
702 'title': 'spamfish - Past Broadcasts sorted by Date',
704 'playlist_mincount': 27,
706 # Highlights sorted by Date
707 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
710 'title': 'spamfish - Highlights sorted by Date',
712 'playlist_mincount': 901,
714 # Uploads sorted by Date
715 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
718 'title': 'esl_csgo - Uploads sorted by Date',
720 'playlist_mincount': 5,
722 # Past Premieres sorted by Date
723 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
726 'title': 'spamfish - Past Premieres sorted by Date',
728 'playlist_mincount': 1,
730 'url': 'https://www.twitch.tv/spamfish/videos/all',
731 'only_matching': True,
733 'url': 'https://m.twitch.tv/spamfish/videos/all',
734 'only_matching': True,
736 'url': 'https://www.twitch.tv/spamfish/videos',
737 'only_matching': True,
740 Broadcast
= collections
.namedtuple('Broadcast', ['type', 'label'])
742 _DEFAULT_BROADCAST
= Broadcast(None, 'All Videos')
744 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
745 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
746 'uploads': Broadcast('UPLOAD', 'Uploads'),
747 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
748 'all': _DEFAULT_BROADCAST
,
751 _DEFAULT_SORTED_BY
= 'Date'
753 'time': _DEFAULT_SORTED_BY
,
757 _OPERATION_NAME
= 'FilterableVideoTower_Videos'
758 _ENTRY_KIND
= 'video'
759 _EDGE_KIND
= 'VideoEdge'
763 def suitable(cls
, url
):
765 if any(ie
.suitable(url
) for ie
in (
767 TwitchVideosCollectionsIE
))
768 else super(TwitchVideosIE
, cls
).suitable(url
))
771 def _make_variables(channel_name
, broadcast_type
, sort
):
773 'channelOwnerLogin': channel_name
,
774 'broadcastType': broadcast_type
,
775 'videoSort': sort
.upper(),
779 def _extract_entry(node
):
780 return _make_video_result(node
)
782 def _real_extract(self
, url
):
783 channel_name
= self
._match
_id
(url
)
785 filter = qs
.get('filter', ['all'])[0]
786 sort
= qs
.get('sort', ['time'])[0]
787 broadcast
= self
._BROADCASTS
.get(filter, self
._DEFAULT
_BROADCAST
)
788 return self
.playlist_result(
789 self
._entries
(channel_name
, broadcast
.type, sort
),
790 playlist_id
=channel_name
,
791 playlist_title
='%s - %s sorted by %s'
792 % (channel_name
, broadcast
.label
,
793 self
._SORTED
_BY
.get(sort
, self
._DEFAULT
_SORTED
_BY
)))
796 class TwitchVideosClipsIE(TwitchPlaylistBaseIE
):
797 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
801 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
804 'title': 'vanillatv - Clips Top All',
806 'playlist_mincount': 1,
808 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
809 'only_matching': True,
812 Clip
= collections
.namedtuple('Clip', ['filter', 'label'])
814 _DEFAULT_CLIP
= Clip('LAST_WEEK', 'Top 7D')
816 '24hr': Clip('LAST_DAY', 'Top 24H'),
818 '30d': Clip('LAST_MONTH', 'Top 30D'),
819 'all': Clip('ALL_TIME', 'Top All'),
822 # NB: values other than 20 result in skipped videos
825 _OPERATION_NAME
= 'ClipsCards__User'
827 _EDGE_KIND
= 'ClipEdge'
831 def _make_variables(channel_name
, filter):
833 'login': channel_name
,
840 def _extract_entry(node
):
841 assert isinstance(node
, dict)
842 clip_url
= url_or_none(node
.get('url'))
846 '_type': 'url_transparent',
847 'ie_key': TwitchClipsIE
.ie_key(),
848 'id': node
.get('id'),
850 'title': node
.get('title'),
851 'thumbnail': node
.get('thumbnailURL'),
852 'duration': float_or_none(node
.get('durationSeconds')),
853 'timestamp': unified_timestamp(node
.get('createdAt')),
854 'view_count': int_or_none(node
.get('viewCount')),
855 'language': node
.get('language'),
858 def _real_extract(self
, url
):
859 channel_name
= self
._match
_id
(url
)
861 range = qs
.get('range', ['7d'])[0]
862 clip
= self
._RANGE
.get(range, self
._DEFAULT
_CLIP
)
863 return self
.playlist_result(
864 self
._entries
(channel_name
, clip
.filter),
865 playlist_id
=channel_name
,
866 playlist_title
='%s - Clips %s' % (channel_name
, clip
.label
))
869 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE
):
870 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
874 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
877 'title': 'spamfish - Collections',
879 'playlist_mincount': 3,
881 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
884 'title': 'monstercat - Collections',
886 'playlist_mincount': 13,
889 _OPERATION_NAME
= 'ChannelCollectionsContent'
890 _ENTRY_KIND
= 'collection'
891 _EDGE_KIND
= 'CollectionsItemEdge'
892 _NODE_KIND
= 'Collection'
895 def _make_variables(channel_name
):
897 'ownerLogin': channel_name
,
901 def _extract_entry(node
):
902 assert isinstance(node
, dict)
903 collection_id
= node
.get('id')
904 if not collection_id
:
907 '_type': 'url_transparent',
908 'ie_key': TwitchCollectionIE
.ie_key(),
910 'url': 'https://www.twitch.tv/collections/%s' % collection_id
,
911 'title': node
.get('title'),
912 'thumbnail': node
.get('thumbnailURL'),
913 'duration': float_or_none(node
.get('lengthSeconds')),
914 'timestamp': unified_timestamp(node
.get('updatedAt')),
915 'view_count': int_or_none(node
.get('viewCount')),
918 def _real_extract(self
, url
):
919 channel_name
= self
._match
_id
(url
)
920 return self
.playlist_result(
921 self
._entries
(channel_name
), playlist_id
=channel_name
,
922 playlist_title
='%s - Collections' % channel_name
)
925 class TwitchStreamIE(TwitchBaseIE
):
926 IE_NAME
= 'twitch:stream'
927 _VALID_URL
= r
'''(?x)
930 (?:(?:www|go|m)\.)?twitch\.tv/|
931 player\.twitch\.tv/\?.*?\bchannel=
937 'url': 'http://www.twitch.tv/shroomztv',
940 'display_id': 'shroomztv',
942 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
943 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
945 'timestamp': 1421928037,
946 'upload_date': '20150122',
947 'uploader': 'ShroomzTV',
948 'uploader_id': 'shroomztv',
953 'skip_download': True,
955 'skip': 'User does not exist',
957 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
958 'only_matching': True,
960 'url': 'https://player.twitch.tv/?channel=lotsofs',
961 'only_matching': True,
963 'url': 'https://go.twitch.tv/food',
964 'only_matching': True,
966 'url': 'https://m.twitch.tv/food',
967 'only_matching': True,
969 'url': 'https://www.twitch.tv/monstercat',
972 'display_id': 'monstercat',
973 'title': 're:Monstercat',
974 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
976 'timestamp': 1677107190,
977 'upload_date': '20230222',
978 'uploader': 'Monstercat',
979 'uploader_id': 'monstercat',
980 'live_status': 'is_live',
981 'thumbnail': 're:https://.*.jpg',
985 'skip_download': 'Livestream',
990 def suitable(cls
, url
):
992 if any(ie
.suitable(url
) for ie
in (
997 TwitchVideosCollectionsIE
,
999 else super(TwitchStreamIE
, cls
).suitable(url
))
1001 def _real_extract(self
, url
):
1002 channel_name
= self
._match
_id
(url
).lower()
1004 gql
= self
._download
_gql
(
1006 'operationName': 'StreamMetadata',
1007 'variables': {'channelLogin': channel_name}
,
1009 'operationName': 'ComscoreStreamingQuery',
1011 'channel': channel_name
,
1015 'isVodOrCollection': False,
1019 'operationName': 'VideoPreviewOverlay',
1020 'variables': {'login': channel_name}
,
1022 'Downloading stream GraphQL')
1024 user
= gql
[0]['data']['user']
1027 raise ExtractorError(
1028 '%s does not exist' % channel_name
, expected
=True)
1030 stream
= user
['stream']
1033 raise UserNotLive(video_id
=channel_name
)
1035 access_token
= self
._download
_access
_token
(
1036 channel_name
, 'stream', 'channelName')
1038 stream_id
= stream
.get('id') or channel_name
1039 formats
= self
._extract
_twitch
_m
3u8_formats
(
1040 'api/channel/hls', channel_name
, access_token
['value'], access_token
['signature'])
1041 self
._prefer
_source
(formats
)
1043 view_count
= stream
.get('viewers')
1044 timestamp
= unified_timestamp(stream
.get('createdAt'))
1046 sq_user
= try_get(gql
, lambda x
: x
[1]['data']['user'], dict) or {}
1047 uploader
= sq_user
.get('displayName')
1048 description
= try_get(
1049 sq_user
, lambda x
: x
['broadcastSettings']['title'], compat_str
)
1051 thumbnail
= url_or_none(try_get(
1052 gql
, lambda x
: x
[2]['data']['user']['stream']['previewImageURL'],
1055 title
= uploader
or channel_name
1056 stream_type
= stream
.get('type')
1057 if stream_type
in ['rerun', 'live']:
1058 title
+= ' (%s)' % stream_type
1062 'display_id': channel_name
,
1064 'description': description
,
1065 'thumbnails': self
._get
_thumbnails
(thumbnail
),
1066 'uploader': uploader
,
1067 'uploader_id': channel_name
,
1068 'timestamp': timestamp
,
1069 'view_count': view_count
,
1071 'is_live': stream_type
== 'live',
1075 class TwitchClipsIE(TwitchBaseIE
):
1076 IE_NAME
= 'twitch:clips'
1077 _VALID_URL
= r
'''(?x)
1080 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
1081 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/)?clip/
1087 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
1088 'md5': '761769e1eafce0ffebfb4089cb3847cd',
1091 'display_id': 'FaintLightGullWholeWheat',
1093 'title': 'EA Play 2016 Live from the Novo Theatre',
1094 'thumbnail': r
're:^https?://.*\.jpg',
1095 'timestamp': 1465767393,
1096 'upload_date': '20160612',
1098 'uploader': 'stereotype_',
1099 'uploader_id': '43566419',
1103 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
1104 'only_matching': True,
1106 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
1107 'only_matching': True,
1109 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
1110 'only_matching': True,
1112 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1113 'only_matching': True,
1115 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1116 'only_matching': True,
1118 'url': 'https://m.twitch.tv/clip/FaintLightGullWholeWheat',
1119 'only_matching': True,
1122 def _real_extract(self
, url
):
1123 video_id
= self
._match
_id
(url
)
1125 clip
= self
._download
_gql
(
1127 'operationName': 'VideoAccessToken_Clip',
1132 'Downloading clip access token GraphQL')[0]['data']['clip']
1135 raise ExtractorError(
1136 'This clip is no longer available', expected
=True)
1139 'sig': clip
['playbackAccessToken']['signature'],
1140 'token': clip
['playbackAccessToken']['value'],
1143 data
= self
._download
_base
_gql
(
1157 tiny: thumbnailURL(width: 86, height: 45)
1158 small: thumbnailURL(width: 260, height: 147)
1159 medium: thumbnailURL(width: 480, height: 272)
1168 }''' % video_id
}, 'Downloading clip GraphQL', fatal
=False)
1171 clip
= try_get(data
, lambda x
: x
['data']['clip'], dict) or clip
1174 for option
in clip
.get('videoQualities', []):
1175 if not isinstance(option
, dict):
1177 source
= url_or_none(option
.get('sourceURL'))
1181 'url': update_url_query(source
, access_query
),
1182 'format_id': option
.get('quality'),
1183 'height': int_or_none(option
.get('quality')),
1184 'fps': int_or_none(option
.get('frameRate')),
1188 for thumbnail_id
in ('tiny', 'small', 'medium'):
1189 thumbnail_url
= clip
.get(thumbnail_id
)
1190 if not thumbnail_url
:
1194 'url': thumbnail_url
,
1196 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
1199 'height': int(mobj
.group(2)),
1200 'width': int(mobj
.group(1)),
1202 thumbnails
.append(thumb
)
1204 old_id
= self
._search
_regex
(r
'%7C(\d+)(?:-\d+)?.mp4', formats
[-1]['url'], 'old id', default
=None)
1207 'id': clip
.get('id') or video_id
,
1208 '_old_archive_ids': [make_archive_id(self
, old_id
)] if old_id
else None,
1209 'display_id': video_id
,
1210 'title': clip
.get('title'),
1212 'duration': int_or_none(clip
.get('durationSeconds')),
1213 'view_count': int_or_none(clip
.get('viewCount')),
1214 'timestamp': unified_timestamp(clip
.get('createdAt')),
1215 'thumbnails': thumbnails
,
1216 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], compat_str
),
1217 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], compat_str
),
1218 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], compat_str
),