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,
59 kwargs['headers'] = headers
60 response = self._download_json(
61 '%s/%s' % (self._API_BASE, path), item_id,
62 *args, **compat_kwargs(kwargs))
63 self._handle_error(response)
66 def _real_initialize(self):
70 username, password = self._get_login_info()
76 'Unable to login. Twitch said: %s' % message, expected=True)
78 def login_step(page, urlh, note, data):
79 form = self._hidden_inputs(page)
82 page_url = urlh.geturl()
83 post_url = self._search_regex(
84 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
85 'post url', default=self._LOGIN_POST_URL, group='url')
86 post_url = urljoin(page_url, post_url)
91 'Content-Type': 'text/plain;charset=UTF-8',
94 response = self._download_json(
95 post_url, None, note, data=json.dumps(form).encode(),
96 headers=headers, expected_status=400)
97 error = response.get('error_description') or response.get('error_code')
101 if 'Authenticated successfully' in response.get('message', ''):
104 redirect_url = urljoin(
106 response.get('redirect') or response['redirect_path'])
107 return self._download_webpage_handle(
108 redirect_url, None, 'Downloading login redirect page',
111 login_page, handle = self._download_webpage_handle(
112 self._LOGIN_FORM_URL, None, 'Downloading login page')
114 # Some TOR nodes and public proxies are blocked completely
115 if 'blacklist_message' in login_page:
116 fail(clean_html(login_page))
118 redirect_page, handle = login_step(
119 login_page, handle, 'Logging in', {
120 'username': username,
121 'password': password,
122 'client_id': self._CLIENT_ID,
126 if not redirect_page:
129 if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
130 # TODO: Add mechanism to request an SMS or phone call
131 tfa_token = self._get_tfa_info('two-factor authentication token')
132 login_step(redirect_page, handle, 'Submitting TFA token', {
133 'authy_token': tfa_token,
134 'remember_2fa': 'true',
137 def _prefer_source(self, formats):
139 source = next(f for f in formats if f['format_id'] == 'Source')
140 source['quality'] = 10
141 except StopIteration:
143 if '/chunked/' in f['url']:
146 'format_note': 'Source',
148 self._sort_formats(formats)
151 class TwitchItemBaseIE(TwitchBaseIE):
152 def _download_info(self, item, item_id):
153 return self._extract_info(self._call_api(
154 'kraken/videos/%s%s' % (item, item_id), item_id,
155 'Downloading %s info JSON' % self._ITEM_TYPE))
157 def _extract_media(self, item_id):
158 info = self._download_info(self._ITEM_SHORTCUT, item_id)
159 response = self._call_api(
160 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
161 'Downloading %s playlist JSON' % self._ITEM_TYPE)
163 chunks = response['chunks']
164 qualities = list(chunks.keys())
165 for num, fragment in enumerate(zip(*chunks.values()), start=1):
167 for fmt_num, fragment_fmt in enumerate(fragment):
168 format_id = qualities[fmt_num]
170 'url': fragment_fmt['url'],
171 'format_id': format_id,
172 'quality': 1 if format_id == 'live' else 0,
174 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
176 fmt['height'] = int(m.group('height'))
178 self._sort_formats(formats)
180 entry['id'] = '%s_%d' % (entry['id'], num)
181 entry['title'] = '%s part %d' % (entry['title'], num)
182 entry['formats'] = formats
183 entries.append(entry)
184 return self.playlist_result(entries, info['id'], info['title'])
186 def _extract_info(self, info):
187 status = info.get('status')
188 if status == 'recording':
190 elif status == 'recorded':
194 _QUALITIES = ('small', 'medium', 'large')
195 quality_key = qualities(_QUALITIES)
197 preview = info.get('preview')
198 if isinstance(preview, dict):
199 for thumbnail_id, thumbnail_url in preview.items():
200 thumbnail_url = url_or_none(thumbnail_url)
201 if not thumbnail_url:
203 if thumbnail_id not in _QUALITIES:
206 'url': thumbnail_url,
207 'preference': quality_key(thumbnail_id),
211 'title': info.get('title') or 'Untitled Broadcast',
212 'description': info.get('description'),
213 'duration': int_or_none(info.get('length')),
214 'thumbnails': thumbnails,
215 'uploader': info.get('channel', {}).get('display_name'),
216 'uploader_id': info.get('channel', {}).get('name'),
217 'timestamp': parse_iso8601(info.get('recorded_at')),
218 'view_count': int_or_none(info.get('views')),
222 def _real_extract(self, url):
223 return self._extract_media(self._match_id(url))
226 class TwitchVideoIE(TwitchItemBaseIE):
227 IE_NAME = 'twitch:video'
228 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
233 'url': 'http://www.twitch.tv/riotgames/b/577357806',
236 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
238 'playlist_mincount': 12,
239 'skip': 'HTTP Error 404: Not Found',
243 class TwitchChapterIE(TwitchItemBaseIE):
244 IE_NAME = 'twitch:chapter'
245 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
246 _ITEM_TYPE = 'chapter'
250 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
253 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
255 'playlist_mincount': 3,
256 'skip': 'HTTP Error 404: Not Found',
258 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
259 'only_matching': True,
263 class TwitchVodIE(TwitchItemBaseIE):
264 IE_NAME = 'twitch:vod'
265 _VALID_URL = r'''(?x)
268 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
269 player\.twitch\.tv/\?.*?\bvideo=v?
277 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
281 'title': 'LCK Summer Split - Week 6 Day 1',
282 'thumbnail': r're:^https?://.*\.jpg$',
284 'timestamp': 1435131709,
285 'upload_date': '20150624',
286 'uploader': 'Riot Games',
287 'uploader_id': 'riotgames',
293 'skip_download': True,
296 # Untitled broadcast (title is None)
297 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
301 'title': 'Untitled Broadcast',
302 'thumbnail': r're:^https?://.*\.jpg$',
304 'timestamp': 1439746708,
305 'upload_date': '20150816',
306 'uploader': 'BelkAO_o',
307 'uploader_id': 'belkao_o',
312 'skip_download': True,
314 'skip': 'HTTP Error 404: Not Found',
316 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
317 'only_matching': True,
319 'url': 'https://www.twitch.tv/videos/6528877',
320 'only_matching': True,
322 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
323 'only_matching': True,
325 'url': 'https://www.twitch.tv/northernlion/video/291940395',
326 'only_matching': True,
328 'url': 'https://player.twitch.tv/?video=480452374',
329 'only_matching': True,
332 def _real_extract(self, url):
333 item_id = self._match_id(url)
335 info = self._download_info(self._ITEM_SHORTCUT, item_id)
336 access_token = self._call_api(
337 'api/vods/%s/access_token' % item_id, item_id,
338 'Downloading %s access token' % self._ITEM_TYPE)
340 formats = self._extract_m3u8_formats(
341 '%s/vod/%s.m3u8?%s' % (
342 self._USHER_BASE, item_id,
343 compat_urllib_parse_urlencode({
344 'allow_source': 'true',
345 'allow_audio_only': 'true',
346 'allow_spectre': 'true',
347 'player': 'twitchweb',
348 'playlist_include_framerate': 'true',
349 'nauth': access_token['token'],
350 'nauthsig': access_token['sig'],
352 item_id, 'mp4', entry_protocol='m3u8_native')
354 self._prefer_source(formats)
355 info['formats'] = formats
357 parsed_url = compat_urllib_parse_urlparse(url)
358 query = compat_parse_qs(parsed_url.query)
360 info['start_time'] = parse_duration(query['t'][0])
362 if info.get('timestamp') is not None:
363 info['subtitles'] = {
365 'url': update_url_query(
366 'https://api.twitch.tv/v5/videos/%s/comments' % item_id, {
367 'client_id': self._CLIENT_ID,
376 class TwitchPlaylistBaseIE(TwitchBaseIE):
377 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
380 def _extract_playlist(self, channel_id):
381 info = self._call_api(
382 'kraken/channels/%s' % channel_id,
383 channel_id, 'Downloading channel info JSON')
384 channel_name = info.get('display_name') or info.get('name')
387 limit = self._PAGE_LIMIT
388 broken_paging_detected = False
389 counter_override = None
390 for counter in itertools.count(1):
391 response = self._call_api(
392 self._PLAYLIST_PATH % (channel_id, offset, limit),
394 'Downloading %s JSON page %s'
395 % (self._PLAYLIST_TYPE, counter_override or counter))
396 page_entries = self._extract_playlist_page(response)
399 total = int_or_none(response.get('_total'))
400 # Since the beginning of March 2016 twitch's paging mechanism
401 # is completely broken on the twitch side. It simply ignores
402 # a limit and returns the whole offset number of videos.
403 # Working around by just requesting all videos at once.
404 # Upd: pagination bug was fixed by twitch on 15.03.2016.
405 if not broken_paging_detected and total and len(page_entries) > limit:
407 'Twitch pagination is broken on twitch side, requesting all videos at once',
409 broken_paging_detected = True
411 counter_override = '(all at once)'
413 entries.extend(page_entries)
414 if broken_paging_detected or total and len(page_entries) >= total:
417 return self.playlist_result(
418 [self._make_url_result(entry) for entry in orderedSet(entries)],
419 channel_id, channel_name)
421 def _make_url_result(self, url):
423 video_id = 'v%s' % TwitchVodIE._match_id(url)
424 return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
425 except AssertionError:
426 return self.url_result(url)
428 def _extract_playlist_page(self, response):
429 videos = response.get('videos')
430 return [video['url'] for video in videos] if videos else []
432 def _real_extract(self, url):
433 return self._extract_playlist(self._match_id(url))
436 class TwitchProfileIE(TwitchPlaylistBaseIE):
437 IE_NAME = 'twitch:profile'
438 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
439 _PLAYLIST_TYPE = 'profile'
442 'url': 'http://www.twitch.tv/vanillatv/profile',
445 'title': 'VanillaTV',
447 'playlist_mincount': 412,
449 'url': 'http://m.twitch.tv/vanillatv/profile',
450 'only_matching': True,
454 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
455 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
456 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
459 class TwitchAllVideosIE(TwitchVideosBaseIE):
460 IE_NAME = 'twitch:videos:all'
461 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
462 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
463 _PLAYLIST_TYPE = 'all videos'
466 'url': 'https://www.twitch.tv/spamfish/videos/all',
471 'playlist_mincount': 869,
473 'url': 'https://m.twitch.tv/spamfish/videos/all',
474 'only_matching': True,
478 class TwitchUploadsIE(TwitchVideosBaseIE):
479 IE_NAME = 'twitch:videos:uploads'
480 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
481 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
482 _PLAYLIST_TYPE = 'uploads'
485 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
490 'playlist_mincount': 0,
492 'url': 'https://m.twitch.tv/spamfish/videos/uploads',
493 'only_matching': True,
497 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
498 IE_NAME = 'twitch:videos:past-broadcasts'
499 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
500 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
501 _PLAYLIST_TYPE = 'past broadcasts'
504 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
509 'playlist_mincount': 0,
511 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
512 'only_matching': True,
516 class TwitchHighlightsIE(TwitchVideosBaseIE):
517 IE_NAME = 'twitch:videos:highlights'
518 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
519 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
520 _PLAYLIST_TYPE = 'highlights'
523 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
528 'playlist_mincount': 805,
530 'url': 'https://m.twitch.tv/spamfish/videos/highlights',
531 'only_matching': True,
535 class TwitchStreamIE(TwitchBaseIE):
536 IE_NAME = 'twitch:stream'
537 _VALID_URL = r'''(?x)
540 (?:(?:www|go|m)\.)?twitch\.tv/|
541 player\.twitch\.tv/\?.*?\bchannel=
547 'url': 'http://www.twitch.tv/shroomztv',
550 'display_id': 'shroomztv',
552 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
553 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
555 'timestamp': 1421928037,
556 'upload_date': '20150122',
557 'uploader': 'ShroomzTV',
558 'uploader_id': 'shroomztv',
563 'skip_download': True,
566 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
567 'only_matching': True,
569 'url': 'https://player.twitch.tv/?channel=lotsofs',
570 'only_matching': True,
572 'url': 'https://go.twitch.tv/food',
573 'only_matching': True,
575 'url': 'https://m.twitch.tv/food',
576 'only_matching': True,
580 def suitable(cls, url):
582 if any(ie.suitable(url) for ie in (
589 TwitchPastBroadcastsIE,
592 else super(TwitchStreamIE, cls).suitable(url))
594 def _real_extract(self, url):
595 channel_name = self._match_id(url)
597 access_token = self._call_api(
598 'api/channels/%s/access_token' % channel_name, channel_name,
599 'Downloading access token JSON')
601 token = access_token['token']
602 channel_id = compat_str(self._parse_json(
603 token, channel_name)['channel_id'])
605 stream = self._call_api(
606 'kraken/streams/%s?stream_type=all' % channel_id,
607 channel_id, 'Downloading stream JSON').get('stream')
610 raise ExtractorError('%s is offline' % channel_id, expected=True)
612 # Channel name may be typed if different case than the original channel name
613 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
614 # an invalid m3u8 URL. Working around by use of original channel name from stream
615 # JSON and fallback to lowercase if it's not available.
616 channel_name = try_get(
617 stream, lambda x: x['channel']['name'],
618 compat_str) or channel_name.lower()
621 'allow_source': 'true',
622 'allow_audio_only': 'true',
623 'allow_spectre': 'true',
624 'p': random.randint(1000000, 10000000),
625 'player': 'twitchweb',
626 'playlist_include_framerate': 'true',
627 'segment_preference': '4',
628 'sig': access_token['sig'].encode('utf-8'),
629 'token': token.encode('utf-8'),
631 formats = self._extract_m3u8_formats(
632 '%s/api/channel/hls/%s.m3u8?%s'
633 % (self._USHER_BASE, channel_name, compat_urllib_parse_urlencode(query)),
635 self._prefer_source(formats)
637 view_count = stream.get('viewers')
638 timestamp = parse_iso8601(stream.get('created_at'))
640 channel = stream['channel']
641 title = self._live_title(channel.get('display_name') or channel.get('name'))
642 description = channel.get('status')
645 for thumbnail_key, thumbnail_url in stream['preview'].items():
646 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
650 'url': thumbnail_url,
651 'width': int(m.group('width')),
652 'height': int(m.group('height')),
656 'id': str_or_none(stream.get('_id')) or channel_id,
657 'display_id': channel_name,
659 'description': description,
660 'thumbnails': thumbnails,
661 'uploader': channel.get('display_name'),
662 'uploader_id': channel.get('name'),
663 'timestamp': timestamp,
664 'view_count': view_count,
670 class TwitchClipsIE(TwitchBaseIE):
671 IE_NAME = 'twitch:clips'
672 _VALID_URL = r'''(?x)
675 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
676 (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/
682 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
683 'md5': '761769e1eafce0ffebfb4089cb3847cd',
687 'title': 'EA Play 2016 Live from the Novo Theatre',
688 'thumbnail': r're:^https?://.*\.jpg',
689 'timestamp': 1465767393,
690 'upload_date': '20160612',
692 'uploader': 'stereotype_',
693 'uploader_id': '43566419',
697 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
698 'only_matching': True,
700 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
701 'only_matching': True,
703 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
704 'only_matching': True,
706 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
707 'only_matching': True,
709 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
710 'only_matching': True,
713 def _real_extract(self, url):
714 video_id = self._match_id(url)
716 clip = self._download_json(
717 'https://gql.twitch.tv/gql', video_id, data=json.dumps({
730 tiny: thumbnailURL(width: 86, height: 45)
731 small: thumbnailURL(width: 260, height: 147)
732 medium: thumbnailURL(width: 480, height: 272)
742 }).encode(), headers={
743 'Client-ID': self._CLIENT_ID,
747 raise ExtractorError(
748 'This clip is no longer available', expected=True)
751 for option in clip.get('videoQualities', []):
752 if not isinstance(option, dict):
754 source = url_or_none(option.get('sourceURL'))
759 'format_id': option.get('quality'),
760 'height': int_or_none(option.get('quality')),
761 'fps': int_or_none(option.get('frameRate')),
763 self._sort_formats(formats)
766 for thumbnail_id in ('tiny', 'small', 'medium'):
767 thumbnail_url = clip.get(thumbnail_id)
768 if not thumbnail_url:
772 'url': thumbnail_url,
774 mobj = re.search(r'-(\d+)x(\d+)\.', thumbnail_url)
777 'height': int(mobj.group(2)),
778 'width': int(mobj.group(1)),
780 thumbnails.append(thumb)
783 'id': clip.get('id') or video_id,
784 'title': clip.get('title') or video_id,
786 'duration': int_or_none(clip.get('durationSeconds')),
787 'views': int_or_none(clip.get('viewCount')),
788 'timestamp': unified_timestamp(clip.get('createdAt')),
789 'thumbnails': thumbnails,
790 'creator': try_get(clip, lambda x: x['broadcaster']['displayName'], compat_str),
791 'uploader': try_get(clip, lambda x: x['curator']['displayName'], compat_str),
792 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),