2 from __future__
import unicode_literals
9 from .common
import InfoExtractor
10 from ..compat
import (
14 compat_urllib_parse_urlencode
,
15 compat_urllib_parse_urlparse
,
34 class TwitchBaseIE(InfoExtractor
):
35 _VALID_URL_BASE
= r
'https?://(?:(?:www|go|m)\.)?twitch\.tv'
37 _API_BASE
= 'https://api.twitch.tv'
38 _USHER_BASE
= 'https://usher.ttvnw.net'
39 _LOGIN_FORM_URL
= 'https://www.twitch.tv/login'
40 _LOGIN_POST_URL
= 'https://passport.twitch.tv/login'
41 _CLIENT_ID
= 'kimne78kx3ncx6brgo4mv6wki5h1ko'
42 _NETRC_MACHINE
= 'twitch'
44 def _handle_error(self
, response
):
45 if not isinstance(response
, dict):
47 error
= response
.get('error')
50 '%s returned error: %s - %s' % (self
.IE_NAME
, error
, response
.get('message')),
53 def _call_api(self
, path
, item_id
, *args
, **kwargs
):
54 headers
= kwargs
.get('headers', {}).copy()
56 'Accept': 'application/vnd.twitchtv.v5+json; charset=UTF-8',
57 'Client-ID': self
._CLIENT
_ID
,
61 'expected_status': (400, 410),
63 response
= self
._download
_json
(
64 '%s/%s' % (self
._API
_BASE
, path
), item_id
,
65 *args
, **compat_kwargs(kwargs
))
66 self
._handle
_error
(response
)
69 def _real_initialize(self
):
73 username
, password
= self
._get
_login
_info
()
79 'Unable to login. Twitch said: %s' % message
, expected
=True)
81 def login_step(page
, urlh
, note
, data
):
82 form
= self
._hidden
_inputs
(page
)
85 page_url
= urlh
.geturl()
86 post_url
= self
._search
_regex
(
87 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page,
88 'post url
', default=self._LOGIN_POST_URL, group='url
')
89 post_url = urljoin(page_url, post_url)
94 'Content
-Type
': 'text
/plain
;charset
=UTF
-8',
97 response = self._download_json(
98 post_url, None, note, data=json.dumps(form).encode(),
99 headers=headers, expected_status=400)
100 error = response.get('error_description
') or response.get('error_code
')
104 if 'Authenticated successfully
' in response.get('message
', ''):
107 redirect_url = urljoin(
109 response.get('redirect
') or response['redirect_path
'])
110 return self._download_webpage_handle(
111 redirect_url, None, 'Downloading login redirect page
',
114 login_page, handle = self._download_webpage_handle(
115 self._LOGIN_FORM_URL, None, 'Downloading login page
')
117 # Some TOR nodes and public proxies are blocked completely
118 if 'blacklist_message
' in login_page:
119 fail(clean_html(login_page))
121 redirect_page, handle = login_step(
122 login_page, handle, 'Logging
in', {
123 'username
': username,
124 'password
': password,
125 'client_id
': self._CLIENT_ID,
129 if not redirect_page:
132 if re.search(r'(?i
)<form
[^
>]+id="two-factor-submit"', redirect_page) is not None:
133 # TODO: Add mechanism to request an SMS or phone call
134 tfa_token = self._get_tfa_info('two
-factor authentication token
')
135 login_step(redirect_page, handle, 'Submitting TFA token
', {
136 'authy_token
': tfa_token,
137 'remember_2fa
': 'true
',
140 def _prefer_source(self, formats):
142 source = next(f for f in formats if f['format_id
'] == 'Source
')
143 source['quality
'] = 10
144 except StopIteration:
146 if '/chunked
/' in f['url
']:
149 'format_note
': 'Source
',
151 self._sort_formats(formats)
154 class TwitchItemBaseIE(TwitchBaseIE):
155 def _download_info(self, item, item_id):
156 return self._extract_info(self._call_api(
157 'kraken
/videos
/%s%s' % (item, item_id), item_id,
158 'Downloading
%s info JSON
' % self._ITEM_TYPE))
160 def _extract_media(self, item_id):
161 info = self._download_info(self._ITEM_SHORTCUT, item_id)
162 response = self._call_api(
163 'api
/videos
/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
164 'Downloading
%s playlist JSON
' % self._ITEM_TYPE)
166 chunks = response['chunks
']
167 qualities = list(chunks.keys())
168 for num, fragment in enumerate(zip(*chunks.values()), start=1):
170 for fmt_num, fragment_fmt in enumerate(fragment):
171 format_id = qualities[fmt_num]
173 'url
': fragment_fmt['url
'],
174 'format_id
': format_id,
175 'quality
': 1 if format_id == 'live
' else 0,
177 m = re.search(r'^
(?P
<height
>\d
+)[Pp
]', format_id)
179 fmt['height
'] = int(m.group('height
'))
181 self._sort_formats(formats)
183 entry['id'] = '%s_%d' % (entry['id'], num)
184 entry['title
'] = '%s part
%d' % (entry['title
'], num)
185 entry['formats
'] = formats
186 entries.append(entry)
187 return self.playlist_result(entries, info['id'], info['title
'])
189 def _extract_info(self, info):
190 status = info.get('status
')
191 if status == 'recording
':
193 elif status == 'recorded
':
197 _QUALITIES = ('small
', 'medium
', 'large
')
198 quality_key = qualities(_QUALITIES)
200 preview = info.get('preview
')
201 if isinstance(preview, dict):
202 for thumbnail_id, thumbnail_url in preview.items():
203 thumbnail_url = url_or_none(thumbnail_url)
204 if not thumbnail_url:
206 if thumbnail_id not in _QUALITIES:
209 'url
': thumbnail_url,
210 'preference
': quality_key(thumbnail_id),
214 'title
': info.get('title
') or 'Untitled Broadcast
',
215 'description
': info.get('description
'),
216 'duration
': int_or_none(info.get('length
')),
217 'thumbnails
': thumbnails,
218 'uploader
': info.get('channel
', {}).get('display_name
'),
219 'uploader_id
': info.get('channel
', {}).get('name
'),
220 'timestamp
': parse_iso8601(info.get('recorded_at
')),
221 'view_count
': int_or_none(info.get('views
')),
225 def _real_extract(self, url):
226 return self._extract_media(self._match_id(url))
229 class TwitchVideoIE(TwitchItemBaseIE):
230 IE_NAME = 'twitch
:video
'
231 _VALID_URL = r'%s/[^
/]+/b
/(?P
<id>\d
+)' % TwitchBaseIE._VALID_URL_BASE
236 'url
': 'http
://www
.twitch
.tv
/riotgames
/b
/577357806',
239 'title
': 'Worlds Semifinals
- Star Horn Royal Club vs
. OMG
',
241 'playlist_mincount
': 12,
242 'skip
': 'HTTP Error
404: Not Found
',
246 class TwitchChapterIE(TwitchItemBaseIE):
247 IE_NAME = 'twitch
:chapter
'
248 _VALID_URL = r'%s/[^
/]+/c
/(?P
<id>\d
+)' % TwitchBaseIE._VALID_URL_BASE
249 _ITEM_TYPE = 'chapter
'
253 'url
': 'http
://www
.twitch
.tv
/acracingleague
/c
/5285812',
256 'title
': 'ACRL Off Season
- Sports Cars
@ Nordschleife
',
258 'playlist_mincount
': 3,
259 'skip
': 'HTTP Error
404: Not Found
',
261 'url
': 'http
://www
.twitch
.tv
/tsm_theoddone
/c
/2349361',
262 'only_matching
': True,
266 class TwitchVodIE(TwitchItemBaseIE):
267 IE_NAME = 'twitch
:vod
'
268 _VALID_URL = r'''(?x)
271 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
272 player\.twitch\.tv/\?.*?\bvideo=v?
280 'url
': 'http
://www
.twitch
.tv
/riotgames
/v
/6528877?t
=5m10s
',
284 'title
': 'LCK Summer Split
- Week
6 Day
1',
285 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
287 'timestamp
': 1435131709,
288 'upload_date
': '20150624',
289 'uploader
': 'Riot Games
',
290 'uploader_id
': 'riotgames
',
296 'skip_download
': True,
299 # Untitled broadcast (title is None)
300 'url
': 'http
://www
.twitch
.tv
/belkao_o
/v
/11230755',
304 'title
': 'Untitled Broadcast
',
305 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
307 'timestamp
': 1439746708,
308 'upload_date
': '20150816',
309 'uploader
': 'BelkAO_o
',
310 'uploader_id
': 'belkao_o
',
315 'skip_download
': True,
317 'skip
': 'HTTP Error
404: Not Found
',
319 'url
': 'http
://player
.twitch
.tv
/?t
=5m10s
&video
=v6528877
',
320 'only_matching
': True,
322 'url
': 'https
://www
.twitch
.tv
/videos
/6528877',
323 'only_matching
': True,
325 'url
': 'https
://m
.twitch
.tv
/beagsandjam
/v
/247478721',
326 'only_matching
': True,
328 'url
': 'https
://www
.twitch
.tv
/northernlion
/video
/291940395',
329 'only_matching
': True,
331 'url
': 'https
://player
.twitch
.tv
/?video
=480452374',
332 'only_matching
': True,
335 def _real_extract(self, url):
336 item_id = self._match_id(url)
338 info = self._download_info(self._ITEM_SHORTCUT, item_id)
339 access_token = self._call_api(
340 'api
/vods
/%s/access_token
' % item_id, item_id,
341 'Downloading
%s access token
' % self._ITEM_TYPE)
343 formats = self._extract_m3u8_formats(
344 '%s/vod
/%s.m3u8?
%s' % (
345 self._USHER_BASE, item_id,
346 compat_urllib_parse_urlencode({
347 'allow_source
': 'true
',
348 'allow_audio_only
': 'true
',
349 'allow_spectre
': 'true
',
350 'player
': 'twitchweb
',
351 'playlist_include_framerate
': 'true
',
352 'nauth
': access_token['token
'],
353 'nauthsig
': access_token['sig
'],
355 item_id, 'mp4
', entry_protocol='m3u8_native
')
357 self._prefer_source(formats)
358 info['formats
'] = formats
360 parsed_url = compat_urllib_parse_urlparse(url)
361 query = compat_parse_qs(parsed_url.query)
363 info['start_time
'] = parse_duration(query['t
'][0])
365 if info.get('timestamp
') is not None:
366 info['subtitles
'] = {
368 'url
': update_url_query(
369 'https
://api
.twitch
.tv
/v5
/videos
/%s/comments
' % item_id, {
370 'client_id
': self._CLIENT_ID,
379 class TwitchPlaylistBaseIE(TwitchBaseIE):
380 _PLAYLIST_PATH = 'kraken
/channels
/%s/videos
/?offset
=%d&limit
=%d'
383 def _extract_playlist(self, channel_id):
384 info = self._call_api(
385 'kraken
/channels
/%s' % channel_id,
386 channel_id, 'Downloading channel info JSON
')
387 channel_name = info.get('display_name
') or info.get('name
')
390 limit = self._PAGE_LIMIT
391 broken_paging_detected = False
392 counter_override = None
393 for counter in itertools.count(1):
394 response = self._call_api(
395 self._PLAYLIST_PATH % (channel_id, offset, limit),
397 'Downloading
%s JSON page
%s'
398 % (self._PLAYLIST_TYPE, counter_override or counter))
399 page_entries = self._extract_playlist_page(response)
402 total = int_or_none(response.get('_total
'))
403 # Since the beginning of March 2016 twitch's paging mechanism
404 # is completely broken on the twitch side. It simply ignores
405 # a limit and returns the whole offset number of videos.
406 # Working around by just requesting all videos at once.
407 # Upd: pagination bug was fixed by twitch on 15.03.2016.
408 if not broken_paging_detected
and total
and len(page_entries
) > limit
:
410 'Twitch pagination is broken on twitch side, requesting all videos at once',
412 broken_paging_detected
= True
414 counter_override
= '(all at once)'
416 entries
.extend(page_entries
)
417 if broken_paging_detected
or total
and len(page_entries
) >= total
:
420 return self
.playlist_result(
421 [self
._make
_url
_result
(entry
) for entry
in orderedSet(entries
)],
422 channel_id
, channel_name
)
424 def _make_url_result(self
, url
):
426 video_id
= 'v%s' % TwitchVodIE
._match
_id
(url
)
427 return self
.url_result(url
, TwitchVodIE
.ie_key(), video_id
=video_id
)
428 except AssertionError:
429 return self
.url_result(url
)
431 def _extract_playlist_page(self
, response
):
432 videos
= response
.get('videos')
433 return [video
['url'] for video
in videos
] if videos
else []
435 def _real_extract(self
, url
):
436 return self
._extract
_playlist
(self
._match
_id
(url
))
439 class TwitchProfileIE(TwitchPlaylistBaseIE
):
440 IE_NAME
= 'twitch:profile'
441 _VALID_URL
= r
'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE
._VALID
_URL
_BASE
442 _PLAYLIST_TYPE
= 'profile'
445 'url': 'http://www.twitch.tv/vanillatv/profile',
448 'title': 'VanillaTV',
450 'playlist_mincount': 412,
452 'url': 'http://m.twitch.tv/vanillatv/profile',
453 'only_matching': True,
457 class TwitchVideosBaseIE(TwitchPlaylistBaseIE
):
458 _VALID_URL_VIDEOS_BASE
= r
'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE
._VALID
_URL
_BASE
459 _PLAYLIST_PATH
= TwitchPlaylistBaseIE
._PLAYLIST
_PATH
+ '&broadcast_type='
462 class TwitchAllVideosIE(TwitchVideosBaseIE
):
463 IE_NAME
= 'twitch:videos:all'
464 _VALID_URL
= r
'%s/all' % TwitchVideosBaseIE
._VALID
_URL
_VIDEOS
_BASE
465 _PLAYLIST_PATH
= TwitchVideosBaseIE
._PLAYLIST
_PATH
+ 'archive,upload,highlight'
466 _PLAYLIST_TYPE
= 'all videos'
469 'url': 'https://www.twitch.tv/spamfish/videos/all',
474 'playlist_mincount': 869,
476 'url': 'https://m.twitch.tv/spamfish/videos/all',
477 'only_matching': True,
481 class TwitchUploadsIE(TwitchVideosBaseIE
):
482 IE_NAME
= 'twitch:videos:uploads'
483 _VALID_URL
= r
'%s/uploads' % TwitchVideosBaseIE
._VALID
_URL
_VIDEOS
_BASE
484 _PLAYLIST_PATH
= TwitchVideosBaseIE
._PLAYLIST
_PATH
+ 'upload'
485 _PLAYLIST_TYPE
= 'uploads'
488 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
493 'playlist_mincount': 0,
495 'url': 'https://m.twitch.tv/spamfish/videos/uploads',
496 'only_matching': True,
500 class TwitchPastBroadcastsIE(TwitchVideosBaseIE
):
501 IE_NAME
= 'twitch:videos:past-broadcasts'
502 _VALID_URL
= r
'%s/past-broadcasts' % TwitchVideosBaseIE
._VALID
_URL
_VIDEOS
_BASE
503 _PLAYLIST_PATH
= TwitchVideosBaseIE
._PLAYLIST
_PATH
+ 'archive'
504 _PLAYLIST_TYPE
= 'past broadcasts'
507 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
512 'playlist_mincount': 0,
514 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
515 'only_matching': True,
519 class TwitchHighlightsIE(TwitchVideosBaseIE
):
520 IE_NAME
= 'twitch:videos:highlights'
521 _VALID_URL
= r
'%s/highlights' % TwitchVideosBaseIE
._VALID
_URL
_VIDEOS
_BASE
522 _PLAYLIST_PATH
= TwitchVideosBaseIE
._PLAYLIST
_PATH
+ 'highlight'
523 _PLAYLIST_TYPE
= 'highlights'
526 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
531 'playlist_mincount': 805,
533 'url': 'https://m.twitch.tv/spamfish/videos/highlights',
534 'only_matching': True,
538 class TwitchStreamIE(TwitchBaseIE
):
539 IE_NAME
= 'twitch:stream'
540 _VALID_URL
= r
'''(?x)
543 (?:(?:www|go|m)\.)?twitch\.tv/|
544 player\.twitch\.tv/\?.*?\bchannel=
550 'url': 'http://www.twitch.tv/shroomztv',
553 'display_id': 'shroomztv',
555 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
556 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
558 'timestamp': 1421928037,
559 'upload_date': '20150122',
560 'uploader': 'ShroomzTV',
561 'uploader_id': 'shroomztv',
566 'skip_download': True,
569 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
570 'only_matching': True,
572 'url': 'https://player.twitch.tv/?channel=lotsofs',
573 'only_matching': True,
575 'url': 'https://go.twitch.tv/food',
576 'only_matching': True,
578 'url': 'https://m.twitch.tv/food',
579 'only_matching': True,
583 def suitable(cls
, url
):
585 if any(ie
.suitable(url
) for ie
in (
592 TwitchPastBroadcastsIE
,
595 else super(TwitchStreamIE
, cls
).suitable(url
))
597 def _real_extract(self
, url
):
598 channel_name
= self
._match
_id
(url
)
600 access_token
= self
._call
_api
(
601 'api/channels/%s/access_token' % channel_name
, channel_name
,
602 'Downloading access token JSON')
604 token
= access_token
['token']
605 channel_id
= compat_str(self
._parse
_json
(
606 token
, channel_name
)['channel_id'])
608 stream
= self
._call
_api
(
609 'kraken/streams/%s?stream_type=all' % channel_id
,
610 channel_id
, 'Downloading stream JSON').get('stream')
613 raise ExtractorError('%s is offline' % channel_id
, expected
=True)
615 # Channel name may be typed if different case than the original channel name
616 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
617 # an invalid m3u8 URL. Working around by use of original channel name from stream
618 # JSON and fallback to lowercase if it's not available.
619 channel_name
= try_get(
620 stream
, lambda x
: x
['channel']['name'],
621 compat_str
) or channel_name
.lower()
624 'allow_source': 'true',
625 'allow_audio_only': 'true',
626 'allow_spectre': 'true',
627 'p': random
.randint(1000000, 10000000),
628 'player': 'twitchweb',
629 'playlist_include_framerate': 'true',
630 'segment_preference': '4',
631 'sig': access_token
['sig'].encode('utf-8'),
632 'token': token
.encode('utf-8'),
634 formats
= self
._extract
_m
3u8_formats
(
635 '%s/api/channel/hls/%s.m3u8?%s'
636 % (self
._USHER
_BASE
, channel_name
, compat_urllib_parse_urlencode(query
)),
638 self
._prefer
_source
(formats
)
640 view_count
= stream
.get('viewers')
641 timestamp
= parse_iso8601(stream
.get('created_at'))
643 channel
= stream
['channel']
644 title
= self
._live
_title
(channel
.get('display_name') or channel
.get('name'))
645 description
= channel
.get('status')
648 for thumbnail_key
, thumbnail_url
in stream
['preview'].items():
649 m
= re
.search(r
'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key
)
653 'url': thumbnail_url
,
654 'width': int(m
.group('width')),
655 'height': int(m
.group('height')),
659 'id': str_or_none(stream
.get('_id')) or channel_id
,
660 'display_id': channel_name
,
662 'description': description
,
663 'thumbnails': thumbnails
,
664 'uploader': channel
.get('display_name'),
665 'uploader_id': channel
.get('name'),
666 'timestamp': timestamp
,
667 'view_count': view_count
,
673 class TwitchClipsIE(TwitchBaseIE
):
674 IE_NAME
= 'twitch:clips'
675 _VALID_URL
= r
'''(?x)
678 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
679 (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/
685 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
686 'md5': '761769e1eafce0ffebfb4089cb3847cd',
690 'title': 'EA Play 2016 Live from the Novo Theatre',
691 'thumbnail': r
're:^https?://.*\.jpg',
692 'timestamp': 1465767393,
693 'upload_date': '20160612',
695 'uploader': 'stereotype_',
696 'uploader_id': '43566419',
700 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
701 'only_matching': True,
703 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
704 'only_matching': True,
706 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
707 'only_matching': True,
709 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
710 'only_matching': True,
712 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
713 'only_matching': True,
716 def _real_extract(self
, url
):
717 video_id
= self
._match
_id
(url
)
719 clip
= self
._download
_json
(
720 'https://gql.twitch.tv/gql', video_id
, data
=json
.dumps({
733 tiny: thumbnailURL(width: 86, height: 45)
734 small: thumbnailURL(width: 260, height: 147)
735 medium: thumbnailURL(width: 480, height: 272)
745 }).encode(), headers
={
746 'Client-ID': self
._CLIENT
_ID
,
750 raise ExtractorError(
751 'This clip is no longer available', expected
=True)
754 for option
in clip
.get('videoQualities', []):
755 if not isinstance(option
, dict):
757 source
= url_or_none(option
.get('sourceURL'))
762 'format_id': option
.get('quality'),
763 'height': int_or_none(option
.get('quality')),
764 'fps': int_or_none(option
.get('frameRate')),
766 self
._sort
_formats
(formats
)
769 for thumbnail_id
in ('tiny', 'small', 'medium'):
770 thumbnail_url
= clip
.get(thumbnail_id
)
771 if not thumbnail_url
:
775 'url': thumbnail_url
,
777 mobj
= re
.search(r
'-(\d+)x(\d+)\.', thumbnail_url
)
780 'height': int(mobj
.group(2)),
781 'width': int(mobj
.group(1)),
783 thumbnails
.append(thumb
)
786 'id': clip
.get('id') or video_id
,
787 'title': clip
.get('title') or video_id
,
789 'duration': int_or_none(clip
.get('durationSeconds')),
790 'views': int_or_none(clip
.get('viewCount')),
791 'timestamp': unified_timestamp(clip
.get('createdAt')),
792 'thumbnails': thumbnails
,
793 'creator': try_get(clip
, lambda x
: x
['broadcaster']['displayName'], compat_str
),
794 'uploader': try_get(clip
, lambda x
: x
['curator']['displayName'], compat_str
),
795 'uploader_id': try_get(clip
, lambda x
: x
['curator']['id'], compat_str
),