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?|
198 www\.twitch\.tv/[^/]+/schedule\?vodID=
204 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
208 'title': 'LCK Summer Split - Week 6 Day 1',
209 'thumbnail': r
're:^https?://.*\.jpg$',
211 'timestamp': 1435131734,
212 'upload_date': '20150624',
213 'uploader': 'Riot Games',
214 'uploader_id': 'riotgames',
221 'title': 'League of Legends'
224 'live_status': 'was_live',
228 'skip_download': True,
231 # Untitled broadcast (title is None)
232 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
236 'title': 'Untitled Broadcast',
237 'thumbnail': r
're:^https?://.*\.jpg$',
239 'timestamp': 1439746708,
240 'upload_date': '20150816',
241 'uploader': 'BelkAO_o',
242 'uploader_id': 'belkao_o',
247 'skip_download': True,
249 'skip': 'HTTP Error 404: Not Found',
251 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
252 'only_matching': True,
254 'url': 'https://www.twitch.tv/videos/6528877',
255 'only_matching': True,
257 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
258 'only_matching': True,
260 'url': 'https://www.twitch.tv/northernlion/video/291940395',
261 'only_matching': True,
263 'url': 'https://player.twitch.tv/?video=480452374',
264 'only_matching': True,
266 'url': 'https://www.twitch.tv/videos/635475444',
270 'title': 'Riot Games',
272 'uploader': 'Riot Games',
273 'uploader_id': 'riotgames',
274 'timestamp': 1590770569,
275 'upload_date': '20200529',
280 'title': 'League of Legends'
285 'title': 'Legends of Runeterra'
293 'live_status': 'was_live',
294 'thumbnail': r
're:^https?://.*\.jpg$',
298 'skip_download': True
301 'note': 'Storyboards',
302 'url': 'https://www.twitch.tv/videos/635475444',
307 'title': 'Riot Games',
309 'uploader': 'Riot Games',
310 'uploader_id': 'riotgames',
311 'timestamp': 1590770569,
312 'upload_date': '20200529',
317 'title': 'League of Legends'
322 'title': 'Legends of Runeterra'
330 'live_status': 'was_live',
331 'thumbnail': r
're:^https?://.*\.jpg$',
338 'skip_download': True
341 'note': 'VOD with single chapter',
342 'url': 'https://www.twitch.tv/videos/1536751224',
346 'title': 'Porter Robinson Star Guardian Stream Tour with LilyPichu',
348 'uploader': 'Riot Games',
349 'uploader_id': 'riotgames',
350 'timestamp': 1658267731,
351 'upload_date': '20220719',
356 'title': 'League of Legends'
359 'live_status': 'was_live',
360 'thumbnail': r
're:^https?://.*\.jpg$',
364 'skip_download': True
366 'expected_warnings': ['Unable to download JSON metadata: HTTP Error 403: Forbidden']
368 'url': 'https://www.twitch.tv/tangotek/schedule?vodID=1822395420',
369 'only_matching': True,
372 def _download_info(self
, item_id
):
373 data
= self
._download
_gql
(
375 'operationName': 'VideoMetadata',
381 'operationName': 'VideoPlayer_ChapterSelectButtonVideo',
383 'includePrivate': False,
387 'operationName': 'VideoPlayer_VODSeekbarPreviewVideo',
389 'includePrivate': False,
393 'Downloading stream metadata GraphQL')
395 video
= traverse_obj(data
, (..., 'data', 'video'), get_all
=False)
397 raise ExtractorError(f
'Video {item_id} does not exist', expected
=True)
399 video
['moments'] = traverse_obj(data
, (..., 'data', 'video', 'moments', 'edges', ..., 'node'))
400 video
['storyboard'] = traverse_obj(
401 data
, (..., 'data', 'video', 'seekPreviewsURL', {url_or_none}
), get_all
=False)
405 def _extract_info(self
, info
):
406 status
= info
.get('status')
407 if status
== 'recording':
409 elif status
== 'recorded':
413 _QUALITIES
= ('small', 'medium', 'large')
414 quality_key
= qualities(_QUALITIES
)
416 preview
= info
.get('preview')
417 if isinstance(preview
, dict):
418 for thumbnail_id
, thumbnail_url
in preview
.items():
419 thumbnail_url
= url_or_none(thumbnail_url
)
420 if not thumbnail_url
:
422 if thumbnail_id
not in _QUALITIES
:
425 'url': thumbnail_url
,
426 'preference': quality_key(thumbnail_id
),
430 'title': info
.get('title') or 'Untitled Broadcast',
431 'description': info
.get('description'),
432 'duration': int_or_none(info
.get('length')),
433 'thumbnails': thumbnails
,
434 'uploader': info
.get('channel', {}).get('display_name'),
435 'uploader_id': info
.get('channel', {}).get('name'),
436 'timestamp': parse_iso8601(info
.get('recorded_at')),
437 'view_count': int_or_none(info
.get('views')),
442 def _extract_chapters(self
, info
, item_id
):
443 if not info
.get('moments'):
444 game
= traverse_obj(info
, ('game', 'displayName'))
446 yield {'title': game}
449 for moment
in info
['moments']:
450 start_time
= int_or_none(moment
.get('positionMilliseconds'), 1000)
451 duration
= int_or_none(moment
.get('durationMilliseconds'), 1000)
452 name
= str_or_none(moment
.get('description'))
454 if start_time
is None or duration
is None:
455 self
.report_warning(f
'Important chapter information missing for chapter {name}', item_id
)
458 'start_time': start_time
,
459 'end_time': start_time
+ duration
,
463 def _extract_info_gql(self
, info
, item_id
):
464 vod_id
= info
.get('id') or item_id
465 # id backward compatibility for download archives
467 vod_id
= 'v%s' % vod_id
468 thumbnail
= url_or_none(info
.get('previewThumbnailURL'))
471 if re
.findall(r
'/404_processing_[^.?#]+\.png', thumbnail
):
472 is_live
, thumbnail
= True, None
478 'title': info
.get('title') or 'Untitled Broadcast',
479 'description': info
.get('description'),
480 'duration': int_or_none(info
.get('lengthSeconds')),
481 'thumbnails': self
._get
_thumbnails
(thumbnail
),
482 'uploader': try_get(info
, lambda x
: x
['owner']['displayName'], compat_str
),
483 'uploader_id': try_get(info
, lambda x
: x
['owner']['login'], compat_str
),
484 'timestamp': unified_timestamp(info
.get('publishedAt')),
485 'view_count': int_or_none(info
.get('viewCount')),
486 'chapters': list(self
._extract
_chapters
(info
, item_id
)),
491 def _extract_storyboard(self
, item_id
, storyboard_json_url
, duration
):
492 if not duration
or not storyboard_json_url
:
494 spec
= self
._download
_json
(storyboard_json_url
, item_id
, 'Downloading storyboard metadata JSON', fatal
=False) or []
495 # sort from highest quality to lowest
496 # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
497 spec
.sort(key
=lambda x
: int_or_none(x
.get('width')) or 0, reverse
=True)
498 base
= base_url(storyboard_json_url
)
499 for i
, s
in enumerate(spec
):
500 count
= int_or_none(s
.get('count'))
501 images
= s
.get('images')
502 if not (images
and count
):
504 fragment_duration
= duration
/ len(images
)
506 'format_id': f
'sb{i}',
507 'format_note': 'storyboard',
512 'url': urljoin(base
, images
[0]),
513 'width': int_or_none(s
.get('width')),
514 'height': int_or_none(s
.get('height')),
515 'fps': count
/ duration
,
516 'rows': int_or_none(s
.get('rows')),
517 'columns': int_or_none(s
.get('cols')),
519 'url': urljoin(base
, path
),
520 'duration': fragment_duration
,
521 } for path
in images
],
524 def _real_extract(self
, url
):
525 vod_id
= self
._match
_id
(url
)
527 video
= self
._download
_info
(vod_id
)
528 info
= self
._extract
_info
_gql
(video
, vod_id
)
529 access_token
= self
._download
_access
_token
(vod_id
, 'video', 'id')
531 formats
= self
._extract
_m
3u8_formats
(
532 '%s/vod/%s.m3u8?%s' % (
533 self
._USHER
_BASE
, vod_id
,
534 compat_urllib_parse_urlencode({
535 'allow_source': 'true',
536 'allow_audio_only': 'true',
537 'allow_spectre': 'true',
538 'player': 'twitchweb',
539 'playlist_include_framerate': 'true',
540 'nauth': access_token
['value'],
541 'nauthsig': access_token
['signature'],
543 vod_id
, 'mp4', entry_protocol
='m3u8_native')
545 formats
.extend(self
._extract
_storyboard
(vod_id
, video
.get('storyboard'), info
.get('duration')))
547 self
._prefer
_source
(formats
)
548 info
['formats'] = formats
550 parsed_url
= compat_urllib_parse_urlparse(url
)
551 query
= compat_parse_qs(parsed_url
.query
)
553 info
['start_time'] = parse_duration(query
['t'][0])
555 if info
.get('timestamp') is not None:
556 info
['subtitles'] = {
558 'url': update_url_query(
559 'https://api.twitch.tv/v5/videos/%s/comments' % vod_id
, {
560 'client_id': self
._CLIENT
_ID
,
569 def _make_video_result(node
):
570 assert isinstance(node
, dict)
571 video_id
= node
.get('id')
575 '_type': 'url_transparent',
576 'ie_key': TwitchVodIE
.ie_key(),
577 'id': 'v' + video_id
,
578 'url': 'https://www.twitch.tv/videos/%s' % video_id
,
579 'title': node
.get('title'),
580 'thumbnail': node
.get('previewThumbnailURL'),
581 'duration': float_or_none(node
.get('lengthSeconds')),
582 'view_count': int_or_none(node
.get('viewCount')),
586 class TwitchCollectionIE(TwitchBaseIE
):
587 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
590 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
592 'id': 'wlDCoH0zEBZZbQ',
593 'title': 'Overthrow Nook, capitalism for children',
595 'playlist_mincount': 13,
598 _OPERATION_NAME
= 'CollectionSideBar'
600 def _real_extract(self
, url
):
601 collection_id
= self
._match
_id
(url
)
602 collection
= self
._download
_gql
(
604 'operationName': self
._OPERATION
_NAME
,
605 'variables': {'collectionID': collection_id}
,
607 'Downloading collection GraphQL')[0]['data']['collection']
608 title
= collection
.get('title')
610 for edge
in collection
['items']['edges']:
611 if not isinstance(edge
, dict):
613 node
= edge
.get('node')
614 if not isinstance(node
, dict):
616 video
= _make_video_result(node
)
618 entries
.append(video
)
619 return self
.playlist_result(
620 entries
, playlist_id
=collection_id
, playlist_title
=title
)
623 class TwitchPlaylistBaseIE(TwitchBaseIE
):
626 def _entries(self
, channel_name
, *args
):
628 variables_common
= self
._make
_variables
(channel_name
, *args
)
629 entries_key
= '%ss' % self
._ENTRY
_KIND
630 for page_num
in itertools
.count(1):
631 variables
= variables_common
.copy()
632 variables
['limit'] = self
._PAGE
_LIMIT
634 variables
['cursor'] = cursor
635 page
= self
._download
_gql
(
637 'operationName': self
._OPERATION
_NAME
,
638 'variables': variables
,
640 'Downloading %ss GraphQL page %s' % (self
._NODE
_KIND
, page_num
),
645 page
, lambda x
: x
[0]['data']['user'][entries_key
]['edges'], list)
649 if not isinstance(edge
, dict):
651 if edge
.get('__typename') != self
._EDGE
_KIND
:
653 node
= edge
.get('node')
654 if not isinstance(node
, dict):
656 if node
.get('__typename') != self
._NODE
_KIND
:
658 entry
= self
._extract
_entry
(node
)
660 cursor
= edge
.get('cursor')
662 if not cursor
or not isinstance(cursor
, compat_str
):
666 class TwitchVideosIE(TwitchPlaylistBaseIE
):
667 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
670 # All Videos sorted by Date
671 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
674 'title': 'spamfish - All Videos sorted by Date',
676 'playlist_mincount': 924,
678 # All Videos sorted by Popular
679 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
682 'title': 'spamfish - All Videos sorted by Popular',
684 'playlist_mincount': 931,
686 # Past Broadcasts sorted by Date
687 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
690 'title': 'spamfish - Past Broadcasts sorted by Date',
692 'playlist_mincount': 27,
694 # Highlights sorted by Date
695 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
698 'title': 'spamfish - Highlights sorted by Date',
700 'playlist_mincount': 901,
702 # Uploads sorted by Date
703 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
706 'title': 'esl_csgo - Uploads sorted by Date',
708 'playlist_mincount': 5,
710 # Past Premieres sorted by Date
711 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
714 'title': 'spamfish - Past Premieres sorted by Date',
716 'playlist_mincount': 1,
718 'url': 'https://www.twitch.tv/spamfish/videos/all',
719 'only_matching': True,
721 'url': 'https://m.twitch.tv/spamfish/videos/all',
722 'only_matching': True,
724 'url': 'https://www.twitch.tv/spamfish/videos',
725 'only_matching': True,
728 Broadcast
= collections
.namedtuple('Broadcast', ['type', 'label'])
730 _DEFAULT_BROADCAST
= Broadcast(None, 'All Videos')
732 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
733 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
734 'uploads': Broadcast('UPLOAD', 'Uploads'),
735 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
736 'all': _DEFAULT_BROADCAST
,
739 _DEFAULT_SORTED_BY
= 'Date'
741 'time': _DEFAULT_SORTED_BY
,
745 _OPERATION_NAME
= 'FilterableVideoTower_Videos'
746 _ENTRY_KIND
= 'video'
747 _EDGE_KIND
= 'VideoEdge'
751 def suitable(cls
, url
):
753 if any(ie
.suitable(url
) for ie
in (
755 TwitchVideosCollectionsIE
))
756 else super(TwitchVideosIE
, cls
).suitable(url
))
759 def _make_variables(channel_name
, broadcast_type
, sort
):
761 'channelOwnerLogin': channel_name
,
762 'broadcastType': broadcast_type
,
763 'videoSort': sort
.upper(),
767 def _extract_entry(node
):
768 return _make_video_result(node
)
770 def _real_extract(self
, url
):
771 channel_name
= self
._match
_id
(url
)
773 filter = qs
.get('filter', ['all'])[0]
774 sort
= qs
.get('sort', ['time'])[0]
775 broadcast
= self
._BROADCASTS
.get(filter, self
._DEFAULT
_BROADCAST
)
776 return self
.playlist_result(
777 self
._entries
(channel_name
, broadcast
.type, sort
),
778 playlist_id
=channel_name
,
779 playlist_title
='%s - %s sorted by %s'
780 % (channel_name
, broadcast
.label
,
781 self
._SORTED
_BY
.get(sort
, self
._DEFAULT
_SORTED
_BY
)))
784 class TwitchVideosClipsIE(TwitchPlaylistBaseIE
):
785 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
789 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
792 'title': 'vanillatv - Clips Top All',
794 'playlist_mincount': 1,
796 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
797 'only_matching': True,
800 Clip
= collections
.namedtuple('Clip', ['filter', 'label'])
802 _DEFAULT_CLIP
= Clip('LAST_WEEK', 'Top 7D')
804 '24hr': Clip('LAST_DAY', 'Top 24H'),
806 '30d': Clip('LAST_MONTH', 'Top 30D'),
807 'all': Clip('ALL_TIME', 'Top All'),
810 # NB: values other than 20 result in skipped videos
813 _OPERATION_NAME
= 'ClipsCards__User'
815 _EDGE_KIND
= 'ClipEdge'
819 def _make_variables(channel_name
, filter):
821 'login': channel_name
,
828 def _extract_entry(node
):
829 assert isinstance(node
, dict)
830 clip_url
= url_or_none(node
.get('url'))
834 '_type': 'url_transparent',
835 'ie_key': TwitchClipsIE
.ie_key(),
836 'id': node
.get('id'),
838 'title': node
.get('title'),
839 'thumbnail': node
.get('thumbnailURL'),
840 'duration': float_or_none(node
.get('durationSeconds')),
841 'timestamp': unified_timestamp(node
.get('createdAt')),
842 'view_count': int_or_none(node
.get('viewCount')),
843 'language': node
.get('language'),
846 def _real_extract(self
, url
):
847 channel_name
= self
._match
_id
(url
)
849 range = qs
.get('range', ['7d'])[0]
850 clip
= self
._RANGE
.get(range, self
._DEFAULT
_CLIP
)
851 return self
.playlist_result(
852 self
._entries
(channel_name
, clip
.filter),
853 playlist_id
=channel_name
,
854 playlist_title
='%s - Clips %s' % (channel_name
, clip
.label
))
857 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE
):
858 _VALID_URL
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
862 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
865 'title': 'spamfish - Collections',
867 'playlist_mincount': 3,
869 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
872 'title': 'monstercat - Collections',
874 'playlist_mincount': 13,
877 _OPERATION_NAME
= 'ChannelCollectionsContent'
878 _ENTRY_KIND
= 'collection'
879 _EDGE_KIND
= 'CollectionsItemEdge'
880 _NODE_KIND
= 'Collection'
883 def _make_variables(channel_name
):
885 'ownerLogin': channel_name
,
889 def _extract_entry(node
):
890 assert isinstance(node
, dict)
891 collection_id
= node
.get('id')
892 if not collection_id
:
895 '_type': 'url_transparent',
896 'ie_key': TwitchCollectionIE
.ie_key(),
898 'url': 'https://www.twitch.tv/collections/%s' % collection_id
,
899 'title': node
.get('title'),
900 'thumbnail': node
.get('thumbnailURL'),
901 'duration': float_or_none(node
.get('lengthSeconds')),
902 'timestamp': unified_timestamp(node
.get('updatedAt')),
903 'view_count': int_or_none(node
.get('viewCount')),
906 def _real_extract(self
, url
):
907 channel_name
= self
._match
_id
(url
)
908 return self
.playlist_result(
909 self
._entries
(channel_name
), playlist_id
=channel_name
,
910 playlist_title
='%s - Collections' % channel_name
)
913 class TwitchStreamIE(TwitchBaseIE
):
914 IE_NAME
= 'twitch:stream'
915 _VALID_URL
= r
'''(?x)
918 (?:(?:www|go|m)\.)?twitch\.tv/|
919 player\.twitch\.tv/\?.*?\bchannel=
925 'url': 'http://www.twitch.tv/shroomztv',
928 'display_id': 'shroomztv',
930 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
931 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
933 'timestamp': 1421928037,
934 'upload_date': '20150122',
935 'uploader': 'ShroomzTV',
936 'uploader_id': 'shroomztv',
941 'skip_download': True,
943 'skip': 'User does not exist',
945 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
946 'only_matching': True,
948 'url': 'https://player.twitch.tv/?channel=lotsofs',
949 'only_matching': True,
951 'url': 'https://go.twitch.tv/food',
952 'only_matching': True,
954 'url': 'https://m.twitch.tv/food',
955 'only_matching': True,
957 'url': 'https://www.twitch.tv/monstercat',
960 'display_id': 'monstercat',
961 'title': 're:Monstercat',
962 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
964 'timestamp': 1677107190,
965 'upload_date': '20230222',
966 'uploader': 'Monstercat',
967 'uploader_id': 'monstercat',
968 'live_status': 'is_live',
969 'thumbnail': 're:https://.*.jpg',
973 'skip_download': 'Livestream',
978 def suitable(cls
, url
):
980 if any(ie
.suitable(url
) for ie
in (
985 TwitchVideosCollectionsIE
,
987 else super(TwitchStreamIE
, cls
).suitable(url
))
989 def _real_extract(self
, url
):
990 channel_name
= self
._match
_id
(url
).lower()
992 gql
= self
._download
_gql
(
994 'operationName': 'StreamMetadata',
995 'variables': {'channelLogin': channel_name}
,
997 'operationName': 'ComscoreStreamingQuery',
999 'channel': channel_name
,
1003 'isVodOrCollection': False,
1007 'operationName': 'VideoPreviewOverlay',
1008 'variables': {'login': channel_name}
,
1010 'Downloading stream GraphQL')
1012 user
= gql
[0]['data']['user']
1015 raise ExtractorError(
1016 '%s does not exist' % channel_name
, expected
=True)
1018 stream
= user
['stream']
1021 raise UserNotLive(video_id
=channel_name
)
1023 access_token
= self
._download
_access
_token
(
1024 channel_name
, 'stream', 'channelName')
1025 token
= access_token
['value']
1027 stream_id
= stream
.get('id') or channel_name
1029 'allow_source': 'true',
1030 'allow_audio_only': 'true',
1031 'allow_spectre': 'true',
1032 'p': random
.randint(1000000, 10000000),
1033 'player': 'twitchweb',
1034 'playlist_include_framerate': 'true',
1035 'segment_preference': '4',
1036 'sig': access_token
['signature'].encode('utf-8'),
1037 'token': token
.encode('utf-8'),
1039 formats
= self
._extract
_m
3u8_formats
(
1040 '%s/api/channel/hls/%s.m3u8' % (self
._USHER
_BASE
, channel_name
),
1041 stream_id
, 'mp4', query
=query
)
1042 self
._prefer
_source
(formats
)
1044 view_count
= stream
.get('viewers')
1045 timestamp
= unified_timestamp(stream
.get('createdAt'))
1047 sq_user
= try_get(gql
, lambda x
: x
[1]['data']['user'], dict) or {}
1048 uploader
= sq_user
.get('displayName')
1049 description
= try_get(
1050 sq_user
, lambda x
: x
['broadcastSettings']['title'], compat_str
)
1052 thumbnail
= url_or_none(try_get(
1053 gql
, lambda x
: x
[2]['data']['user']['stream']['previewImageURL'],
1056 title
= uploader
or channel_name
1057 stream_type
= stream
.get('type')
1058 if stream_type
in ['rerun', 'live']:
1059 title
+= ' (%s)' % stream_type
1063 'display_id': channel_name
,
1065 'description': description
,
1066 'thumbnails': self
._get
_thumbnails
(thumbnail
),
1067 'uploader': uploader
,
1068 'uploader_id': channel_name
,
1069 'timestamp': timestamp
,
1070 'view_count': view_count
,
1072 'is_live': stream_type
== 'live',
1076 class TwitchClipsIE(TwitchBaseIE
):
1077 IE_NAME
= 'twitch:clips'
1078 _VALID_URL
= r
'''(?x)
1081 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
1082 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/)?clip/
1088 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
1089 'md5': '761769e1eafce0ffebfb4089cb3847cd',
1092 'display_id': 'FaintLightGullWholeWheat',
1094 'title': 'EA Play 2016 Live from the Novo Theatre',
1095 'thumbnail': r
're:^https?://.*\.jpg',
1096 'timestamp': 1465767393,
1097 'upload_date': '20160612',
1099 'uploader': 'stereotype_',
1100 'uploader_id': '43566419',
1104 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
1105 'only_matching': True,
1107 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
1108 'only_matching': True,
1110 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
1111 'only_matching': True,
1113 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1114 'only_matching': True,
1116 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1117 'only_matching': True,
1119 'url': 'https://m.twitch.tv/clip/FaintLightGullWholeWheat',
1120 'only_matching': True,
1123 def _real_extract(self
, url
):
1124 video_id
= self
._match
_id
(url
)
1126 clip
= self
._download
_gql
(
1128 'operationName': 'VideoAccessToken_Clip',
1133 'Downloading clip access token GraphQL')[0]['data']['clip']
1136 raise ExtractorError(
1137 'This clip is no longer available', expected
=True)
1140 'sig': clip
['playbackAccessToken']['signature'],
1141 'token': clip
['playbackAccessToken']['value'],
1144 data
= self
._download
_base
_gql
(
1158 tiny: thumbnailURL(width: 86, height: 45)
1159 small: thumbnailURL(width: 260, height: 147)
1160 medium: thumbnailURL(width: 480, height: 272)
1169 }''' % video_id
}, 'Downloading clip GraphQL', fatal
=False)
1172 clip
= try_get(data
, lambda x
: x
['data']['clip'], dict) or clip
1175 for option
in clip
.get('videoQualities', []):
1176 if not isinstance(option
, dict):
1178 source
= url_or_none(option
.get('sourceURL'))
1182 'url': update_url_query(source
, access_query
),
1183 'format_id': option
.get('quality'),
1184 'height': int_or_none(option
.get('quality')),
1185 'fps': int_or_none(option
.get('frameRate')),
1189 for thumbnail_id
in ('tiny', 'small', 'medium'):
1190 thumbnail_url
= clip
.get(thumbnail_id
)
1191 if not thumbnail_url
:
1195 'url': thumbnail_url
,
1197 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
1200 'height': int(mobj
.group(2)),
1201 'width': int(mobj
.group(1)),
1203 thumbnails
.append(thumb
)
1205 old_id
= self
._search
_regex
(r
'%7C(\d+)(?:-\d+)?.mp4', formats
[-1]['url'], 'old id', default
=None)
1208 'id': clip
.get('id') or video_id
,
1209 '_old_archive_ids': [make_archive_id(self
, old_id
)] if old_id
else None,
1210 'display_id': video_id
,
1211 'title': clip
.get('title'),
1213 'duration': int_or_none(clip
.get('durationSeconds')),
1214 'view_count': int_or_none(clip
.get('viewCount')),
1215 'timestamp': unified_timestamp(clip
.get('createdAt')),
1216 'thumbnails': thumbnails
,
1217 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], compat_str
),
1218 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], compat_str
),
1219 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], compat_str
),