2 from __future__ import unicode_literals
8 from .common import InfoExtractor
14 compat_urllib_parse_urlencode,
15 compat_urllib_parse_urlparse,
35 class TwitchBaseIE(InfoExtractor):
36 _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv'
38 _API_BASE = 'https://api.twitch.tv'
39 _USHER_BASE = 'https://usher.ttvnw.net'
40 _LOGIN_URL = 'https://www.twitch.tv/login'
41 _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6'
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=page_url, group='url')
81 post_url = urljoin(page_url, post_url)
83 headers = {'Referer': page_url}
86 response = self._download_json(
88 data=urlencode_postdata(form),
90 except ExtractorError as e:
91 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
92 response = self._parse_json(
93 e.cause.read().decode('utf-8'), None)
94 fail(response.get('message') or response['errors'][0])
97 if 'Authenticated successfully' in response.get('message', ''):
100 redirect_url = urljoin(
102 response.get('redirect') or response['redirect_path'])
103 return self._download_webpage_handle(
104 redirect_url, None, 'Downloading login redirect page',
107 login_page, handle = self._download_webpage_handle(
108 self._LOGIN_URL, None, 'Downloading login page')
110 # Some TOR nodes and public proxies are blocked completely
111 if 'blacklist_message' in login_page:
112 fail(clean_html(login_page))
114 redirect_page, handle = login_step(
115 login_page, handle, 'Logging in', {
116 'username': username,
117 'password': password,
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|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,
301 def _real_extract(self, url):
302 item_id = self._match_id(url)
304 info = self._download_info(self._ITEM_SHORTCUT, item_id)
305 access_token = self._call_api(
306 'api/vods/%s/access_token' % item_id, item_id,
307 'Downloading %s access token' % self._ITEM_TYPE)
309 formats = self._extract_m3u8_formats(
311 self._USHER_BASE, item_id,
312 compat_urllib_parse_urlencode({
313 'allow_source': 'true',
314 'allow_audio_only': 'true',
315 'allow_spectre': 'true',
316 'player': 'twitchweb',
317 'nauth': access_token['token'],
318 'nauthsig': access_token['sig'],
320 item_id, 'mp4', entry_protocol='m3u8_native')
322 self._prefer_source(formats)
323 info['formats'] = formats
325 parsed_url = compat_urllib_parse_urlparse(url)
326 query = compat_parse_qs(parsed_url.query)
328 info['start_time'] = parse_duration(query['t'][0])
330 if info.get('timestamp') is not None:
331 info['subtitles'] = {
333 'url': update_url_query(
334 'https://rechat.twitch.tv/rechat-messages', {
335 'video_id': 'v%s' % item_id,
336 'start': info['timestamp'],
345 class TwitchPlaylistBaseIE(TwitchBaseIE):
346 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
349 def _extract_playlist(self, channel_id):
350 info = self._call_api(
351 'kraken/channels/%s' % channel_id,
352 channel_id, 'Downloading channel info JSON')
353 channel_name = info.get('display_name') or info.get('name')
356 limit = self._PAGE_LIMIT
357 broken_paging_detected = False
358 counter_override = None
359 for counter in itertools.count(1):
360 response = self._call_api(
361 self._PLAYLIST_PATH % (channel_id, offset, limit),
363 'Downloading %s JSON page %s'
364 % (self._PLAYLIST_TYPE, counter_override or counter))
365 page_entries = self._extract_playlist_page(response)
368 total = int_or_none(response.get('_total'))
369 # Since the beginning of March 2016 twitch's paging mechanism
370 # is completely broken on the twitch side. It simply ignores
371 # a limit and returns the whole offset number of videos.
372 # Working around by just requesting all videos at once.
373 # Upd: pagination bug was fixed by twitch on 15.03.2016.
374 if not broken_paging_detected and total and len(page_entries) > limit:
376 'Twitch pagination is broken on twitch side, requesting all videos at once',
378 broken_paging_detected = True
380 counter_override = '(all at once)'
382 entries.extend(page_entries)
383 if broken_paging_detected or total and len(page_entries) >= total:
386 return self.playlist_result(
387 [self._make_url_result(entry) for entry in orderedSet(entries)],
388 channel_id, channel_name)
390 def _make_url_result(self, url):
392 video_id = 'v%s' % TwitchVodIE._match_id(url)
393 return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
394 except AssertionError:
395 return self.url_result(url)
397 def _extract_playlist_page(self, response):
398 videos = response.get('videos')
399 return [video['url'] for video in videos] if videos else []
401 def _real_extract(self, url):
402 return self._extract_playlist(self._match_id(url))
405 class TwitchProfileIE(TwitchPlaylistBaseIE):
406 IE_NAME = 'twitch:profile'
407 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
408 _PLAYLIST_TYPE = 'profile'
411 'url': 'http://www.twitch.tv/vanillatv/profile',
414 'title': 'VanillaTV',
416 'playlist_mincount': 412,
418 'url': 'http://m.twitch.tv/vanillatv/profile',
419 'only_matching': True,
423 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
424 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
425 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
428 class TwitchAllVideosIE(TwitchVideosBaseIE):
429 IE_NAME = 'twitch:videos:all'
430 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
431 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
432 _PLAYLIST_TYPE = 'all videos'
435 'url': 'https://www.twitch.tv/spamfish/videos/all',
440 'playlist_mincount': 869,
442 'url': 'https://m.twitch.tv/spamfish/videos/all',
443 'only_matching': True,
447 class TwitchUploadsIE(TwitchVideosBaseIE):
448 IE_NAME = 'twitch:videos:uploads'
449 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
450 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
451 _PLAYLIST_TYPE = 'uploads'
454 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
459 'playlist_mincount': 0,
461 'url': 'https://m.twitch.tv/spamfish/videos/uploads',
462 'only_matching': True,
466 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
467 IE_NAME = 'twitch:videos:past-broadcasts'
468 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
469 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
470 _PLAYLIST_TYPE = 'past broadcasts'
473 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
478 'playlist_mincount': 0,
480 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
481 'only_matching': True,
485 class TwitchHighlightsIE(TwitchVideosBaseIE):
486 IE_NAME = 'twitch:videos:highlights'
487 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
488 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
489 _PLAYLIST_TYPE = 'highlights'
492 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
497 'playlist_mincount': 805,
499 'url': 'https://m.twitch.tv/spamfish/videos/highlights',
500 'only_matching': True,
504 class TwitchStreamIE(TwitchBaseIE):
505 IE_NAME = 'twitch:stream'
506 _VALID_URL = r'''(?x)
509 (?:(?:www|go|m)\.)?twitch\.tv/|
510 player\.twitch\.tv/\?.*?\bchannel=
516 'url': 'http://www.twitch.tv/shroomztv',
519 'display_id': 'shroomztv',
521 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
522 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
524 'timestamp': 1421928037,
525 'upload_date': '20150122',
526 'uploader': 'ShroomzTV',
527 'uploader_id': 'shroomztv',
532 'skip_download': True,
535 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
536 'only_matching': True,
538 'url': 'https://player.twitch.tv/?channel=lotsofs',
539 'only_matching': True,
541 'url': 'https://go.twitch.tv/food',
542 'only_matching': True,
544 'url': 'https://m.twitch.tv/food',
545 'only_matching': True,
549 def suitable(cls, url):
551 if any(ie.suitable(url) for ie in (
558 TwitchPastBroadcastsIE,
560 else super(TwitchStreamIE, cls).suitable(url))
562 def _real_extract(self, url):
563 channel_id = self._match_id(url)
565 stream = self._call_api(
566 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
567 'Downloading stream JSON').get('stream')
570 raise ExtractorError('%s is offline' % channel_id, expected=True)
572 # Channel name may be typed if different case than the original channel name
573 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
574 # an invalid m3u8 URL. Working around by use of original channel name from stream
575 # JSON and fallback to lowercase if it's not available.
576 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
578 access_token = self._call_api(
579 'api/channels/%s/access_token' % channel_id, channel_id,
580 'Downloading channel access token')
583 'allow_source': 'true',
584 'allow_audio_only': 'true',
585 'allow_spectre': 'true',
586 'p': random.randint(1000000, 10000000),
587 'player': 'twitchweb',
588 'segment_preference': '4',
589 'sig': access_token['sig'].encode('utf-8'),
590 'token': access_token['token'].encode('utf-8'),
592 formats = self._extract_m3u8_formats(
593 '%s/api/channel/hls/%s.m3u8?%s'
594 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
596 self._prefer_source(formats)
598 view_count = stream.get('viewers')
599 timestamp = parse_iso8601(stream.get('created_at'))
601 channel = stream['channel']
602 title = self._live_title(channel.get('display_name') or channel.get('name'))
603 description = channel.get('status')
606 for thumbnail_key, thumbnail_url in stream['preview'].items():
607 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
611 'url': thumbnail_url,
612 'width': int(m.group('width')),
613 'height': int(m.group('height')),
617 'id': compat_str(stream['_id']),
618 'display_id': channel_id,
620 'description': description,
621 'thumbnails': thumbnails,
622 'uploader': channel.get('display_name'),
623 'uploader_id': channel.get('name'),
624 'timestamp': timestamp,
625 'view_count': view_count,
631 class TwitchClipsIE(TwitchBaseIE):
632 IE_NAME = 'twitch:clips'
633 _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
636 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
637 'md5': '761769e1eafce0ffebfb4089cb3847cd',
641 'title': 'EA Play 2016 Live from the Novo Theatre',
642 'thumbnail': r're:^https?://.*\.jpg',
643 'timestamp': 1465767393,
644 'upload_date': '20160612',
646 'uploader': 'stereotype_',
647 'uploader_id': '43566419',
651 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
652 'only_matching': True,
655 def _real_extract(self, url):
656 video_id = self._match_id(url)
658 status = self._download_json(
659 'https://clips.twitch.tv/api/v2/clips/%s/status' % video_id,
664 for option in status['quality_options']:
665 if not isinstance(option, dict):
667 source = url_or_none(option.get('source'))
672 'format_id': option.get('quality'),
673 'height': int_or_none(option.get('quality')),
674 'fps': int_or_none(option.get('frame_rate')),
677 self._sort_formats(formats)
683 clip = self._call_api(
684 'kraken/clips/%s' % video_id, video_id, fatal=False, headers={
685 'Accept': 'application/vnd.twitchtv.v5+json',
689 quality_key = qualities(('tiny', 'small', 'medium'))
691 thumbnails_dict = clip.get('thumbnails')
692 if isinstance(thumbnails_dict, dict):
693 for thumbnail_id, thumbnail_url in thumbnails_dict.items():
696 'url': thumbnail_url,
697 'preference': quality_key(thumbnail_id),
701 'id': clip.get('tracking_id') or video_id,
702 'title': clip.get('title') or video_id,
703 'duration': float_or_none(clip.get('duration')),
704 'views': int_or_none(clip.get('views')),
705 'timestamp': unified_timestamp(clip.get('created_at')),
706 'thumbnails': thumbnails,
707 'creator': try_get(clip, lambda x: x['broadcaster']['display_name'], compat_str),
708 'uploader': try_get(clip, lambda x: x['curator']['display_name'], compat_str),
709 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),