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 kwargs.setdefault('headers', {})['Client-ID'] = self._CLIENT_ID
55 response = self._download_json(
56 '%s/%s' % (self._API_BASE, path), item_id,
57 *args, **compat_kwargs(kwargs))
58 self._handle_error(response)
61 def _real_initialize(self):
65 username, password = self._get_login_info()
71 'Unable to login. Twitch said: %s' % message, expected=True)
73 def login_step(page, urlh, note, data):
74 form = self._hidden_inputs(page)
77 page_url = urlh.geturl()
78 post_url = self._search_regex(
79 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
80 'post url', default=self._LOGIN_POST_URL, group='url')
81 post_url = urljoin(page_url, post_url)
86 'Content-Type': 'text/plain;charset=UTF-8',
89 response = self._download_json(
90 post_url, None, note, data=json.dumps(form).encode(),
91 headers=headers, expected_status=400)
92 error = response.get('error_description') or response.get('error_code')
96 if 'Authenticated successfully' in response.get('message', ''):
99 redirect_url = urljoin(
101 response.get('redirect') or response['redirect_path'])
102 return self._download_webpage_handle(
103 redirect_url, None, 'Downloading login redirect page',
106 login_page, handle = self._download_webpage_handle(
107 self._LOGIN_FORM_URL, None, 'Downloading login page')
109 # Some TOR nodes and public proxies are blocked completely
110 if 'blacklist_message' in login_page:
111 fail(clean_html(login_page))
113 redirect_page, handle = login_step(
114 login_page, handle, 'Logging in', {
115 'username': username,
116 'password': password,
117 'client_id': self._CLIENT_ID,
121 if not redirect_page:
124 if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
125 # TODO: Add mechanism to request an SMS or phone call
126 tfa_token = self._get_tfa_info('two-factor authentication token')
127 login_step(redirect_page, handle, 'Submitting TFA token', {
128 'authy_token': tfa_token,
129 'remember_2fa': 'true',
132 def _prefer_source(self, formats):
134 source = next(f for f in formats if f['format_id'] == 'Source')
135 source['preference'] = 10
136 except StopIteration:
137 pass # No Source stream present
138 self._sort_formats(formats)
141 class TwitchItemBaseIE(TwitchBaseIE):
142 def _download_info(self, item, item_id):
143 return self._extract_info(self._call_api(
144 'kraken/videos/%s%s' % (item, item_id), item_id,
145 'Downloading %s info JSON' % self._ITEM_TYPE))
147 def _extract_media(self, item_id):
148 info = self._download_info(self._ITEM_SHORTCUT, item_id)
149 response = self._call_api(
150 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
151 'Downloading %s playlist JSON' % self._ITEM_TYPE)
153 chunks = response['chunks']
154 qualities = list(chunks.keys())
155 for num, fragment in enumerate(zip(*chunks.values()), start=1):
157 for fmt_num, fragment_fmt in enumerate(fragment):
158 format_id = qualities[fmt_num]
160 'url': fragment_fmt['url'],
161 'format_id': format_id,
162 'quality': 1 if format_id == 'live' else 0,
164 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
166 fmt['height'] = int(m.group('height'))
168 self._sort_formats(formats)
170 entry['id'] = '%s_%d' % (entry['id'], num)
171 entry['title'] = '%s part %d' % (entry['title'], num)
172 entry['formats'] = formats
173 entries.append(entry)
174 return self.playlist_result(entries, info['id'], info['title'])
176 def _extract_info(self, info):
177 status = info.get('status')
178 if status == 'recording':
180 elif status == 'recorded':
186 'title': info.get('title') or 'Untitled Broadcast',
187 'description': info.get('description'),
188 'duration': int_or_none(info.get('length')),
189 'thumbnail': info.get('preview'),
190 'uploader': info.get('channel', {}).get('display_name'),
191 'uploader_id': info.get('channel', {}).get('name'),
192 'timestamp': parse_iso8601(info.get('recorded_at')),
193 'view_count': int_or_none(info.get('views')),
197 def _real_extract(self, url):
198 return self._extract_media(self._match_id(url))
201 class TwitchVideoIE(TwitchItemBaseIE):
202 IE_NAME = 'twitch:video'
203 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
208 'url': 'http://www.twitch.tv/riotgames/b/577357806',
211 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
213 'playlist_mincount': 12,
214 'skip': 'HTTP Error 404: Not Found',
218 class TwitchChapterIE(TwitchItemBaseIE):
219 IE_NAME = 'twitch:chapter'
220 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
221 _ITEM_TYPE = 'chapter'
225 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
228 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
230 'playlist_mincount': 3,
231 'skip': 'HTTP Error 404: Not Found',
233 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
234 'only_matching': True,
238 class TwitchVodIE(TwitchItemBaseIE):
239 IE_NAME = 'twitch:vod'
240 _VALID_URL = r'''(?x)
243 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
244 player\.twitch\.tv/\?.*?\bvideo=v
252 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
256 'title': 'LCK Summer Split - Week 6 Day 1',
257 'thumbnail': r're:^https?://.*\.jpg$',
259 'timestamp': 1435131709,
260 'upload_date': '20150624',
261 'uploader': 'Riot Games',
262 'uploader_id': 'riotgames',
268 'skip_download': True,
271 # Untitled broadcast (title is None)
272 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
276 'title': 'Untitled Broadcast',
277 'thumbnail': r're:^https?://.*\.jpg$',
279 'timestamp': 1439746708,
280 'upload_date': '20150816',
281 'uploader': 'BelkAO_o',
282 'uploader_id': 'belkao_o',
287 'skip_download': True,
289 'skip': 'HTTP Error 404: Not Found',
291 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
292 'only_matching': True,
294 'url': 'https://www.twitch.tv/videos/6528877',
295 'only_matching': True,
297 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
298 'only_matching': True,
300 'url': 'https://www.twitch.tv/northernlion/video/291940395',
301 'only_matching': True,
304 def _real_extract(self, url):
305 item_id = self._match_id(url)
307 info = self._download_info(self._ITEM_SHORTCUT, item_id)
308 access_token = self._call_api(
309 'api/vods/%s/access_token' % item_id, item_id,
310 'Downloading %s access token' % self._ITEM_TYPE)
312 formats = self._extract_m3u8_formats(
314 self._USHER_BASE, item_id,
315 compat_urllib_parse_urlencode({
316 'allow_source': 'true',
317 'allow_audio_only': 'true',
318 'allow_spectre': 'true',
319 'player': 'twitchweb',
320 'nauth': access_token['token'],
321 'nauthsig': access_token['sig'],
323 item_id, 'mp4', entry_protocol='m3u8_native')
325 self._prefer_source(formats)
326 info['formats'] = formats
328 parsed_url = compat_urllib_parse_urlparse(url)
329 query = compat_parse_qs(parsed_url.query)
331 info['start_time'] = parse_duration(query['t'][0])
333 if info.get('timestamp') is not None:
334 info['subtitles'] = {
336 'url': update_url_query(
337 'https://rechat.twitch.tv/rechat-messages', {
338 'video_id': 'v%s' % item_id,
339 'start': info['timestamp'],
348 class TwitchPlaylistBaseIE(TwitchBaseIE):
349 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
352 def _extract_playlist(self, channel_id):
353 info = self._call_api(
354 'kraken/channels/%s' % channel_id,
355 channel_id, 'Downloading channel info JSON')
356 channel_name = info.get('display_name') or info.get('name')
359 limit = self._PAGE_LIMIT
360 broken_paging_detected = False
361 counter_override = None
362 for counter in itertools.count(1):
363 response = self._call_api(
364 self._PLAYLIST_PATH % (channel_id, offset, limit),
366 'Downloading %s JSON page %s'
367 % (self._PLAYLIST_TYPE, counter_override or counter))
368 page_entries = self._extract_playlist_page(response)
371 total = int_or_none(response.get('_total'))
372 # Since the beginning of March 2016 twitch's paging mechanism
373 # is completely broken on the twitch side. It simply ignores
374 # a limit and returns the whole offset number of videos.
375 # Working around by just requesting all videos at once.
376 # Upd: pagination bug was fixed by twitch on 15.03.2016.
377 if not broken_paging_detected and total and len(page_entries) > limit:
379 'Twitch pagination is broken on twitch side, requesting all videos at once',
381 broken_paging_detected = True
383 counter_override = '(all at once)'
385 entries.extend(page_entries)
386 if broken_paging_detected or total and len(page_entries) >= total:
389 return self.playlist_result(
390 [self._make_url_result(entry) for entry in orderedSet(entries)],
391 channel_id, channel_name)
393 def _make_url_result(self, url):
395 video_id = 'v%s' % TwitchVodIE._match_id(url)
396 return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
397 except AssertionError:
398 return self.url_result(url)
400 def _extract_playlist_page(self, response):
401 videos = response.get('videos')
402 return [video['url'] for video in videos] if videos else []
404 def _real_extract(self, url):
405 return self._extract_playlist(self._match_id(url))
408 class TwitchProfileIE(TwitchPlaylistBaseIE):
409 IE_NAME = 'twitch:profile'
410 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
411 _PLAYLIST_TYPE = 'profile'
414 'url': 'http://www.twitch.tv/vanillatv/profile',
417 'title': 'VanillaTV',
419 'playlist_mincount': 412,
421 'url': 'http://m.twitch.tv/vanillatv/profile',
422 'only_matching': True,
426 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
427 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
428 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
431 class TwitchAllVideosIE(TwitchVideosBaseIE):
432 IE_NAME = 'twitch:videos:all'
433 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
434 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
435 _PLAYLIST_TYPE = 'all videos'
438 'url': 'https://www.twitch.tv/spamfish/videos/all',
443 'playlist_mincount': 869,
445 'url': 'https://m.twitch.tv/spamfish/videos/all',
446 'only_matching': True,
450 class TwitchUploadsIE(TwitchVideosBaseIE):
451 IE_NAME = 'twitch:videos:uploads'
452 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
453 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
454 _PLAYLIST_TYPE = 'uploads'
457 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
462 'playlist_mincount': 0,
464 'url': 'https://m.twitch.tv/spamfish/videos/uploads',
465 'only_matching': True,
469 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
470 IE_NAME = 'twitch:videos:past-broadcasts'
471 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
472 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
473 _PLAYLIST_TYPE = 'past broadcasts'
476 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
481 'playlist_mincount': 0,
483 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
484 'only_matching': True,
488 class TwitchHighlightsIE(TwitchVideosBaseIE):
489 IE_NAME = 'twitch:videos:highlights'
490 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
491 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
492 _PLAYLIST_TYPE = 'highlights'
495 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
500 'playlist_mincount': 805,
502 'url': 'https://m.twitch.tv/spamfish/videos/highlights',
503 'only_matching': True,
507 class TwitchStreamIE(TwitchBaseIE):
508 IE_NAME = 'twitch:stream'
509 _VALID_URL = r'''(?x)
512 (?:(?:www|go|m)\.)?twitch\.tv/|
513 player\.twitch\.tv/\?.*?\bchannel=
519 'url': 'http://www.twitch.tv/shroomztv',
522 'display_id': 'shroomztv',
524 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
525 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
527 'timestamp': 1421928037,
528 'upload_date': '20150122',
529 'uploader': 'ShroomzTV',
530 'uploader_id': 'shroomztv',
535 'skip_download': True,
538 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
539 'only_matching': True,
541 'url': 'https://player.twitch.tv/?channel=lotsofs',
542 'only_matching': True,
544 'url': 'https://go.twitch.tv/food',
545 'only_matching': True,
547 'url': 'https://m.twitch.tv/food',
548 'only_matching': True,
552 def suitable(cls, url):
554 if any(ie.suitable(url) for ie in (
561 TwitchPastBroadcastsIE,
563 else super(TwitchStreamIE, cls).suitable(url))
565 def _real_extract(self, url):
566 channel_id = self._match_id(url)
568 stream = self._call_api(
569 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
570 'Downloading stream JSON').get('stream')
573 raise ExtractorError('%s is offline' % channel_id, expected=True)
575 # Channel name may be typed if different case than the original channel name
576 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
577 # an invalid m3u8 URL. Working around by use of original channel name from stream
578 # JSON and fallback to lowercase if it's not available.
579 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
581 access_token = self._call_api(
582 'api/channels/%s/access_token' % channel_id, channel_id,
583 'Downloading channel access token')
586 'allow_source': 'true',
587 'allow_audio_only': 'true',
588 'allow_spectre': 'true',
589 'p': random.randint(1000000, 10000000),
590 'player': 'twitchweb',
591 'segment_preference': '4',
592 'sig': access_token['sig'].encode('utf-8'),
593 'token': access_token['token'].encode('utf-8'),
595 formats = self._extract_m3u8_formats(
596 '%s/api/channel/hls/%s.m3u8?%s'
597 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
599 self._prefer_source(formats)
601 view_count = stream.get('viewers')
602 timestamp = parse_iso8601(stream.get('created_at'))
604 channel = stream['channel']
605 title = self._live_title(channel.get('display_name') or channel.get('name'))
606 description = channel.get('status')
609 for thumbnail_key, thumbnail_url in stream['preview'].items():
610 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
614 'url': thumbnail_url,
615 'width': int(m.group('width')),
616 'height': int(m.group('height')),
620 'id': compat_str(stream['_id']),
621 'display_id': channel_id,
623 'description': description,
624 'thumbnails': thumbnails,
625 'uploader': channel.get('display_name'),
626 'uploader_id': channel.get('name'),
627 'timestamp': timestamp,
628 'view_count': view_count,
634 class TwitchClipsIE(TwitchBaseIE):
635 IE_NAME = 'twitch:clips'
636 _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
639 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
640 'md5': '761769e1eafce0ffebfb4089cb3847cd',
644 'title': 'EA Play 2016 Live from the Novo Theatre',
645 'thumbnail': r're:^https?://.*\.jpg',
646 'timestamp': 1465767393,
647 'upload_date': '20160612',
649 'uploader': 'stereotype_',
650 'uploader_id': '43566419',
654 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
655 'only_matching': True,
658 def _real_extract(self, url):
659 video_id = self._match_id(url)
661 status = self._download_json(
662 'https://clips.twitch.tv/api/v2/clips/%s/status' % video_id,
667 for option in status['quality_options']:
668 if not isinstance(option, dict):
670 source = url_or_none(option.get('source'))
675 'format_id': option.get('quality'),
676 'height': int_or_none(option.get('quality')),
677 'fps': int_or_none(option.get('frame_rate')),
680 self._sort_formats(formats)
686 clip = self._call_api(
687 'kraken/clips/%s' % video_id, video_id, fatal=False, headers={
688 'Accept': 'application/vnd.twitchtv.v5+json',
692 quality_key = qualities(('tiny', 'small', 'medium'))
694 thumbnails_dict = clip.get('thumbnails')
695 if isinstance(thumbnails_dict, dict):
696 for thumbnail_id, thumbnail_url in thumbnails_dict.items():
699 'url': thumbnail_url,
700 'preference': quality_key(thumbnail_id),
704 'id': clip.get('tracking_id') or video_id,
705 'title': clip.get('title') or video_id,
706 'duration': float_or_none(clip.get('duration')),
707 'views': int_or_none(clip.get('views')),
708 'timestamp': unified_timestamp(clip.get('created_at')),
709 'thumbnails': thumbnails,
710 'creator': try_get(clip, lambda x: x['broadcaster']['display_name'], compat_str),
711 'uploader': try_get(clip, lambda x: x['curator']['display_name'], compat_str),
712 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),