2 from __future__
import unicode_literals
10 from .common
import InfoExtractor
11 from ..compat
import (
14 compat_urllib_parse_urlencode
,
15 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': '07e3691a1bad77a36aba590c351180439a40baefc1c275356f40fc7082419a84',
52 'StreamMetadata': '1c719a40e481453e5c48d9bb585d971b8b372f8ebb105b17076722264dfa5b3e',
53 'ComscoreStreamingQuery': 'e1edae8122517d013405f237ffcc124515dc6ded82480a88daef69c83b53ac01',
54 'VideoAccessToken_Clip': '36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11',
55 'VideoPreviewOverlay': '3006e77e51b128d838fa4e835723ca4dc9a05c5efd4466c1085215c6e437e65c',
56 'VideoMetadata': '226edb3e692509f727fd56821f5653c05740242c82b0388883e0c0e75dcbf687',
57 'VideoPlayer_ChapterSelectButtonVideo': '8d2793384aac3773beab5e59bd5d6f585aedb923d292800119e03d40cd0f9b41',
60 def _real_initialize(self
):
64 username
, password
= self
._get
_login
_info
()
70 'Unable to login. Twitch said: %s' % message
, expected
=True)
72 def login_step(page
, urlh
, note
, data
):
73 form
= self
._hidden
_inputs
(page
)
76 page_url
= urlh
.geturl()
77 post_url
= self
._search
_regex
(
78 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page,
79 'post url
', default=self._LOGIN_POST_URL, group='url
')
80 post_url = urljoin(page_url, post_url)
84 'Origin
': 'https
://www
.twitch
.tv
',
85 'Content
-Type
': 'text
/plain
;charset
=UTF
-8',
88 response = self._download_json(
89 post_url, None, note, data=json.dumps(form).encode(),
90 headers=headers, expected_status=400)
91 error = dict_get(response, ('error
', 'error_description
', 'error_code
'))
95 if 'Authenticated successfully
' in response.get('message
', ''):
98 redirect_url = urljoin(
100 response.get('redirect
') or response['redirect_path
'])
101 return self._download_webpage_handle(
102 redirect_url, None, 'Downloading login redirect page
',
105 login_page, handle = self._download_webpage_handle(
106 self._LOGIN_FORM_URL, None, 'Downloading login page
')
108 # Some TOR nodes and public proxies are blocked completely
109 if 'blacklist_message
' in login_page:
110 fail(clean_html(login_page))
112 redirect_page, handle = login_step(
113 login_page, handle, 'Logging
in', {
114 'username
': username,
115 'password
': password,
116 'client_id
': self._CLIENT_ID,
120 if not redirect_page:
123 if re.search(r'(?i
)<form
[^
>]+id="two-factor-submit"', redirect_page) is not None:
124 # TODO: Add mechanism to request an SMS or phone call
125 tfa_token = self._get_tfa_info('two
-factor authentication token
')
126 login_step(redirect_page, handle, 'Submitting TFA token
', {
127 'authy_token
': tfa_token,
128 'remember_2fa
': 'true
',
131 def _prefer_source(self, formats):
133 source = next(f for f in formats if f['format_id
'] == 'Source
')
134 source['quality
'] = 10
135 except StopIteration:
137 if '/chunked
/' in f['url
']:
140 'format_note
': 'Source
',
142 self._sort_formats(formats)
144 def _download_base_gql(self, video_id, ops, note, fatal=True):
146 'Content
-Type
': 'text
/plain
;charset
=UTF
-8',
147 'Client
-ID
': self._CLIENT_ID,
149 gql_auth = self._get_cookies('https
://gql
.twitch
.tv
').get('auth
-token
')
151 headers['Authorization
'] = 'OAuth
' + gql_auth.value
152 return self._download_json(
153 'https
://gql
.twitch
.tv
/gql
', video_id, note,
154 data=json.dumps(ops).encode(),
155 headers=headers, fatal=fatal)
157 def _download_gql(self, video_id, ops, note, fatal=True):
162 'sha256Hash
': self._OPERATION_HASHES[op['operationName
']],
165 return self._download_base_gql(video_id, ops, note)
167 def _download_access_token(self, video_id, token_kind, param_name):
168 method = '%sPlaybackAccessToken
' % token_kind
175 playerBackend: "mediaplayer",
183 }''' % (method, param_name, video_id),
185 return self._download_base_gql(
187 'Downloading
%s access token GraphQL
' % token_kind)['data
'][method]
190 class TwitchVodIE(TwitchBaseIE):
191 IE_NAME = 'twitch
:vod
'
192 _VALID_URL = r'''(?x)
195 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
196 player\.twitch\.tv/\?.*?\bvideo=v?
202 'url
': 'http
://www
.twitch
.tv
/riotgames
/v
/6528877?t
=5m10s
',
206 'title
': 'LCK Summer Split
- Week
6 Day
1',
207 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
209 'timestamp
': 1435131734,
210 'upload_date
': '20150624',
211 'uploader
': 'Riot Games
',
212 'uploader_id
': 'riotgames
',
218 'skip_download
': True,
221 # Untitled broadcast (title is None)
222 'url
': 'http
://www
.twitch
.tv
/belkao_o
/v
/11230755',
226 'title
': 'Untitled Broadcast
',
227 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
229 'timestamp
': 1439746708,
230 'upload_date
': '20150816',
231 'uploader
': 'BelkAO_o
',
232 'uploader_id
': 'belkao_o
',
237 'skip_download
': True,
239 'skip
': 'HTTP Error
404: Not Found
',
241 'url
': 'http
://player
.twitch
.tv
/?t
=5m10s
&video
=v6528877
',
242 'only_matching
': True,
244 'url
': 'https
://www
.twitch
.tv
/videos
/6528877',
245 'only_matching
': True,
247 'url
': 'https
://m
.twitch
.tv
/beagsandjam
/v
/247478721',
248 'only_matching
': True,
250 'url
': 'https
://www
.twitch
.tv
/northernlion
/video
/291940395',
251 'only_matching
': True,
253 'url
': 'https
://player
.twitch
.tv
/?video
=480452374',
254 'only_matching
': True,
256 'url
': 'https
://www
.twitch
.tv
/videos
/635475444',
260 'title
': 'Riot Games
',
262 'uploader
': 'Riot Games
',
263 'uploader_id
': 'riotgames
',
264 'timestamp
': 1590770569,
265 'upload_date
': '20200529',
270 'title
': 'League of Legends
'
275 'title
': 'Legends of Runeterra
'
285 'skip_download
': True
289 def _download_info(self, item_id):
290 data = self._download_gql(
292 'operationName
': 'VideoMetadata
',
298 'operationName
': 'VideoPlayer_ChapterSelectButtonVideo
',
300 'includePrivate
': False,
304 'Downloading stream metadata GraphQL
')
306 video = traverse_obj(data, (0, 'data
', 'video
'))
307 video['moments
'] = traverse_obj(data, (1, 'data
', 'video
', 'moments
', 'edges
', ..., 'node
'))
310 raise ExtractorError(
311 'Video
%s does
not exist
' % item_id, expected=True)
312 return self._extract_info_gql(video, item_id)
314 def _extract_info(self, info):
315 status = info.get('status
')
316 if status == 'recording
':
318 elif status == 'recorded
':
322 _QUALITIES = ('small
', 'medium
', 'large
')
323 quality_key = qualities(_QUALITIES)
325 preview = info.get('preview
')
326 if isinstance(preview, dict):
327 for thumbnail_id, thumbnail_url in preview.items():
328 thumbnail_url = url_or_none(thumbnail_url)
329 if not thumbnail_url:
331 if thumbnail_id not in _QUALITIES:
334 'url
': thumbnail_url,
335 'preference
': quality_key(thumbnail_id),
339 'title
': info.get('title
') or 'Untitled Broadcast
',
340 'description
': info.get('description
'),
341 'duration
': int_or_none(info.get('length
')),
342 'thumbnails
': thumbnails,
343 'uploader
': info.get('channel
', {}).get('display_name
'),
344 'uploader_id
': info.get('channel
', {}).get('name
'),
345 'timestamp
': parse_iso8601(info.get('recorded_at
')),
346 'view_count
': int_or_none(info.get('views
')),
351 def _extract_moments(self, info, item_id):
352 for moment in info.get('moments
') or []:
353 start_time = int_or_none(moment.get('positionMilliseconds
'), 1000)
354 duration = int_or_none(moment.get('durationMilliseconds
'), 1000)
355 name = str_or_none(moment.get('description
'))
357 if start_time is None or duration is None:
358 self.report_warning(f'Important chapter information missing
for chapter {name}
', item_id)
361 'start_time
': start_time,
362 'end_time
': start_time + duration,
366 def _extract_info_gql(self, info, item_id):
367 vod_id = info.get('id') or item_id
368 # id backward compatibility for download archives
370 vod_id = 'v
%s' % vod_id
371 thumbnail = url_or_none(info.get('previewThumbnailURL
'))
374 if thumbnail.endswith('/404_processing
_{width}x{height}
.png
'):
375 is_live, thumbnail = True, None
378 for p in ('width
', 'height
'):
379 thumbnail = thumbnail.replace('{%s}
' % p, '0')
383 'title
': info.get('title
') or 'Untitled Broadcast
',
384 'description
': info.get('description
'),
385 'duration
': int_or_none(info.get('lengthSeconds
')),
386 'thumbnail
': thumbnail,
387 'uploader
': try_get(info, lambda x: x['owner
']['displayName
'], compat_str),
388 'uploader_id
': try_get(info, lambda x: x['owner
']['login
'], compat_str),
389 'timestamp
': unified_timestamp(info.get('publishedAt
')),
390 'view_count
': int_or_none(info.get('viewCount
')),
391 'chapters
': list(self._extract_moments(info, item_id)),
396 def _real_extract(self, url):
397 vod_id = self._match_id(url)
399 info = self._download_info(vod_id)
400 access_token = self._download_access_token(vod_id, 'video
', 'id')
402 formats = self._extract_m3u8_formats(
403 '%s/vod
/%s.m3u8?
%s' % (
404 self._USHER_BASE, vod_id,
405 compat_urllib_parse_urlencode({
406 'allow_source
': 'true
',
407 'allow_audio_only
': 'true
',
408 'allow_spectre
': 'true
',
409 'player
': 'twitchweb
',
410 'playlist_include_framerate
': 'true
',
411 'nauth
': access_token['value
'],
412 'nauthsig
': access_token['signature
'],
414 vod_id, 'mp4
', entry_protocol='m3u8_native
')
416 self._prefer_source(formats)
417 info['formats
'] = formats
419 parsed_url = compat_urllib_parse_urlparse(url)
420 query = compat_parse_qs(parsed_url.query)
422 info['start_time
'] = parse_duration(query['t
'][0])
424 if info.get('timestamp
') is not None:
425 info['subtitles
'] = {
427 'url
': update_url_query(
428 'https
://api
.twitch
.tv
/v5
/videos
/%s/comments
' % vod_id, {
429 'client_id
': self._CLIENT_ID,
438 def _make_video_result(node):
439 assert isinstance(node, dict)
440 video_id = node.get('id')
444 '_type
': 'url_transparent
',
445 'ie_key
': TwitchVodIE.ie_key(),
446 'id': 'v
' + video_id,
447 'url
': 'https
://www
.twitch
.tv
/videos
/%s' % video_id,
448 'title
': node.get('title
'),
449 'thumbnail
': node.get('previewThumbnailURL
'),
450 'duration
': float_or_none(node.get('lengthSeconds
')),
451 'view_count
': int_or_none(node.get('viewCount
')),
455 class TwitchCollectionIE(TwitchBaseIE):
456 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/collections
/(?P
<id>[^
/]+)'
459 'url
': 'https
://www
.twitch
.tv
/collections
/wlDCoH0zEBZZbQ
',
461 'id': 'wlDCoH0zEBZZbQ
',
462 'title
': 'Overthrow Nook
, capitalism
for children
',
464 'playlist_mincount
': 13,
467 _OPERATION_NAME = 'CollectionSideBar
'
469 def _real_extract(self, url):
470 collection_id = self._match_id(url)
471 collection = self._download_gql(
473 'operationName
': self._OPERATION_NAME,
474 'variables
': {'collectionID': collection_id},
476 'Downloading collection GraphQL
')[0]['data
']['collection
']
477 title = collection.get('title
')
479 for edge in collection['items
']['edges
']:
480 if not isinstance(edge, dict):
482 node = edge.get('node
')
483 if not isinstance(node, dict):
485 video = _make_video_result(node)
487 entries.append(video)
488 return self.playlist_result(
489 entries, playlist_id=collection_id, playlist_title=title)
492 class TwitchPlaylistBaseIE(TwitchBaseIE):
495 def _entries(self, channel_name, *args):
497 variables_common = self._make_variables(channel_name, *args)
498 entries_key = '%ss' % self._ENTRY_KIND
499 for page_num in itertools.count(1):
500 variables = variables_common.copy()
501 variables['limit
'] = self._PAGE_LIMIT
503 variables['cursor
'] = cursor
504 page = self._download_gql(
506 'operationName
': self._OPERATION_NAME,
507 'variables
': variables,
509 'Downloading
%ss GraphQL page
%s' % (self._NODE_KIND, page_num),
514 page, lambda x: x[0]['data
']['user
'][entries_key]['edges
'], list)
518 if not isinstance(edge, dict):
520 if edge.get('__typename
') != self._EDGE_KIND:
522 node = edge.get('node
')
523 if not isinstance(node, dict):
525 if node.get('__typename
') != self._NODE_KIND:
527 entry = self._extract_entry(node)
529 cursor = edge.get('cursor
')
531 if not cursor or not isinstance(cursor, compat_str):
535 class TwitchVideosIE(TwitchPlaylistBaseIE):
536 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/(?P
<id>[^
/]+)/(?
:videos|profile
)'
539 # All Videos sorted by Date
540 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=all
',
543 'title
': 'spamfish
- All Videos
sorted by Date
',
545 'playlist_mincount
': 924,
547 # All Videos sorted by Popular
548 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=all
&sort
=views
',
551 'title
': 'spamfish
- All Videos
sorted by Popular
',
553 'playlist_mincount
': 931,
555 # Past Broadcasts sorted by Date
556 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=archives
',
559 'title
': 'spamfish
- Past Broadcasts
sorted by Date
',
561 'playlist_mincount
': 27,
563 # Highlights sorted by Date
564 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=highlights
',
567 'title
': 'spamfish
- Highlights
sorted by Date
',
569 'playlist_mincount
': 901,
571 # Uploads sorted by Date
572 'url
': 'https
://www
.twitch
.tv
/esl_csgo
/videos?
filter=uploads
&sort
=time
',
575 'title
': 'esl_csgo
- Uploads
sorted by Date
',
577 'playlist_mincount
': 5,
579 # Past Premieres sorted by Date
580 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=past_premieres
',
583 'title
': 'spamfish
- Past Premieres
sorted by Date
',
585 'playlist_mincount
': 1,
587 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos
/all
',
588 'only_matching
': True,
590 'url
': 'https
://m
.twitch
.tv
/spamfish
/videos
/all
',
591 'only_matching
': True,
593 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos
',
594 'only_matching
': True,
597 Broadcast = collections.namedtuple('Broadcast
', ['type', 'label
'])
599 _DEFAULT_BROADCAST = Broadcast(None, 'All Videos
')
601 'archives
': Broadcast('ARCHIVE
', 'Past Broadcasts
'),
602 'highlights
': Broadcast('HIGHLIGHT
', 'Highlights
'),
603 'uploads
': Broadcast('UPLOAD
', 'Uploads
'),
604 'past_premieres
': Broadcast('PAST_PREMIERE
', 'Past Premieres
'),
605 'all
': _DEFAULT_BROADCAST,
608 _DEFAULT_SORTED_BY = 'Date
'
610 'time
': _DEFAULT_SORTED_BY,
614 _OPERATION_NAME = 'FilterableVideoTower_Videos
'
615 _ENTRY_KIND = 'video
'
616 _EDGE_KIND = 'VideoEdge
'
620 def suitable(cls, url):
622 if any(ie.suitable(url) for ie in (
624 TwitchVideosCollectionsIE))
625 else super(TwitchVideosIE, cls).suitable(url))
628 def _make_variables(channel_name, broadcast_type, sort):
630 'channelOwnerLogin
': channel_name,
631 'broadcastType
': broadcast_type,
632 'videoSort
': sort.upper(),
636 def _extract_entry(node):
637 return _make_video_result(node)
639 def _real_extract(self, url):
640 channel_name = self._match_id(url)
642 filter = qs.get('filter', ['all
'])[0]
643 sort = qs.get('sort
', ['time
'])[0]
644 broadcast = self._BROADCASTS.get(filter, self._DEFAULT_BROADCAST)
645 return self.playlist_result(
646 self._entries(channel_name, broadcast.type, sort),
647 playlist_id=channel_name,
648 playlist_title='%s - %s sorted by
%s'
649 % (channel_name, broadcast.label,
650 self._SORTED_BY.get(sort, self._DEFAULT_SORTED_BY)))
653 class TwitchVideosClipsIE(TwitchPlaylistBaseIE):
654 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/(?P
<id>[^
/]+)/(?
:clips|videos
/*?
\?.*?
\bfilter
=clips
)'
658 'url
': 'https
://www
.twitch
.tv
/vanillatv
/clips?
filter=clips
&range=all
',
661 'title
': 'vanillatv
- Clips Top All
',
663 'playlist_mincount
': 1,
665 'url
': 'https
://www
.twitch
.tv
/dota2ruhub
/videos?
filter=clips
&range=7d
',
666 'only_matching
': True,
669 Clip = collections.namedtuple('Clip
', ['filter', 'label
'])
671 _DEFAULT_CLIP = Clip('LAST_WEEK
', 'Top
7D
')
673 '24hr
': Clip('LAST_DAY
', 'Top
24H
'),
675 '30d
': Clip('LAST_MONTH
', 'Top
30D
'),
676 'all
': Clip('ALL_TIME
', 'Top All
'),
679 # NB: values other than 20 result in skipped videos
682 _OPERATION_NAME = 'ClipsCards__User
'
684 _EDGE_KIND = 'ClipEdge
'
688 def _make_variables(channel_name, filter):
690 'login
': channel_name,
697 def _extract_entry(node):
698 assert isinstance(node, dict)
699 clip_url = url_or_none(node.get('url
'))
703 '_type
': 'url_transparent
',
704 'ie_key
': TwitchClipsIE.ie_key(),
705 'id': node.get('id'),
707 'title
': node.get('title
'),
708 'thumbnail
': node.get('thumbnailURL
'),
709 'duration
': float_or_none(node.get('durationSeconds
')),
710 'timestamp
': unified_timestamp(node.get('createdAt
')),
711 'view_count
': int_or_none(node.get('viewCount
')),
712 'language
': node.get('language
'),
715 def _real_extract(self, url):
716 channel_name = self._match_id(url)
718 range = qs.get('range', ['7d
'])[0]
719 clip = self._RANGE.get(range, self._DEFAULT_CLIP)
720 return self.playlist_result(
721 self._entries(channel_name, clip.filter),
722 playlist_id=channel_name,
723 playlist_title='%s - Clips
%s' % (channel_name, clip.label))
726 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE):
727 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/(?P
<id>[^
/]+)/videos
/*?
\?.*?
\bfilter
=collections
'
731 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=collections
',
734 'title
': 'spamfish
- Collections
',
736 'playlist_mincount
': 3,
739 _OPERATION_NAME = 'ChannelCollectionsContent
'
740 _ENTRY_KIND = 'collection
'
741 _EDGE_KIND = 'CollectionsItemEdge
'
742 _NODE_KIND = 'Collection
'
745 def _make_variables(channel_name):
747 'ownerLogin
': channel_name,
751 def _extract_entry(node):
752 assert isinstance(node, dict)
753 collection_id = node.get('id')
754 if not collection_id:
757 '_type
': 'url_transparent
',
758 'ie_key
': TwitchCollectionIE.ie_key(),
760 'url
': 'https
://www
.twitch
.tv
/collections
/%s' % collection_id,
761 'title
': node.get('title
'),
762 'thumbnail
': node.get('thumbnailURL
'),
763 'duration
': float_or_none(node.get('lengthSeconds
')),
764 'timestamp
': unified_timestamp(node.get('updatedAt
')),
765 'view_count
': int_or_none(node.get('viewCount
')),
768 def _real_extract(self, url):
769 channel_name = self._match_id(url)
770 return self.playlist_result(
771 self._entries(channel_name), playlist_id=channel_name,
772 playlist_title='%s - Collections
' % channel_name)
775 class TwitchStreamIE(TwitchBaseIE):
776 IE_NAME = 'twitch
:stream
'
777 _VALID_URL = r'''(?x)
780 (?:(?:www|go|m)\.)?twitch\.tv/|
781 player\.twitch\.tv/\?.*?\bchannel=
787 'url
': 'http
://www
.twitch
.tv
/shroomztv
',
790 'display_id
': 'shroomztv
',
792 'title
': 're
:^ShroomzTV
[0-9]{4}
-[0-9]{2}
-[0-9]{2}
[0-9]{2}
:[0-9]{2}$
',
793 'description
': 'H1Z1
- lonewolfing
with ShroomzTV | A3 Battle Royale later
- @ShroomzTV',
795 'timestamp
': 1421928037,
796 'upload_date
': '20150122',
797 'uploader
': 'ShroomzTV
',
798 'uploader_id
': 'shroomztv
',
803 'skip_download
': True,
806 'url
': 'http
://www
.twitch
.tv
/miracle_doto
#profile-0',
807 'only_matching': True,
809 'url': 'https://player.twitch.tv/?channel=lotsofs',
810 'only_matching': True,
812 'url': 'https://go.twitch.tv/food',
813 'only_matching': True,
815 'url': 'https://m.twitch.tv/food',
816 'only_matching': True,
820 def suitable(cls
, url
):
822 if any(ie
.suitable(url
) for ie
in (
827 TwitchVideosCollectionsIE
,
829 else super(TwitchStreamIE
, cls
).suitable(url
))
831 def _real_extract(self
, url
):
832 channel_name
= self
._match
_id
(url
).lower()
834 gql
= self
._download
_gql
(
836 'operationName': 'StreamMetadata',
837 'variables': {'channelLogin': channel_name}
,
839 'operationName': 'ComscoreStreamingQuery',
841 'channel': channel_name
,
845 'isVodOrCollection': False,
849 'operationName': 'VideoPreviewOverlay',
850 'variables': {'login': channel_name}
,
852 'Downloading stream GraphQL')
854 user
= gql
[0]['data']['user']
857 raise ExtractorError(
858 '%s does not exist' % channel_name
, expected
=True)
860 stream
= user
['stream']
863 raise ExtractorError('%s is offline' % channel_name
, expected
=True)
865 access_token
= self
._download
_access
_token
(
866 channel_name
, 'stream', 'channelName')
867 token
= access_token
['value']
869 stream_id
= stream
.get('id') or channel_name
871 'allow_source': 'true',
872 'allow_audio_only': 'true',
873 'allow_spectre': 'true',
874 'p': random
.randint(1000000, 10000000),
875 'player': 'twitchweb',
876 'playlist_include_framerate': 'true',
877 'segment_preference': '4',
878 'sig': access_token
['signature'].encode('utf-8'),
879 'token': token
.encode('utf-8'),
881 formats
= self
._extract
_m
3u8_formats
(
882 '%s/api/channel/hls/%s.m3u8' % (self
._USHER
_BASE
, channel_name
),
883 stream_id
, 'mp4', query
=query
)
884 self
._prefer
_source
(formats
)
886 view_count
= stream
.get('viewers')
887 timestamp
= unified_timestamp(stream
.get('createdAt'))
889 sq_user
= try_get(gql
, lambda x
: x
[1]['data']['user'], dict) or {}
890 uploader
= sq_user
.get('displayName')
891 description
= try_get(
892 sq_user
, lambda x
: x
['broadcastSettings']['title'], compat_str
)
894 thumbnail
= url_or_none(try_get(
895 gql
, lambda x
: x
[2]['data']['user']['stream']['previewImageURL'],
898 title
= uploader
or channel_name
899 stream_type
= stream
.get('type')
900 if stream_type
in ['rerun', 'live']:
901 title
+= ' (%s)' % stream_type
905 'display_id': channel_name
,
907 'description': description
,
908 'thumbnail': thumbnail
,
909 'uploader': uploader
,
910 'uploader_id': channel_name
,
911 'timestamp': timestamp
,
912 'view_count': view_count
,
914 'is_live': stream_type
== 'live',
918 class TwitchClipsIE(TwitchBaseIE
):
919 IE_NAME
= 'twitch:clips'
920 _VALID_URL
= r
'''(?x)
923 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
924 (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/
930 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
931 'md5': '761769e1eafce0ffebfb4089cb3847cd',
934 'display_id': 'FaintLightGullWholeWheat',
936 'title': 'EA Play 2016 Live from the Novo Theatre',
937 'thumbnail': r
're:^https?://.*\.jpg',
938 'timestamp': 1465767393,
939 'upload_date': '20160612',
941 'uploader': 'stereotype_',
942 'uploader_id': '43566419',
946 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
947 'only_matching': True,
949 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
950 'only_matching': True,
952 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
953 'only_matching': True,
955 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
956 'only_matching': True,
958 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
959 'only_matching': True,
962 def _real_extract(self
, url
):
963 video_id
= self
._match
_id
(url
)
965 clip
= self
._download
_gql
(
967 'operationName': 'VideoAccessToken_Clip',
972 'Downloading clip access token GraphQL')[0]['data']['clip']
975 raise ExtractorError(
976 'This clip is no longer available', expected
=True)
979 'sig': clip
['playbackAccessToken']['signature'],
980 'token': clip
['playbackAccessToken']['value'],
983 data
= self
._download
_base
_gql
(
997 tiny: thumbnailURL(width: 86, height: 45)
998 small: thumbnailURL(width: 260, height: 147)
999 medium: thumbnailURL(width: 480, height: 272)
1008 }''' % video_id
}, 'Downloading clip GraphQL', fatal
=False)
1011 clip
= try_get(data
, lambda x
: x
['data']['clip'], dict) or clip
1014 for option
in clip
.get('videoQualities', []):
1015 if not isinstance(option
, dict):
1017 source
= url_or_none(option
.get('sourceURL'))
1021 'url': update_url_query(source
, access_query
),
1022 'format_id': option
.get('quality'),
1023 'height': int_or_none(option
.get('quality')),
1024 'fps': int_or_none(option
.get('frameRate')),
1026 self
._sort
_formats
(formats
)
1029 for thumbnail_id
in ('tiny', 'small', 'medium'):
1030 thumbnail_url
= clip
.get(thumbnail_id
)
1031 if not thumbnail_url
:
1035 'url': thumbnail_url
,
1037 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
1040 'height': int(mobj
.group(2)),
1041 'width': int(mobj
.group(1)),
1043 thumbnails
.append(thumb
)
1046 'id': clip
.get('id') or video_id
,
1047 'display_id': video_id
,
1048 'title': clip
.get('title') or video_id
,
1050 'duration': int_or_none(clip
.get('durationSeconds')),
1051 'view_count': int_or_none(clip
.get('viewCount')),
1052 'timestamp': unified_timestamp(clip
.get('createdAt')),
1053 'thumbnails': thumbnails
,
1054 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], compat_str
),
1055 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], compat_str
),
1056 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], compat_str
),