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()
55 headers['Client-ID'] = self._CLIENT_ID
56 kwargs['headers'] = headers
57 response = self._download_json(
58 '%s/%s' % (self._API_BASE, path), item_id,
59 *args, **compat_kwargs(kwargs))
60 self._handle_error(response)
63 def _real_initialize(self):
67 username, password = self._get_login_info()
73 'Unable to login. Twitch said: %s' % message, expected=True)
75 def login_step(page, urlh, note, data):
76 form = self._hidden_inputs(page)
79 page_url = urlh.geturl()
80 post_url = self._search_regex(
81 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
82 'post url', default=self._LOGIN_POST_URL, group='url')
83 post_url = urljoin(page_url, post_url)
88 'Content-Type': 'text/plain;charset=UTF-8',
91 response = self._download_json(
92 post_url, None, note, data=json.dumps(form).encode(),
93 headers=headers, expected_status=400)
94 error = response.get('error_description') or response.get('error_code')
98 if 'Authenticated successfully' in response.get('message', ''):
101 redirect_url = urljoin(
103 response.get('redirect') or response['redirect_path'])
104 return self._download_webpage_handle(
105 redirect_url, None, 'Downloading login redirect page',
108 login_page, handle = self._download_webpage_handle(
109 self._LOGIN_FORM_URL, None, 'Downloading login page')
111 # Some TOR nodes and public proxies are blocked completely
112 if 'blacklist_message' in login_page:
113 fail(clean_html(login_page))
115 redirect_page, handle = login_step(
116 login_page, handle, 'Logging in', {
117 'username': username,
118 'password': password,
119 'client_id': self._CLIENT_ID,
123 if not redirect_page:
126 if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
127 # TODO: Add mechanism to request an SMS or phone call
128 tfa_token = self._get_tfa_info('two-factor authentication token')
129 login_step(redirect_page, handle, 'Submitting TFA token', {
130 'authy_token': tfa_token,
131 'remember_2fa': 'true',
134 def _prefer_source(self, formats):
136 source = next(f for f in formats if f['format_id'] == 'Source')
137 source['quality'] = 10
138 except StopIteration:
140 if '/chunked/' in f['url']:
143 'format_note': 'Source',
145 self._sort_formats(formats)
148 class TwitchItemBaseIE(TwitchBaseIE):
149 def _download_info(self, item, item_id):
150 return self._extract_info(self._call_api(
151 'kraken/videos/%s%s' % (item, item_id), item_id,
152 'Downloading %s info JSON' % self._ITEM_TYPE))
154 def _extract_media(self, item_id):
155 info = self._download_info(self._ITEM_SHORTCUT, item_id)
156 response = self._call_api(
157 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
158 'Downloading %s playlist JSON' % self._ITEM_TYPE)
160 chunks = response['chunks']
161 qualities = list(chunks.keys())
162 for num, fragment in enumerate(zip(*chunks.values()), start=1):
164 for fmt_num, fragment_fmt in enumerate(fragment):
165 format_id = qualities[fmt_num]
167 'url': fragment_fmt['url'],
168 'format_id': format_id,
169 'quality': 1 if format_id == 'live' else 0,
171 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
173 fmt['height'] = int(m.group('height'))
175 self._sort_formats(formats)
177 entry['id'] = '%s_%d' % (entry['id'], num)
178 entry['title'] = '%s part %d' % (entry['title'], num)
179 entry['formats'] = formats
180 entries.append(entry)
181 return self.playlist_result(entries, info['id'], info['title'])
183 def _extract_info(self, info):
184 status = info.get('status')
185 if status == 'recording':
187 elif status == 'recorded':
193 'title': info.get('title') or 'Untitled Broadcast',
194 'description': info.get('description'),
195 'duration': int_or_none(info.get('length')),
196 'thumbnail': info.get('preview'),
197 'uploader': info.get('channel', {}).get('display_name'),
198 'uploader_id': info.get('channel', {}).get('name'),
199 'timestamp': parse_iso8601(info.get('recorded_at')),
200 'view_count': int_or_none(info.get('views')),
204 def _real_extract(self, url):
205 return self._extract_media(self._match_id(url))
208 class TwitchVideoIE(TwitchItemBaseIE):
209 IE_NAME = 'twitch:video'
210 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
215 'url': 'http://www.twitch.tv/riotgames/b/577357806',
218 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
220 'playlist_mincount': 12,
221 'skip': 'HTTP Error 404: Not Found',
225 class TwitchChapterIE(TwitchItemBaseIE):
226 IE_NAME = 'twitch:chapter'
227 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
228 _ITEM_TYPE = 'chapter'
232 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
235 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
237 'playlist_mincount': 3,
238 'skip': 'HTTP Error 404: Not Found',
240 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
241 'only_matching': True,
245 class TwitchVodIE(TwitchItemBaseIE):
246 IE_NAME = 'twitch:vod'
247 _VALID_URL = r'''(?x)
250 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
251 player\.twitch\.tv/\?.*?\bvideo=v?
259 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
263 'title': 'LCK Summer Split - Week 6 Day 1',
264 'thumbnail': r're:^https?://.*\.jpg$',
266 'timestamp': 1435131709,
267 'upload_date': '20150624',
268 'uploader': 'Riot Games',
269 'uploader_id': 'riotgames',
275 'skip_download': True,
278 # Untitled broadcast (title is None)
279 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
283 'title': 'Untitled Broadcast',
284 'thumbnail': r're:^https?://.*\.jpg$',
286 'timestamp': 1439746708,
287 'upload_date': '20150816',
288 'uploader': 'BelkAO_o',
289 'uploader_id': 'belkao_o',
294 'skip_download': True,
296 'skip': 'HTTP Error 404: Not Found',
298 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
299 'only_matching': True,
301 'url': 'https://www.twitch.tv/videos/6528877',
302 'only_matching': True,
304 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
305 'only_matching': True,
307 'url': 'https://www.twitch.tv/northernlion/video/291940395',
308 'only_matching': True,
310 'url': 'https://player.twitch.tv/?video=480452374',
311 'only_matching': True,
314 def _real_extract(self, url):
315 item_id = self._match_id(url)
317 info = self._download_info(self._ITEM_SHORTCUT, item_id)
318 access_token = self._call_api(
319 'api/vods/%s/access_token' % item_id, item_id,
320 'Downloading %s access token' % self._ITEM_TYPE)
322 formats = self._extract_m3u8_formats(
323 '%s/vod/%s.m3u8?%s' % (
324 self._USHER_BASE, item_id,
325 compat_urllib_parse_urlencode({
326 'allow_source': 'true',
327 'allow_audio_only': 'true',
328 'allow_spectre': 'true',
329 'player': 'twitchweb',
330 'nauth': access_token['token'],
331 'nauthsig': access_token['sig'],
333 item_id, 'mp4', entry_protocol='m3u8_native')
335 self._prefer_source(formats)
336 info['formats'] = formats
338 parsed_url = compat_urllib_parse_urlparse(url)
339 query = compat_parse_qs(parsed_url.query)
341 info['start_time'] = parse_duration(query['t'][0])
343 if info.get('timestamp') is not None:
344 info['subtitles'] = {
346 'url': update_url_query(
347 'https://api.twitch.tv/v5/videos/%s/comments' % item_id, {
348 'client_id': self._CLIENT_ID,
357 class TwitchPlaylistBaseIE(TwitchBaseIE):
358 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
361 def _extract_playlist(self, channel_id):
362 info = self._call_api(
363 'kraken/channels/%s' % channel_id,
364 channel_id, 'Downloading channel info JSON')
365 channel_name = info.get('display_name') or info.get('name')
368 limit = self._PAGE_LIMIT
369 broken_paging_detected = False
370 counter_override = None
371 for counter in itertools.count(1):
372 response = self._call_api(
373 self._PLAYLIST_PATH % (channel_id, offset, limit),
375 'Downloading %s JSON page %s'
376 % (self._PLAYLIST_TYPE, counter_override or counter))
377 page_entries = self._extract_playlist_page(response)
380 total = int_or_none(response.get('_total'))
381 # Since the beginning of March 2016 twitch's paging mechanism
382 # is completely broken on the twitch side. It simply ignores
383 # a limit and returns the whole offset number of videos.
384 # Working around by just requesting all videos at once.
385 # Upd: pagination bug was fixed by twitch on 15.03.2016.
386 if not broken_paging_detected and total and len(page_entries) > limit:
388 'Twitch pagination is broken on twitch side, requesting all videos at once',
390 broken_paging_detected = True
392 counter_override = '(all at once)'
394 entries.extend(page_entries)
395 if broken_paging_detected or total and len(page_entries) >= total:
398 return self.playlist_result(
399 [self._make_url_result(entry) for entry in orderedSet(entries)],
400 channel_id, channel_name)
402 def _make_url_result(self, url):
404 video_id = 'v%s' % TwitchVodIE._match_id(url)
405 return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
406 except AssertionError:
407 return self.url_result(url)
409 def _extract_playlist_page(self, response):
410 videos = response.get('videos')
411 return [video['url'] for video in videos] if videos else []
413 def _real_extract(self, url):
414 return self._extract_playlist(self._match_id(url))
417 class TwitchProfileIE(TwitchPlaylistBaseIE):
418 IE_NAME = 'twitch:profile'
419 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
420 _PLAYLIST_TYPE = 'profile'
423 'url': 'http://www.twitch.tv/vanillatv/profile',
426 'title': 'VanillaTV',
428 'playlist_mincount': 412,
430 'url': 'http://m.twitch.tv/vanillatv/profile',
431 'only_matching': True,
435 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
436 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
437 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
440 class TwitchAllVideosIE(TwitchVideosBaseIE):
441 IE_NAME = 'twitch:videos:all'
442 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
443 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
444 _PLAYLIST_TYPE = 'all videos'
447 'url': 'https://www.twitch.tv/spamfish/videos/all',
452 'playlist_mincount': 869,
454 'url': 'https://m.twitch.tv/spamfish/videos/all',
455 'only_matching': True,
459 class TwitchUploadsIE(TwitchVideosBaseIE):
460 IE_NAME = 'twitch:videos:uploads'
461 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
462 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
463 _PLAYLIST_TYPE = 'uploads'
466 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
471 'playlist_mincount': 0,
473 'url': 'https://m.twitch.tv/spamfish/videos/uploads',
474 'only_matching': True,
478 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
479 IE_NAME = 'twitch:videos:past-broadcasts'
480 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
481 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
482 _PLAYLIST_TYPE = 'past broadcasts'
485 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
490 'playlist_mincount': 0,
492 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
493 'only_matching': True,
497 class TwitchHighlightsIE(TwitchVideosBaseIE):
498 IE_NAME = 'twitch:videos:highlights'
499 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
500 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
501 _PLAYLIST_TYPE = 'highlights'
504 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
509 'playlist_mincount': 805,
511 'url': 'https://m.twitch.tv/spamfish/videos/highlights',
512 'only_matching': True,
516 class TwitchStreamIE(TwitchBaseIE):
517 IE_NAME = 'twitch:stream'
518 _VALID_URL = r'''(?x)
521 (?:(?:www|go|m)\.)?twitch\.tv/|
522 player\.twitch\.tv/\?.*?\bchannel=
528 'url': 'http://www.twitch.tv/shroomztv',
531 'display_id': 'shroomztv',
533 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
534 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
536 'timestamp': 1421928037,
537 'upload_date': '20150122',
538 'uploader': 'ShroomzTV',
539 'uploader_id': 'shroomztv',
544 'skip_download': True,
547 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
548 'only_matching': True,
550 'url': 'https://player.twitch.tv/?channel=lotsofs',
551 'only_matching': True,
553 'url': 'https://go.twitch.tv/food',
554 'only_matching': True,
556 'url': 'https://m.twitch.tv/food',
557 'only_matching': True,
561 def suitable(cls, url):
563 if any(ie.suitable(url) for ie in (
570 TwitchPastBroadcastsIE,
573 else super(TwitchStreamIE, cls).suitable(url))
575 def _real_extract(self, url):
576 channel_id = self._match_id(url)
578 stream = self._call_api(
579 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
580 'Downloading stream JSON').get('stream')
583 raise ExtractorError('%s is offline' % channel_id, expected=True)
585 # Channel name may be typed if different case than the original channel name
586 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
587 # an invalid m3u8 URL. Working around by use of original channel name from stream
588 # JSON and fallback to lowercase if it's not available.
589 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
591 access_token = self._call_api(
592 'api/channels/%s/access_token' % channel_id, channel_id,
593 'Downloading channel access token')
596 'allow_source': 'true',
597 'allow_audio_only': 'true',
598 'allow_spectre': 'true',
599 'p': random.randint(1000000, 10000000),
600 'player': 'twitchweb',
601 'segment_preference': '4',
602 'sig': access_token['sig'].encode('utf-8'),
603 'token': access_token['token'].encode('utf-8'),
605 formats = self._extract_m3u8_formats(
606 '%s/api/channel/hls/%s.m3u8?%s'
607 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
609 self._prefer_source(formats)
611 view_count = stream.get('viewers')
612 timestamp = parse_iso8601(stream.get('created_at'))
614 channel = stream['channel']
615 title = self._live_title(channel.get('display_name') or channel.get('name'))
616 description = channel.get('status')
619 for thumbnail_key, thumbnail_url in stream['preview'].items():
620 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
624 'url': thumbnail_url,
625 'width': int(m.group('width')),
626 'height': int(m.group('height')),
630 'id': compat_str(stream['_id']),
631 'display_id': channel_id,
633 'description': description,
634 'thumbnails': thumbnails,
635 'uploader': channel.get('display_name'),
636 'uploader_id': channel.get('name'),
637 'timestamp': timestamp,
638 'view_count': view_count,
644 class TwitchClipsIE(TwitchBaseIE):
645 IE_NAME = 'twitch:clips'
646 _VALID_URL = r'https?://(?:clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|(?:www\.)?twitch\.tv/[^/]+/clip/)(?P<id>[^/?#&]+)'
649 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
650 'md5': '761769e1eafce0ffebfb4089cb3847cd',
654 'title': 'EA Play 2016 Live from the Novo Theatre',
655 'thumbnail': r're:^https?://.*\.jpg',
656 'timestamp': 1465767393,
657 'upload_date': '20160612',
659 'uploader': 'stereotype_',
660 'uploader_id': '43566419',
664 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
665 'only_matching': True,
667 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
668 'only_matching': True,
670 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
671 'only_matching': True,
674 def _real_extract(self, url):
675 video_id = self._match_id(url)
677 status = self._download_json(
678 'https://clips.twitch.tv/api/v2/clips/%s/status' % video_id,
683 for option in status['quality_options']:
684 if not isinstance(option, dict):
686 source = url_or_none(option.get('source'))
691 'format_id': option.get('quality'),
692 'height': int_or_none(option.get('quality')),
693 'fps': int_or_none(option.get('frame_rate')),
696 self._sort_formats(formats)
702 clip = self._call_api(
703 'kraken/clips/%s' % video_id, video_id, fatal=False, headers={
704 'Accept': 'application/vnd.twitchtv.v5+json',
708 quality_key = qualities(('tiny', 'small', 'medium'))
710 thumbnails_dict = clip.get('thumbnails')
711 if isinstance(thumbnails_dict, dict):
712 for thumbnail_id, thumbnail_url in thumbnails_dict.items():
715 'url': thumbnail_url,
716 'preference': quality_key(thumbnail_id),
720 'id': clip.get('tracking_id') or video_id,
721 'title': clip.get('title') or video_id,
722 'duration': float_or_none(clip.get('duration')),
723 'views': int_or_none(clip.get('views')),
724 'timestamp': unified_timestamp(clip.get('created_at')),
725 'thumbnails': thumbnails,
726 'creator': try_get(clip, lambda x: x['broadcaster']['display_name'], compat_str),
727 'uploader': try_get(clip, lambda x: x['curator']['display_name'], compat_str),
728 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),