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,
33 class TwitchBaseIE(InfoExtractor):
34 _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv'
36 _API_BASE = 'https://api.twitch.tv'
37 _USHER_BASE = 'https://usher.ttvnw.net'
38 _LOGIN_FORM_URL = 'https://www.twitch.tv/login'
39 _LOGIN_POST_URL = 'https://passport.twitch.tv/login'
40 _CLIENT_ID = 'kimne78kx3ncx6brgo4mv6wki5h1ko'
41 _NETRC_MACHINE = 'twitch'
43 def _handle_error(self, response):
44 if not isinstance(response, dict):
46 error = response.get('error')
49 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
52 def _call_api(self, path, item_id, *args, **kwargs):
53 headers = kwargs.get('headers', {}).copy()
55 'Accept': 'application/vnd.twitchtv.v5+json; charset=UTF-8',
56 'Client-ID': self._CLIENT_ID,
58 kwargs['headers'] = headers
59 response = self._download_json(
60 '%s/%s' % (self._API_BASE, path), item_id,
61 *args, **compat_kwargs(kwargs))
62 self._handle_error(response)
65 def _real_initialize(self):
69 username, password = self._get_login_info()
75 'Unable to login. Twitch said: %s' % message, expected=True)
77 def login_step(page, urlh, note, data):
78 form = self._hidden_inputs(page)
81 page_url = urlh.geturl()
82 post_url = self._search_regex(
83 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
84 'post url', default=self._LOGIN_POST_URL, group='url')
85 post_url = urljoin(page_url, post_url)
90 'Content-Type': 'text/plain;charset=UTF-8',
93 response = self._download_json(
94 post_url, None, note, data=json.dumps(form).encode(),
95 headers=headers, expected_status=400)
96 error = response.get('error_description') or response.get('error_code')
100 if 'Authenticated successfully' in response.get('message', ''):
103 redirect_url = urljoin(
105 response.get('redirect') or response['redirect_path'])
106 return self._download_webpage_handle(
107 redirect_url, None, 'Downloading login redirect page',
110 login_page, handle = self._download_webpage_handle(
111 self._LOGIN_FORM_URL, None, 'Downloading login page')
113 # Some TOR nodes and public proxies are blocked completely
114 if 'blacklist_message' in login_page:
115 fail(clean_html(login_page))
117 redirect_page, handle = login_step(
118 login_page, handle, 'Logging in', {
119 'username': username,
120 'password': password,
121 'client_id': self._CLIENT_ID,
125 if not redirect_page:
128 if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
129 # TODO: Add mechanism to request an SMS or phone call
130 tfa_token = self._get_tfa_info('two-factor authentication token')
131 login_step(redirect_page, handle, 'Submitting TFA token', {
132 'authy_token': tfa_token,
133 'remember_2fa': 'true',
136 def _prefer_source(self, formats):
138 source = next(f for f in formats if f['format_id'] == 'Source')
139 source['quality'] = 10
140 except StopIteration:
142 if '/chunked/' in f['url']:
145 'format_note': 'Source',
147 self._sort_formats(formats)
150 class TwitchItemBaseIE(TwitchBaseIE):
151 def _download_info(self, item, item_id):
152 return self._extract_info(self._call_api(
153 'kraken/videos/%s%s' % (item, item_id), item_id,
154 'Downloading %s info JSON' % self._ITEM_TYPE))
156 def _extract_media(self, item_id):
157 info = self._download_info(self._ITEM_SHORTCUT, item_id)
158 response = self._call_api(
159 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
160 'Downloading %s playlist JSON' % self._ITEM_TYPE)
162 chunks = response['chunks']
163 qualities = list(chunks.keys())
164 for num, fragment in enumerate(zip(*chunks.values()), start=1):
166 for fmt_num, fragment_fmt in enumerate(fragment):
167 format_id = qualities[fmt_num]
169 'url': fragment_fmt['url'],
170 'format_id': format_id,
171 'quality': 1 if format_id == 'live' else 0,
173 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
175 fmt['height'] = int(m.group('height'))
177 self._sort_formats(formats)
179 entry['id'] = '%s_%d' % (entry['id'], num)
180 entry['title'] = '%s part %d' % (entry['title'], num)
181 entry['formats'] = formats
182 entries.append(entry)
183 return self.playlist_result(entries, info['id'], info['title'])
185 def _extract_info(self, info):
186 status = info.get('status')
187 if status == 'recording':
189 elif status == 'recorded':
193 _QUALITIES = ('small', 'medium', 'large')
194 quality_key = qualities(_QUALITIES)
196 preview = info.get('preview')
197 if isinstance(preview, dict):
198 for thumbnail_id, thumbnail_url in preview.items():
199 thumbnail_url = url_or_none(thumbnail_url)
200 if not thumbnail_url:
202 if thumbnail_id not in _QUALITIES:
205 'url': thumbnail_url,
206 'preference': quality_key(thumbnail_id),
210 'title': info.get('title') or 'Untitled Broadcast',
211 'description': info.get('description'),
212 'duration': int_or_none(info.get('length')),
213 'thumbnails': thumbnails,
214 'uploader': info.get('channel', {}).get('display_name'),
215 'uploader_id': info.get('channel', {}).get('name'),
216 'timestamp': parse_iso8601(info.get('recorded_at')),
217 'view_count': int_or_none(info.get('views')),
221 def _real_extract(self, url):
222 return self._extract_media(self._match_id(url))
225 class TwitchVideoIE(TwitchItemBaseIE):
226 IE_NAME = 'twitch:video'
227 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
232 'url': 'http://www.twitch.tv/riotgames/b/577357806',
235 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
237 'playlist_mincount': 12,
238 'skip': 'HTTP Error 404: Not Found',
242 class TwitchChapterIE(TwitchItemBaseIE):
243 IE_NAME = 'twitch:chapter'
244 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
245 _ITEM_TYPE = 'chapter'
249 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
252 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
254 'playlist_mincount': 3,
255 'skip': 'HTTP Error 404: Not Found',
257 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
258 'only_matching': True,
262 class TwitchVodIE(TwitchItemBaseIE):
263 IE_NAME = 'twitch:vod'
264 _VALID_URL = r'''(?x)
267 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
268 player\.twitch\.tv/\?.*?\bvideo=v?
276 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
280 'title': 'LCK Summer Split - Week 6 Day 1',
281 'thumbnail': r're:^https?://.*\.jpg$',
283 'timestamp': 1435131709,
284 'upload_date': '20150624',
285 'uploader': 'Riot Games',
286 'uploader_id': 'riotgames',
292 'skip_download': True,
295 # Untitled broadcast (title is None)
296 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
300 'title': 'Untitled Broadcast',
301 'thumbnail': r're:^https?://.*\.jpg$',
303 'timestamp': 1439746708,
304 'upload_date': '20150816',
305 'uploader': 'BelkAO_o',
306 'uploader_id': 'belkao_o',
311 'skip_download': True,
313 'skip': 'HTTP Error 404: Not Found',
315 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
316 'only_matching': True,
318 'url': 'https://www.twitch.tv/videos/6528877',
319 'only_matching': True,
321 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
322 'only_matching': True,
324 'url': 'https://www.twitch.tv/northernlion/video/291940395',
325 'only_matching': True,
327 'url': 'https://player.twitch.tv/?video=480452374',
328 'only_matching': True,
331 def _real_extract(self, url):
332 item_id = self._match_id(url)
334 info = self._download_info(self._ITEM_SHORTCUT, item_id)
335 access_token = self._call_api(
336 'api/vods/%s/access_token' % item_id, item_id,
337 'Downloading %s access token' % self._ITEM_TYPE)
339 formats = self._extract_m3u8_formats(
340 '%s/vod/%s.m3u8?%s' % (
341 self._USHER_BASE, item_id,
342 compat_urllib_parse_urlencode({
343 'allow_source': 'true',
344 'allow_audio_only': 'true',
345 'allow_spectre': 'true',
346 'player': 'twitchweb',
347 'playlist_include_framerate': 'true',
348 'nauth': access_token['token'],
349 'nauthsig': access_token['sig'],
351 item_id, 'mp4', entry_protocol='m3u8_native')
353 self._prefer_source(formats)
354 info['formats'] = formats
356 parsed_url = compat_urllib_parse_urlparse(url)
357 query = compat_parse_qs(parsed_url.query)
359 info['start_time'] = parse_duration(query['t'][0])
361 if info.get('timestamp') is not None:
362 info['subtitles'] = {
364 'url': update_url_query(
365 'https://api.twitch.tv/v5/videos/%s/comments' % item_id, {
366 'client_id': self._CLIENT_ID,
375 class TwitchPlaylistBaseIE(TwitchBaseIE):
376 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
379 def _extract_playlist(self, channel_id):
380 info = self._call_api(
381 'kraken/channels/%s' % channel_id,
382 channel_id, 'Downloading channel info JSON')
383 channel_name = info.get('display_name') or info.get('name')
386 limit = self._PAGE_LIMIT
387 broken_paging_detected = False
388 counter_override = None
389 for counter in itertools.count(1):
390 response = self._call_api(
391 self._PLAYLIST_PATH % (channel_id, offset, limit),
393 'Downloading %s JSON page %s'
394 % (self._PLAYLIST_TYPE, counter_override or counter))
395 page_entries = self._extract_playlist_page(response)
398 total = int_or_none(response.get('_total'))
399 # Since the beginning of March 2016 twitch's paging mechanism
400 # is completely broken on the twitch side. It simply ignores
401 # a limit and returns the whole offset number of videos.
402 # Working around by just requesting all videos at once.
403 # Upd: pagination bug was fixed by twitch on 15.03.2016.
404 if not broken_paging_detected and total and len(page_entries) > limit:
406 'Twitch pagination is broken on twitch side, requesting all videos at once',
408 broken_paging_detected = True
410 counter_override = '(all at once)'
412 entries.extend(page_entries)
413 if broken_paging_detected or total and len(page_entries) >= total:
416 return self.playlist_result(
417 [self._make_url_result(entry) for entry in orderedSet(entries)],
418 channel_id, channel_name)
420 def _make_url_result(self, url):
422 video_id = 'v%s' % TwitchVodIE._match_id(url)
423 return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
424 except AssertionError:
425 return self.url_result(url)
427 def _extract_playlist_page(self, response):
428 videos = response.get('videos')
429 return [video['url'] for video in videos] if videos else []
431 def _real_extract(self, url):
432 return self._extract_playlist(self._match_id(url))
435 class TwitchProfileIE(TwitchPlaylistBaseIE):
436 IE_NAME = 'twitch:profile'
437 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
438 _PLAYLIST_TYPE = 'profile'
441 'url': 'http://www.twitch.tv/vanillatv/profile',
444 'title': 'VanillaTV',
446 'playlist_mincount': 412,
448 'url': 'http://m.twitch.tv/vanillatv/profile',
449 'only_matching': True,
453 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
454 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
455 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
458 class TwitchAllVideosIE(TwitchVideosBaseIE):
459 IE_NAME = 'twitch:videos:all'
460 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
461 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
462 _PLAYLIST_TYPE = 'all videos'
465 'url': 'https://www.twitch.tv/spamfish/videos/all',
470 'playlist_mincount': 869,
472 'url': 'https://m.twitch.tv/spamfish/videos/all',
473 'only_matching': True,
477 class TwitchUploadsIE(TwitchVideosBaseIE):
478 IE_NAME = 'twitch:videos:uploads'
479 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
480 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
481 _PLAYLIST_TYPE = 'uploads'
484 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
489 'playlist_mincount': 0,
491 'url': 'https://m.twitch.tv/spamfish/videos/uploads',
492 'only_matching': True,
496 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
497 IE_NAME = 'twitch:videos:past-broadcasts'
498 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
499 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
500 _PLAYLIST_TYPE = 'past broadcasts'
503 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
508 'playlist_mincount': 0,
510 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
511 'only_matching': True,
515 class TwitchHighlightsIE(TwitchVideosBaseIE):
516 IE_NAME = 'twitch:videos:highlights'
517 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
518 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
519 _PLAYLIST_TYPE = 'highlights'
522 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
527 'playlist_mincount': 805,
529 'url': 'https://m.twitch.tv/spamfish/videos/highlights',
530 'only_matching': True,
534 class TwitchStreamIE(TwitchBaseIE):
535 IE_NAME = 'twitch:stream'
536 _VALID_URL = r'''(?x)
539 (?:(?:www|go|m)\.)?twitch\.tv/|
540 player\.twitch\.tv/\?.*?\bchannel=
546 'url': 'http://www.twitch.tv/shroomztv',
549 'display_id': 'shroomztv',
551 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
552 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
554 'timestamp': 1421928037,
555 'upload_date': '20150122',
556 'uploader': 'ShroomzTV',
557 'uploader_id': 'shroomztv',
562 'skip_download': True,
565 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
566 'only_matching': True,
568 'url': 'https://player.twitch.tv/?channel=lotsofs',
569 'only_matching': True,
571 'url': 'https://go.twitch.tv/food',
572 'only_matching': True,
574 'url': 'https://m.twitch.tv/food',
575 'only_matching': True,
579 def suitable(cls, url):
581 if any(ie.suitable(url) for ie in (
588 TwitchPastBroadcastsIE,
591 else super(TwitchStreamIE, cls).suitable(url))
593 def _real_extract(self, url):
594 channel_id = self._match_id(url)
596 stream = self._call_api(
597 'kraken/streams/%s?stream_type=all' % channel_id.lower(),
598 channel_id, 'Downloading stream JSON').get('stream')
601 raise ExtractorError('%s is offline' % channel_id, expected=True)
603 # Channel name may be typed if different case than the original channel name
604 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
605 # an invalid m3u8 URL. Working around by use of original channel name from stream
606 # JSON and fallback to lowercase if it's not available.
607 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
609 access_token = self._call_api(
610 'api/channels/%s/access_token' % channel_id, channel_id,
611 'Downloading channel access token')
614 'allow_source': 'true',
615 'allow_audio_only': 'true',
616 'allow_spectre': 'true',
617 'p': random.randint(1000000, 10000000),
618 'player': 'twitchweb',
619 'playlist_include_framerate': 'true',
620 'segment_preference': '4',
621 'sig': access_token['sig'].encode('utf-8'),
622 'token': access_token['token'].encode('utf-8'),
624 formats = self._extract_m3u8_formats(
625 '%s/api/channel/hls/%s.m3u8?%s'
626 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
628 self._prefer_source(formats)
630 view_count = stream.get('viewers')
631 timestamp = parse_iso8601(stream.get('created_at'))
633 channel = stream['channel']
634 title = self._live_title(channel.get('display_name') or channel.get('name'))
635 description = channel.get('status')
638 for thumbnail_key, thumbnail_url in stream['preview'].items():
639 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
643 'url': thumbnail_url,
644 'width': int(m.group('width')),
645 'height': int(m.group('height')),
649 'id': compat_str(stream['_id']),
650 'display_id': channel_id,
652 'description': description,
653 'thumbnails': thumbnails,
654 'uploader': channel.get('display_name'),
655 'uploader_id': channel.get('name'),
656 'timestamp': timestamp,
657 'view_count': view_count,
663 class TwitchClipsIE(TwitchBaseIE):
664 IE_NAME = 'twitch:clips'
665 _VALID_URL = r'''(?x)
668 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
669 (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/
675 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
676 'md5': '761769e1eafce0ffebfb4089cb3847cd',
680 'title': 'EA Play 2016 Live from the Novo Theatre',
681 'thumbnail': r're:^https?://.*\.jpg',
682 'timestamp': 1465767393,
683 'upload_date': '20160612',
685 'uploader': 'stereotype_',
686 'uploader_id': '43566419',
690 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
691 'only_matching': True,
693 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
694 'only_matching': True,
696 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
697 'only_matching': True,
699 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
700 'only_matching': True,
702 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
703 'only_matching': True,
706 def _real_extract(self, url):
707 video_id = self._match_id(url)
709 clip = self._download_json(
710 'https://gql.twitch.tv/gql', video_id, data=json.dumps({
723 tiny: thumbnailURL(width: 86, height: 45)
724 small: thumbnailURL(width: 260, height: 147)
725 medium: thumbnailURL(width: 480, height: 272)
735 }).encode(), headers={
736 'Client-ID': self._CLIENT_ID,
740 raise ExtractorError(
741 'This clip is no longer available', expected=True)
744 for option in clip.get('videoQualities', []):
745 if not isinstance(option, dict):
747 source = url_or_none(option.get('sourceURL'))
752 'format_id': option.get('quality'),
753 'height': int_or_none(option.get('quality')),
754 'fps': int_or_none(option.get('frameRate')),
756 self._sort_formats(formats)
759 for thumbnail_id in ('tiny', 'small', 'medium'):
760 thumbnail_url = clip.get(thumbnail_id)
761 if not thumbnail_url:
765 'url': thumbnail_url,
767 mobj = re.search(r'-(\d+)x(\d+)\.', thumbnail_url)
770 'height': int(mobj.group(2)),
771 'width': int(mobj.group(1)),
773 thumbnails.append(thumb)
776 'id': clip.get('id') or video_id,
777 'title': clip.get('title') or video_id,
779 'duration': int_or_none(clip.get('durationSeconds')),
780 'views': int_or_none(clip.get('viewCount')),
781 'timestamp': unified_timestamp(clip.get('createdAt')),
782 'thumbnails': thumbnails,
783 'creator': try_get(clip, lambda x: x['broadcaster']['displayName'], compat_str),
784 'uploader': try_get(clip, lambda x: x['curator']['displayName'], compat_str),
785 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),