2 from __future__ import unicode_literals
8 from .common import InfoExtractor
13 compat_urllib_parse_urlencode,
14 compat_urllib_parse_urlparse,
30 class TwitchBaseIE(InfoExtractor):
31 _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
33 _API_BASE = 'https://api.twitch.tv'
34 _USHER_BASE = 'https://usher.ttvnw.net'
35 _LOGIN_URL = 'http://www.twitch.tv/login'
36 _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6'
37 _NETRC_MACHINE = 'twitch'
39 def _handle_error(self, response):
40 if not isinstance(response, dict):
42 error = response.get('error')
45 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
48 def _call_api(self, path, item_id, note):
49 response = self._download_json(
50 '%s/%s' % (self._API_BASE, path), item_id, note,
51 headers={'Client-ID': self._CLIENT_ID})
52 self._handle_error(response)
55 def _real_initialize(self):
59 (username, password) = self._get_login_info()
65 'Unable to login. Twitch said: %s' % message, expected=True)
67 login_page, handle = self._download_webpage_handle(
68 self._LOGIN_URL, None, 'Downloading login page')
70 # Some TOR nodes and public proxies are blocked completely
71 if 'blacklist_message' in login_page:
72 fail(clean_html(login_page))
74 login_form = self._hidden_inputs(login_page)
81 redirect_url = handle.geturl()
83 post_url = self._search_regex(
84 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
85 'post url', default=redirect_url, group='url')
87 if not post_url.startswith('http'):
88 post_url = compat_urlparse.urljoin(redirect_url, post_url)
90 headers = {'Referer': redirect_url}
93 response = self._download_json(
94 post_url, None, 'Logging in as %s' % username,
95 data=urlencode_postdata(login_form),
97 except ExtractorError as e:
98 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
99 response = self._parse_json(
100 e.cause.read().decode('utf-8'), None)
101 fail(response['message'])
104 if response.get('redirect'):
105 self._download_webpage(
106 response['redirect'], None, 'Downloading login redirect page',
109 def _prefer_source(self, formats):
111 source = next(f for f in formats if f['format_id'] == 'Source')
112 source['preference'] = 10
113 except StopIteration:
114 pass # No Source stream present
115 self._sort_formats(formats)
118 class TwitchItemBaseIE(TwitchBaseIE):
119 def _download_info(self, item, item_id):
120 return self._extract_info(self._call_api(
121 'kraken/videos/%s%s' % (item, item_id), item_id,
122 'Downloading %s info JSON' % self._ITEM_TYPE))
124 def _extract_media(self, item_id):
125 info = self._download_info(self._ITEM_SHORTCUT, item_id)
126 response = self._call_api(
127 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
128 'Downloading %s playlist JSON' % self._ITEM_TYPE)
130 chunks = response['chunks']
131 qualities = list(chunks.keys())
132 for num, fragment in enumerate(zip(*chunks.values()), start=1):
134 for fmt_num, fragment_fmt in enumerate(fragment):
135 format_id = qualities[fmt_num]
137 'url': fragment_fmt['url'],
138 'format_id': format_id,
139 'quality': 1 if format_id == 'live' else 0,
141 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
143 fmt['height'] = int(m.group('height'))
145 self._sort_formats(formats)
147 entry['id'] = '%s_%d' % (entry['id'], num)
148 entry['title'] = '%s part %d' % (entry['title'], num)
149 entry['formats'] = formats
150 entries.append(entry)
151 return self.playlist_result(entries, info['id'], info['title'])
153 def _extract_info(self, info):
156 'title': info.get('title') or 'Untitled Broadcast',
157 'description': info.get('description'),
158 'duration': int_or_none(info.get('length')),
159 'thumbnail': info.get('preview'),
160 'uploader': info.get('channel', {}).get('display_name'),
161 'uploader_id': info.get('channel', {}).get('name'),
162 'timestamp': parse_iso8601(info.get('recorded_at')),
163 'view_count': int_or_none(info.get('views')),
166 def _real_extract(self, url):
167 return self._extract_media(self._match_id(url))
170 class TwitchVideoIE(TwitchItemBaseIE):
171 IE_NAME = 'twitch:video'
172 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
177 'url': 'http://www.twitch.tv/riotgames/b/577357806',
180 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
182 'playlist_mincount': 12,
183 'skip': 'HTTP Error 404: Not Found',
187 class TwitchChapterIE(TwitchItemBaseIE):
188 IE_NAME = 'twitch:chapter'
189 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
190 _ITEM_TYPE = 'chapter'
194 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
197 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
199 'playlist_mincount': 3,
200 'skip': 'HTTP Error 404: Not Found',
202 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
203 'only_matching': True,
207 class TwitchVodIE(TwitchItemBaseIE):
208 IE_NAME = 'twitch:vod'
209 _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
214 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
218 'title': 'LCK Summer Split - Week 6 Day 1',
219 'thumbnail': 're:^https?://.*\.jpg$',
221 'timestamp': 1435131709,
222 'upload_date': '20150624',
223 'uploader': 'Riot Games',
224 'uploader_id': 'riotgames',
230 'skip_download': True,
233 # Untitled broadcast (title is None)
234 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
238 'title': 'Untitled Broadcast',
239 'thumbnail': 're:^https?://.*\.jpg$',
241 'timestamp': 1439746708,
242 'upload_date': '20150816',
243 'uploader': 'BelkAO_o',
244 'uploader_id': 'belkao_o',
249 'skip_download': True,
251 'skip': 'HTTP Error 404: Not Found',
254 def _real_extract(self, url):
255 item_id = self._match_id(url)
257 info = self._download_info(self._ITEM_SHORTCUT, item_id)
258 access_token = self._call_api(
259 'api/vods/%s/access_token' % item_id, item_id,
260 'Downloading %s access token' % self._ITEM_TYPE)
262 formats = self._extract_m3u8_formats(
264 self._USHER_BASE, item_id,
265 compat_urllib_parse_urlencode({
266 'allow_source': 'true',
267 'allow_audio_only': 'true',
268 'allow_spectre': 'true',
269 'player': 'twitchweb',
270 'nauth': access_token['token'],
271 'nauthsig': access_token['sig'],
273 item_id, 'mp4', entry_protocol='m3u8_native')
275 self._prefer_source(formats)
276 info['formats'] = formats
278 parsed_url = compat_urllib_parse_urlparse(url)
279 query = compat_parse_qs(parsed_url.query)
281 info['start_time'] = parse_duration(query['t'][0])
283 if info.get('timestamp') is not None:
284 info['subtitles'] = {
286 'url': update_url_query(
287 'https://rechat.twitch.tv/rechat-messages', {
288 'video_id': 'v%s' % item_id,
289 'start': info['timestamp'],
298 class TwitchPlaylistBaseIE(TwitchBaseIE):
299 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
302 def _extract_playlist(self, channel_id):
303 info = self._call_api(
304 'kraken/channels/%s' % channel_id,
305 channel_id, 'Downloading channel info JSON')
306 channel_name = info.get('display_name') or info.get('name')
309 limit = self._PAGE_LIMIT
310 broken_paging_detected = False
311 counter_override = None
312 for counter in itertools.count(1):
313 response = self._call_api(
314 self._PLAYLIST_PATH % (channel_id, offset, limit),
316 'Downloading %s JSON page %s'
317 % (self._PLAYLIST_TYPE, counter_override or counter))
318 page_entries = self._extract_playlist_page(response)
321 total = int_or_none(response.get('_total'))
322 # Since the beginning of March 2016 twitch's paging mechanism
323 # is completely broken on the twitch side. It simply ignores
324 # a limit and returns the whole offset number of videos.
325 # Working around by just requesting all videos at once.
326 # Upd: pagination bug was fixed by twitch on 15.03.2016.
327 if not broken_paging_detected and total and len(page_entries) > limit:
329 'Twitch pagination is broken on twitch side, requesting all videos at once',
331 broken_paging_detected = True
333 counter_override = '(all at once)'
335 entries.extend(page_entries)
336 if broken_paging_detected or total and len(page_entries) >= total:
339 return self.playlist_result(
340 [self.url_result(entry) for entry in orderedSet(entries)],
341 channel_id, channel_name)
343 def _extract_playlist_page(self, response):
344 videos = response.get('videos')
345 return [video['url'] for video in videos] if videos else []
347 def _real_extract(self, url):
348 return self._extract_playlist(self._match_id(url))
351 class TwitchProfileIE(TwitchPlaylistBaseIE):
352 IE_NAME = 'twitch:profile'
353 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
354 _PLAYLIST_TYPE = 'profile'
357 'url': 'http://www.twitch.tv/vanillatv/profile',
360 'title': 'VanillaTV',
362 'playlist_mincount': 412,
366 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
367 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
368 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
371 class TwitchAllVideosIE(TwitchVideosBaseIE):
372 IE_NAME = 'twitch:videos:all'
373 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
374 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
375 _PLAYLIST_TYPE = 'all videos'
378 'url': 'https://www.twitch.tv/spamfish/videos/all',
383 'playlist_mincount': 869,
387 class TwitchUploadsIE(TwitchVideosBaseIE):
388 IE_NAME = 'twitch:videos:uploads'
389 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
390 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
391 _PLAYLIST_TYPE = 'uploads'
394 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
399 'playlist_mincount': 0,
403 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
404 IE_NAME = 'twitch:videos:past-broadcasts'
405 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
406 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
407 _PLAYLIST_TYPE = 'past broadcasts'
410 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
415 'playlist_mincount': 0,
419 class TwitchHighlightsIE(TwitchVideosBaseIE):
420 IE_NAME = 'twitch:videos:highlights'
421 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
422 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
423 _PLAYLIST_TYPE = 'highlights'
426 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
431 'playlist_mincount': 805,
435 class TwitchStreamIE(TwitchBaseIE):
436 IE_NAME = 'twitch:stream'
437 _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
440 'url': 'http://www.twitch.tv/shroomztv',
443 'display_id': 'shroomztv',
445 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
446 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
448 'timestamp': 1421928037,
449 'upload_date': '20150122',
450 'uploader': 'ShroomzTV',
451 'uploader_id': 'shroomztv',
456 'skip_download': True,
459 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
460 'only_matching': True,
463 def _real_extract(self, url):
464 channel_id = self._match_id(url)
466 stream = self._call_api(
467 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
468 'Downloading stream JSON').get('stream')
471 raise ExtractorError('%s is offline' % channel_id, expected=True)
473 # Channel name may be typed if different case than the original channel name
474 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
475 # an invalid m3u8 URL. Working around by use of original channel name from stream
476 # JSON and fallback to lowercase if it's not available.
477 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
479 access_token = self._call_api(
480 'api/channels/%s/access_token' % channel_id, channel_id,
481 'Downloading channel access token')
484 'allow_source': 'true',
485 'allow_audio_only': 'true',
486 'allow_spectre': 'true',
487 'p': random.randint(1000000, 10000000),
488 'player': 'twitchweb',
489 'segment_preference': '4',
490 'sig': access_token['sig'].encode('utf-8'),
491 'token': access_token['token'].encode('utf-8'),
493 formats = self._extract_m3u8_formats(
494 '%s/api/channel/hls/%s.m3u8?%s'
495 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
497 self._prefer_source(formats)
499 view_count = stream.get('viewers')
500 timestamp = parse_iso8601(stream.get('created_at'))
502 channel = stream['channel']
503 title = self._live_title(channel.get('display_name') or channel.get('name'))
504 description = channel.get('status')
507 for thumbnail_key, thumbnail_url in stream['preview'].items():
508 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
512 'url': thumbnail_url,
513 'width': int(m.group('width')),
514 'height': int(m.group('height')),
518 'id': compat_str(stream['_id']),
519 'display_id': channel_id,
521 'description': description,
522 'thumbnails': thumbnails,
523 'uploader': channel.get('display_name'),
524 'uploader_id': channel.get('name'),
525 'timestamp': timestamp,
526 'view_count': view_count,
532 class TwitchClipsIE(InfoExtractor):
533 IE_NAME = 'twitch:clips'
534 _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
537 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
538 'md5': '761769e1eafce0ffebfb4089cb3847cd',
540 'id': 'AggressiveCobraPoooound',
542 'title': 'EA Play 2016 Live from the Novo Theatre',
543 'thumbnail': 're:^https?://.*\.jpg',
545 'uploader': 'stereotype_',
546 'uploader_id': 'stereotype_',
550 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
551 'only_matching': True,
554 def _real_extract(self, url):
555 video_id = self._match_id(url)
557 webpage = self._download_webpage(url, video_id)
559 clip = self._parse_json(
561 r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
562 video_id, transform_source=js_to_json)
564 title = clip.get('channel_title') or self._og_search_title(webpage)
567 'url': option['source'],
568 'format_id': option.get('quality'),
569 'height': int_or_none(option.get('quality')),
570 } for option in clip.get('quality_options', []) if option.get('source')]
574 'url': clip['clip_video_url'],
577 self._sort_formats(formats)
582 'thumbnail': self._og_search_thumbnail(webpage),
583 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
584 'uploader': clip.get('curator_login'),
585 'uploader_id': clip.get('curator_display_name'),