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 _perform_login(self
, username
, password
):
63 'Unable to login. Twitch said: %s' % message
, expected
=True)
65 def login_step(page
, urlh
, note
, data
):
66 form
= self
._hidden
_inputs
(page
)
69 page_url
= urlh
.geturl()
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
',
135 self._sort_formats(formats)
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]
183 class TwitchVodIE(TwitchBaseIE):
184 IE_NAME = 'twitch
:vod
'
185 _VALID_URL = r'''(?x)
188 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
189 player\.twitch\.tv/\?.*?\bvideo=v?
195 'url
': 'http
://www
.twitch
.tv
/riotgames
/v
/6528877?t
=5m10s
',
199 'title
': 'LCK Summer Split
- Week
6 Day
1',
200 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
202 'timestamp
': 1435131734,
203 'upload_date
': '20150624',
204 'uploader
': 'Riot Games
',
205 'uploader_id
': 'riotgames
',
211 'skip_download
': True,
214 # Untitled broadcast (title is None)
215 'url
': 'http
://www
.twitch
.tv
/belkao_o
/v
/11230755',
219 'title
': 'Untitled Broadcast
',
220 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
222 'timestamp
': 1439746708,
223 'upload_date
': '20150816',
224 'uploader
': 'BelkAO_o
',
225 'uploader_id
': 'belkao_o
',
230 'skip_download
': True,
232 'skip
': 'HTTP Error
404: Not Found
',
234 'url
': 'http
://player
.twitch
.tv
/?t
=5m10s
&video
=v6528877
',
235 'only_matching
': True,
237 'url
': 'https
://www
.twitch
.tv
/videos
/6528877',
238 'only_matching
': True,
240 'url
': 'https
://m
.twitch
.tv
/beagsandjam
/v
/247478721',
241 'only_matching
': True,
243 'url
': 'https
://www
.twitch
.tv
/northernlion
/video
/291940395',
244 'only_matching
': True,
246 'url
': 'https
://player
.twitch
.tv
/?video
=480452374',
247 'only_matching
': True,
249 'url
': 'https
://www
.twitch
.tv
/videos
/635475444',
253 'title
': 'Riot Games
',
255 'uploader
': 'Riot Games
',
256 'uploader_id
': 'riotgames
',
257 'timestamp
': 1590770569,
258 'upload_date
': '20200529',
263 'title
': 'League of Legends
'
268 'title
': 'Legends of Runeterra
'
278 'skip_download
': True
282 def _download_info(self, item_id):
283 data = self._download_gql(
285 'operationName
': 'VideoMetadata
',
291 'operationName
': 'VideoPlayer_ChapterSelectButtonVideo
',
293 'includePrivate
': False,
297 'Downloading stream metadata GraphQL
')
299 video = traverse_obj(data, (0, 'data
', 'video
'))
300 video['moments
'] = traverse_obj(data, (1, 'data
', 'video
', 'moments
', 'edges
', ..., 'node
'))
303 raise ExtractorError(
304 'Video
%s does
not exist
' % item_id, expected=True)
305 return self._extract_info_gql(video, item_id)
307 def _extract_info(self, info):
308 status = info.get('status
')
309 if status == 'recording
':
311 elif status == 'recorded
':
315 _QUALITIES = ('small
', 'medium
', 'large
')
316 quality_key = qualities(_QUALITIES)
318 preview = info.get('preview
')
319 if isinstance(preview, dict):
320 for thumbnail_id, thumbnail_url in preview.items():
321 thumbnail_url = url_or_none(thumbnail_url)
322 if not thumbnail_url:
324 if thumbnail_id not in _QUALITIES:
327 'url
': thumbnail_url,
328 'preference
': quality_key(thumbnail_id),
332 'title
': info.get('title
') or 'Untitled Broadcast
',
333 'description
': info.get('description
'),
334 'duration
': int_or_none(info.get('length
')),
335 'thumbnails
': thumbnails,
336 'uploader
': info.get('channel
', {}).get('display_name
'),
337 'uploader_id
': info.get('channel
', {}).get('name
'),
338 'timestamp
': parse_iso8601(info.get('recorded_at
')),
339 'view_count
': int_or_none(info.get('views
')),
344 def _extract_moments(self, info, item_id):
345 for moment in info.get('moments
') or []:
346 start_time = int_or_none(moment.get('positionMilliseconds
'), 1000)
347 duration = int_or_none(moment.get('durationMilliseconds
'), 1000)
348 name = str_or_none(moment.get('description
'))
350 if start_time is None or duration is None:
351 self.report_warning(f'Important chapter information missing
for chapter {name}
', item_id)
354 'start_time
': start_time,
355 'end_time
': start_time + duration,
359 def _extract_info_gql(self, info, item_id):
360 vod_id = info.get('id') or item_id
361 # id backward compatibility for download archives
363 vod_id = 'v
%s' % vod_id
364 thumbnail = url_or_none(info.get('previewThumbnailURL
'))
367 if thumbnail.endswith('/404_processing
_{width}x{height}
.png
'):
368 is_live, thumbnail = True, None
371 for p in ('width
', 'height
'):
372 thumbnail = thumbnail.replace('{%s}
' % p, '0')
376 'title
': info.get('title
') or 'Untitled Broadcast
',
377 'description
': info.get('description
'),
378 'duration
': int_or_none(info.get('lengthSeconds
')),
379 'thumbnail
': thumbnail,
380 'uploader
': try_get(info, lambda x: x['owner
']['displayName
'], compat_str),
381 'uploader_id
': try_get(info, lambda x: x['owner
']['login
'], compat_str),
382 'timestamp
': unified_timestamp(info.get('publishedAt
')),
383 'view_count
': int_or_none(info.get('viewCount
')),
384 'chapters
': list(self._extract_moments(info, item_id)),
389 def _real_extract(self, url):
390 vod_id = self._match_id(url)
392 info = self._download_info(vod_id)
393 access_token = self._download_access_token(vod_id, 'video
', 'id')
395 formats = self._extract_m3u8_formats(
396 '%s/vod
/%s.m3u8?
%s' % (
397 self._USHER_BASE, vod_id,
398 compat_urllib_parse_urlencode({
399 'allow_source
': 'true
',
400 'allow_audio_only
': 'true
',
401 'allow_spectre
': 'true
',
402 'player
': 'twitchweb
',
403 'playlist_include_framerate
': 'true
',
404 'nauth
': access_token['value
'],
405 'nauthsig
': access_token['signature
'],
407 vod_id, 'mp4
', entry_protocol='m3u8_native
')
409 self._prefer_source(formats)
410 info['formats
'] = formats
412 parsed_url = compat_urllib_parse_urlparse(url)
413 query = compat_parse_qs(parsed_url.query)
415 info['start_time
'] = parse_duration(query['t
'][0])
417 if info.get('timestamp
') is not None:
418 info['subtitles
'] = {
420 'url
': update_url_query(
421 'https
://api
.twitch
.tv
/v5
/videos
/%s/comments
' % vod_id, {
422 'client_id
': self._CLIENT_ID,
431 def _make_video_result(node):
432 assert isinstance(node, dict)
433 video_id = node.get('id')
437 '_type
': 'url_transparent
',
438 'ie_key
': TwitchVodIE.ie_key(),
439 'id': 'v
' + video_id,
440 'url
': 'https
://www
.twitch
.tv
/videos
/%s' % video_id,
441 'title
': node.get('title
'),
442 'thumbnail
': node.get('previewThumbnailURL
'),
443 'duration
': float_or_none(node.get('lengthSeconds
')),
444 'view_count
': int_or_none(node.get('viewCount
')),
448 class TwitchCollectionIE(TwitchBaseIE):
449 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/collections
/(?P
<id>[^
/]+)'
452 'url
': 'https
://www
.twitch
.tv
/collections
/wlDCoH0zEBZZbQ
',
454 'id': 'wlDCoH0zEBZZbQ
',
455 'title
': 'Overthrow Nook
, capitalism
for children
',
457 'playlist_mincount
': 13,
460 _OPERATION_NAME = 'CollectionSideBar
'
462 def _real_extract(self, url):
463 collection_id = self._match_id(url)
464 collection = self._download_gql(
466 'operationName
': self._OPERATION_NAME,
467 'variables
': {'collectionID': collection_id},
469 'Downloading collection GraphQL
')[0]['data
']['collection
']
470 title = collection.get('title
')
472 for edge in collection['items
']['edges
']:
473 if not isinstance(edge, dict):
475 node = edge.get('node
')
476 if not isinstance(node, dict):
478 video = _make_video_result(node)
480 entries.append(video)
481 return self.playlist_result(
482 entries, playlist_id=collection_id, playlist_title=title)
485 class TwitchPlaylistBaseIE(TwitchBaseIE):
488 def _entries(self, channel_name, *args):
490 variables_common = self._make_variables(channel_name, *args)
491 entries_key = '%ss' % self._ENTRY_KIND
492 for page_num in itertools.count(1):
493 variables = variables_common.copy()
494 variables['limit
'] = self._PAGE_LIMIT
496 variables['cursor
'] = cursor
497 page = self._download_gql(
499 'operationName
': self._OPERATION_NAME,
500 'variables
': variables,
502 'Downloading
%ss GraphQL page
%s' % (self._NODE_KIND, page_num),
507 page, lambda x: x[0]['data
']['user
'][entries_key]['edges
'], list)
511 if not isinstance(edge, dict):
513 if edge.get('__typename
') != self._EDGE_KIND:
515 node = edge.get('node
')
516 if not isinstance(node, dict):
518 if node.get('__typename
') != self._NODE_KIND:
520 entry = self._extract_entry(node)
522 cursor = edge.get('cursor
')
524 if not cursor or not isinstance(cursor, compat_str):
528 class TwitchVideosIE(TwitchPlaylistBaseIE):
529 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/(?P
<id>[^
/]+)/(?
:videos|profile
)'
532 # All Videos sorted by Date
533 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=all
',
536 'title
': 'spamfish
- All Videos
sorted by Date
',
538 'playlist_mincount
': 924,
540 # All Videos sorted by Popular
541 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=all
&sort
=views
',
544 'title
': 'spamfish
- All Videos
sorted by Popular
',
546 'playlist_mincount
': 931,
548 # Past Broadcasts sorted by Date
549 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=archives
',
552 'title
': 'spamfish
- Past Broadcasts
sorted by Date
',
554 'playlist_mincount
': 27,
556 # Highlights sorted by Date
557 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=highlights
',
560 'title
': 'spamfish
- Highlights
sorted by Date
',
562 'playlist_mincount
': 901,
564 # Uploads sorted by Date
565 'url
': 'https
://www
.twitch
.tv
/esl_csgo
/videos?
filter=uploads
&sort
=time
',
568 'title
': 'esl_csgo
- Uploads
sorted by Date
',
570 'playlist_mincount
': 5,
572 # Past Premieres sorted by Date
573 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=past_premieres
',
576 'title
': 'spamfish
- Past Premieres
sorted by Date
',
578 'playlist_mincount
': 1,
580 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos
/all
',
581 'only_matching
': True,
583 'url
': 'https
://m
.twitch
.tv
/spamfish
/videos
/all
',
584 'only_matching
': True,
586 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos
',
587 'only_matching
': True,
590 Broadcast = collections.namedtuple('Broadcast
', ['type', 'label
'])
592 _DEFAULT_BROADCAST = Broadcast(None, 'All Videos
')
594 'archives
': Broadcast('ARCHIVE
', 'Past Broadcasts
'),
595 'highlights
': Broadcast('HIGHLIGHT
', 'Highlights
'),
596 'uploads
': Broadcast('UPLOAD
', 'Uploads
'),
597 'past_premieres
': Broadcast('PAST_PREMIERE
', 'Past Premieres
'),
598 'all
': _DEFAULT_BROADCAST,
601 _DEFAULT_SORTED_BY = 'Date
'
603 'time
': _DEFAULT_SORTED_BY,
607 _OPERATION_NAME = 'FilterableVideoTower_Videos
'
608 _ENTRY_KIND = 'video
'
609 _EDGE_KIND = 'VideoEdge
'
613 def suitable(cls, url):
615 if any(ie.suitable(url) for ie in (
617 TwitchVideosCollectionsIE))
618 else super(TwitchVideosIE, cls).suitable(url))
621 def _make_variables(channel_name, broadcast_type, sort):
623 'channelOwnerLogin
': channel_name,
624 'broadcastType
': broadcast_type,
625 'videoSort
': sort.upper(),
629 def _extract_entry(node):
630 return _make_video_result(node)
632 def _real_extract(self, url):
633 channel_name = self._match_id(url)
635 filter = qs.get('filter', ['all
'])[0]
636 sort = qs.get('sort
', ['time
'])[0]
637 broadcast = self._BROADCASTS.get(filter, self._DEFAULT_BROADCAST)
638 return self.playlist_result(
639 self._entries(channel_name, broadcast.type, sort),
640 playlist_id=channel_name,
641 playlist_title='%s - %s sorted by
%s'
642 % (channel_name, broadcast.label,
643 self._SORTED_BY.get(sort, self._DEFAULT_SORTED_BY)))
646 class TwitchVideosClipsIE(TwitchPlaylistBaseIE):
647 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/(?P
<id>[^
/]+)/(?
:clips|videos
/*?
\?.*?
\bfilter
=clips
)'
651 'url
': 'https
://www
.twitch
.tv
/vanillatv
/clips?
filter=clips
&range=all
',
654 'title
': 'vanillatv
- Clips Top All
',
656 'playlist_mincount
': 1,
658 'url
': 'https
://www
.twitch
.tv
/dota2ruhub
/videos?
filter=clips
&range=7d
',
659 'only_matching
': True,
662 Clip = collections.namedtuple('Clip
', ['filter', 'label
'])
664 _DEFAULT_CLIP = Clip('LAST_WEEK
', 'Top
7D
')
666 '24hr
': Clip('LAST_DAY
', 'Top
24H
'),
668 '30d
': Clip('LAST_MONTH
', 'Top
30D
'),
669 'all
': Clip('ALL_TIME
', 'Top All
'),
672 # NB: values other than 20 result in skipped videos
675 _OPERATION_NAME = 'ClipsCards__User
'
677 _EDGE_KIND = 'ClipEdge
'
681 def _make_variables(channel_name, filter):
683 'login
': channel_name,
690 def _extract_entry(node):
691 assert isinstance(node, dict)
692 clip_url = url_or_none(node.get('url
'))
696 '_type
': 'url_transparent
',
697 'ie_key
': TwitchClipsIE.ie_key(),
698 'id': node.get('id'),
700 'title
': node.get('title
'),
701 'thumbnail
': node.get('thumbnailURL
'),
702 'duration
': float_or_none(node.get('durationSeconds
')),
703 'timestamp
': unified_timestamp(node.get('createdAt
')),
704 'view_count
': int_or_none(node.get('viewCount
')),
705 'language
': node.get('language
'),
708 def _real_extract(self, url):
709 channel_name = self._match_id(url)
711 range = qs.get('range', ['7d
'])[0]
712 clip = self._RANGE.get(range, self._DEFAULT_CLIP)
713 return self.playlist_result(
714 self._entries(channel_name, clip.filter),
715 playlist_id=channel_name,
716 playlist_title='%s - Clips
%s' % (channel_name, clip.label))
719 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE):
720 _VALID_URL = r'https?
://(?
:(?
:www|go|m
)\
.)?twitch\
.tv
/(?P
<id>[^
/]+)/videos
/*?
\?.*?
\bfilter
=collections
'
724 'url
': 'https
://www
.twitch
.tv
/spamfish
/videos?
filter=collections
',
727 'title
': 'spamfish
- Collections
',
729 'playlist_mincount
': 3,
732 _OPERATION_NAME = 'ChannelCollectionsContent
'
733 _ENTRY_KIND = 'collection
'
734 _EDGE_KIND = 'CollectionsItemEdge
'
735 _NODE_KIND = 'Collection
'
738 def _make_variables(channel_name):
740 'ownerLogin
': channel_name,
744 def _extract_entry(node):
745 assert isinstance(node, dict)
746 collection_id = node.get('id')
747 if not collection_id:
750 '_type
': 'url_transparent
',
751 'ie_key
': TwitchCollectionIE.ie_key(),
753 'url
': 'https
://www
.twitch
.tv
/collections
/%s' % collection_id,
754 'title
': node.get('title
'),
755 'thumbnail
': node.get('thumbnailURL
'),
756 'duration
': float_or_none(node.get('lengthSeconds
')),
757 'timestamp
': unified_timestamp(node.get('updatedAt
')),
758 'view_count
': int_or_none(node.get('viewCount
')),
761 def _real_extract(self, url):
762 channel_name = self._match_id(url)
763 return self.playlist_result(
764 self._entries(channel_name), playlist_id=channel_name,
765 playlist_title='%s - Collections
' % channel_name)
768 class TwitchStreamIE(TwitchBaseIE):
769 IE_NAME = 'twitch
:stream
'
770 _VALID_URL = r'''(?x)
773 (?:(?:www|go|m)\.)?twitch\.tv/|
774 player\.twitch\.tv/\?.*?\bchannel=
780 'url
': 'http
://www
.twitch
.tv
/shroomztv
',
783 'display_id
': 'shroomztv
',
785 'title
': 're
:^ShroomzTV
[0-9]{4}
-[0-9]{2}
-[0-9]{2}
[0-9]{2}
:[0-9]{2}$
',
786 'description
': 'H1Z1
- lonewolfing
with ShroomzTV | A3 Battle Royale later
- @ShroomzTV',
788 'timestamp
': 1421928037,
789 'upload_date
': '20150122',
790 'uploader
': 'ShroomzTV
',
791 'uploader_id
': 'shroomztv
',
796 'skip_download
': True,
799 'url
': 'http
://www
.twitch
.tv
/miracle_doto
#profile-0',
800 'only_matching': True,
802 'url': 'https://player.twitch.tv/?channel=lotsofs',
803 'only_matching': True,
805 'url': 'https://go.twitch.tv/food',
806 'only_matching': True,
808 'url': 'https://m.twitch.tv/food',
809 'only_matching': True,
813 def suitable(cls
, url
):
815 if any(ie
.suitable(url
) for ie
in (
820 TwitchVideosCollectionsIE
,
822 else super(TwitchStreamIE
, cls
).suitable(url
))
824 def _real_extract(self
, url
):
825 channel_name
= self
._match
_id
(url
).lower()
827 gql
= self
._download
_gql
(
829 'operationName': 'StreamMetadata',
830 'variables': {'channelLogin': channel_name}
,
832 'operationName': 'ComscoreStreamingQuery',
834 'channel': channel_name
,
838 'isVodOrCollection': False,
842 'operationName': 'VideoPreviewOverlay',
843 'variables': {'login': channel_name}
,
845 'Downloading stream GraphQL')
847 user
= gql
[0]['data']['user']
850 raise ExtractorError(
851 '%s does not exist' % channel_name
, expected
=True)
853 stream
= user
['stream']
856 raise ExtractorError('%s is offline' % channel_name
, expected
=True)
858 access_token
= self
._download
_access
_token
(
859 channel_name
, 'stream', 'channelName')
860 token
= access_token
['value']
862 stream_id
= stream
.get('id') or channel_name
864 'allow_source': 'true',
865 'allow_audio_only': 'true',
866 'allow_spectre': 'true',
867 'p': random
.randint(1000000, 10000000),
868 'player': 'twitchweb',
869 'playlist_include_framerate': 'true',
870 'segment_preference': '4',
871 'sig': access_token
['signature'].encode('utf-8'),
872 'token': token
.encode('utf-8'),
874 formats
= self
._extract
_m
3u8_formats
(
875 '%s/api/channel/hls/%s.m3u8' % (self
._USHER
_BASE
, channel_name
),
876 stream_id
, 'mp4', query
=query
)
877 self
._prefer
_source
(formats
)
879 view_count
= stream
.get('viewers')
880 timestamp
= unified_timestamp(stream
.get('createdAt'))
882 sq_user
= try_get(gql
, lambda x
: x
[1]['data']['user'], dict) or {}
883 uploader
= sq_user
.get('displayName')
884 description
= try_get(
885 sq_user
, lambda x
: x
['broadcastSettings']['title'], compat_str
)
887 thumbnail
= url_or_none(try_get(
888 gql
, lambda x
: x
[2]['data']['user']['stream']['previewImageURL'],
891 title
= uploader
or channel_name
892 stream_type
= stream
.get('type')
893 if stream_type
in ['rerun', 'live']:
894 title
+= ' (%s)' % stream_type
898 'display_id': channel_name
,
900 'description': description
,
901 'thumbnail': thumbnail
,
902 'uploader': uploader
,
903 'uploader_id': channel_name
,
904 'timestamp': timestamp
,
905 'view_count': view_count
,
907 'is_live': stream_type
== 'live',
911 class TwitchClipsIE(TwitchBaseIE
):
912 IE_NAME
= 'twitch:clips'
913 _VALID_URL
= r
'''(?x)
916 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
917 (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/
923 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
924 'md5': '761769e1eafce0ffebfb4089cb3847cd',
927 'display_id': 'FaintLightGullWholeWheat',
929 'title': 'EA Play 2016 Live from the Novo Theatre',
930 'thumbnail': r
're:^https?://.*\.jpg',
931 'timestamp': 1465767393,
932 'upload_date': '20160612',
934 'uploader': 'stereotype_',
935 'uploader_id': '43566419',
939 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
940 'only_matching': True,
942 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
943 'only_matching': True,
945 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
946 'only_matching': True,
948 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
949 'only_matching': True,
951 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
952 'only_matching': True,
955 def _real_extract(self
, url
):
956 video_id
= self
._match
_id
(url
)
958 clip
= self
._download
_gql
(
960 'operationName': 'VideoAccessToken_Clip',
965 'Downloading clip access token GraphQL')[0]['data']['clip']
968 raise ExtractorError(
969 'This clip is no longer available', expected
=True)
972 'sig': clip
['playbackAccessToken']['signature'],
973 'token': clip
['playbackAccessToken']['value'],
976 data
= self
._download
_base
_gql
(
990 tiny: thumbnailURL(width: 86, height: 45)
991 small: thumbnailURL(width: 260, height: 147)
992 medium: thumbnailURL(width: 480, height: 272)
1001 }''' % video_id
}, 'Downloading clip GraphQL', fatal
=False)
1004 clip
= try_get(data
, lambda x
: x
['data']['clip'], dict) or clip
1007 for option
in clip
.get('videoQualities', []):
1008 if not isinstance(option
, dict):
1010 source
= url_or_none(option
.get('sourceURL'))
1014 'url': update_url_query(source
, access_query
),
1015 'format_id': option
.get('quality'),
1016 'height': int_or_none(option
.get('quality')),
1017 'fps': int_or_none(option
.get('frameRate')),
1019 self
._sort
_formats
(formats
)
1022 for thumbnail_id
in ('tiny', 'small', 'medium'):
1023 thumbnail_url
= clip
.get(thumbnail_id
)
1024 if not thumbnail_url
:
1028 'url': thumbnail_url
,
1030 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
1033 'height': int(mobj
.group(2)),
1034 'width': int(mobj
.group(1)),
1036 thumbnails
.append(thumb
)
1039 'id': clip
.get('id') or video_id
,
1040 'display_id': video_id
,
1041 'title': clip
.get('title') or video_id
,
1043 'duration': int_or_none(clip
.get('durationSeconds')),
1044 'view_count': int_or_none(clip
.get('viewCount')),
1045 'timestamp': unified_timestamp(clip
.get('createdAt')),
1046 'thumbnails': thumbnails
,
1047 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], compat_str
),
1048 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], compat_str
),
1049 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], compat_str
),