2 from __future__ import unicode_literals
8 from .common import InfoExtractor
13 compat_urllib_parse_urlencode,
14 compat_urllib_parse_urlparse,
29 class TwitchBaseIE(InfoExtractor):
30 _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
32 _API_BASE = 'https://api.twitch.tv'
33 _USHER_BASE = 'https://usher.ttvnw.net'
34 _LOGIN_URL = 'http://www.twitch.tv/login'
35 _NETRC_MACHINE = 'twitch'
37 def _handle_error(self, response):
38 if not isinstance(response, dict):
40 error = response.get('error')
43 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
46 def _call_api(self, path, item_id, note):
48 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
49 'X-Requested-With': 'XMLHttpRequest',
51 for cookie in self._downloader.cookiejar:
52 if cookie.name == 'api_token':
53 headers['Twitch-Api-Token'] = cookie.value
54 response = self._download_json(
55 '%s/%s' % (self._API_BASE, path), item_id, note)
56 self._handle_error(response)
59 def _real_initialize(self):
63 (username, password) = self._get_login_info()
69 'Unable to login. Twitch said: %s' % message, expected=True)
71 login_page, handle = self._download_webpage_handle(
72 self._LOGIN_URL, None, 'Downloading login page')
74 # Some TOR nodes and public proxies are blocked completely
75 if 'blacklist_message' in login_page:
76 fail(clean_html(login_page))
78 login_form = self._hidden_inputs(login_page)
85 redirect_url = handle.geturl()
87 post_url = self._search_regex(
88 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
89 'post url', default=redirect_url, group='url')
91 if not post_url.startswith('http'):
92 post_url = compat_urlparse.urljoin(redirect_url, post_url)
94 headers = {'Referer': redirect_url}
97 response = self._download_json(
98 post_url, None, 'Logging in as %s' % username,
99 data=urlencode_postdata(login_form),
101 except ExtractorError as e:
102 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
103 response = self._parse_json(
104 e.cause.read().decode('utf-8'), None)
105 fail(response['message'])
108 if response.get('redirect'):
109 self._download_webpage(
110 response['redirect'], None, 'Downloading login redirect page',
113 def _prefer_source(self, formats):
115 source = next(f for f in formats if f['format_id'] == 'Source')
116 source['preference'] = 10
117 except StopIteration:
118 pass # No Source stream present
119 self._sort_formats(formats)
122 class TwitchItemBaseIE(TwitchBaseIE):
123 def _download_info(self, item, item_id):
124 return self._extract_info(self._call_api(
125 'kraken/videos/%s%s' % (item, item_id), item_id,
126 'Downloading %s info JSON' % self._ITEM_TYPE))
128 def _extract_media(self, item_id):
129 info = self._download_info(self._ITEM_SHORTCUT, item_id)
130 response = self._call_api(
131 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
132 'Downloading %s playlist JSON' % self._ITEM_TYPE)
134 chunks = response['chunks']
135 qualities = list(chunks.keys())
136 for num, fragment in enumerate(zip(*chunks.values()), start=1):
138 for fmt_num, fragment_fmt in enumerate(fragment):
139 format_id = qualities[fmt_num]
141 'url': fragment_fmt['url'],
142 'format_id': format_id,
143 'quality': 1 if format_id == 'live' else 0,
145 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
147 fmt['height'] = int(m.group('height'))
149 self._sort_formats(formats)
151 entry['id'] = '%s_%d' % (entry['id'], num)
152 entry['title'] = '%s part %d' % (entry['title'], num)
153 entry['formats'] = formats
154 entries.append(entry)
155 return self.playlist_result(entries, info['id'], info['title'])
157 def _extract_info(self, info):
160 'title': info.get('title') or 'Untitled Broadcast',
161 'description': info.get('description'),
162 'duration': int_or_none(info.get('length')),
163 'thumbnail': info.get('preview'),
164 'uploader': info.get('channel', {}).get('display_name'),
165 'uploader_id': info.get('channel', {}).get('name'),
166 'timestamp': parse_iso8601(info.get('recorded_at')),
167 'view_count': int_or_none(info.get('views')),
170 def _real_extract(self, url):
171 return self._extract_media(self._match_id(url))
174 class TwitchVideoIE(TwitchItemBaseIE):
175 IE_NAME = 'twitch:video'
176 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
181 'url': 'http://www.twitch.tv/riotgames/b/577357806',
184 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
186 'playlist_mincount': 12,
187 'skip': 'HTTP Error 404: Not Found',
191 class TwitchChapterIE(TwitchItemBaseIE):
192 IE_NAME = 'twitch:chapter'
193 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
194 _ITEM_TYPE = 'chapter'
198 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
201 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
203 'playlist_mincount': 3,
204 'skip': 'HTTP Error 404: Not Found',
206 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
207 'only_matching': True,
211 class TwitchVodIE(TwitchItemBaseIE):
212 IE_NAME = 'twitch:vod'
213 _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
218 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
222 'title': 'LCK Summer Split - Week 6 Day 1',
223 'thumbnail': 're:^https?://.*\.jpg$',
225 'timestamp': 1435131709,
226 'upload_date': '20150624',
227 'uploader': 'Riot Games',
228 'uploader_id': 'riotgames',
234 'skip_download': True,
237 # Untitled broadcast (title is None)
238 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
242 'title': 'Untitled Broadcast',
243 'thumbnail': 're:^https?://.*\.jpg$',
245 'timestamp': 1439746708,
246 'upload_date': '20150816',
247 'uploader': 'BelkAO_o',
248 'uploader_id': 'belkao_o',
253 'skip_download': True,
257 def _real_extract(self, url):
258 item_id = self._match_id(url)
260 info = self._download_info(self._ITEM_SHORTCUT, item_id)
261 access_token = self._call_api(
262 'api/vods/%s/access_token' % item_id, item_id,
263 'Downloading %s access token' % self._ITEM_TYPE)
265 formats = self._extract_m3u8_formats(
267 self._USHER_BASE, item_id,
268 compat_urllib_parse_urlencode({
269 'allow_source': 'true',
270 'allow_audio_only': 'true',
271 'allow_spectre': 'true',
272 'player': 'twitchweb',
273 'nauth': access_token['token'],
274 'nauthsig': access_token['sig'],
276 item_id, 'mp4', entry_protocol='m3u8_native')
278 self._prefer_source(formats)
279 info['formats'] = formats
281 parsed_url = compat_urllib_parse_urlparse(url)
282 query = compat_parse_qs(parsed_url.query)
284 info['start_time'] = parse_duration(query['t'][0])
289 class TwitchPlaylistBaseIE(TwitchBaseIE):
290 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
293 def _extract_playlist(self, channel_id):
294 info = self._call_api(
295 'kraken/channels/%s' % channel_id,
296 channel_id, 'Downloading channel info JSON')
297 channel_name = info.get('display_name') or info.get('name')
300 limit = self._PAGE_LIMIT
301 broken_paging_detected = False
302 counter_override = None
303 for counter in itertools.count(1):
304 response = self._call_api(
305 self._PLAYLIST_PATH % (channel_id, offset, limit),
307 'Downloading %s videos JSON page %s'
308 % (self._PLAYLIST_TYPE, counter_override or counter))
309 page_entries = self._extract_playlist_page(response)
312 total = int_or_none(response.get('_total'))
313 # Since the beginning of March 2016 twitch's paging mechanism
314 # is completely broken on the twitch side. It simply ignores
315 # a limit and returns the whole offset number of videos.
316 # Working around by just requesting all videos at once.
317 # Upd: pagination bug was fixed by twitch on 15.03.2016.
318 if not broken_paging_detected and total and len(page_entries) > limit:
320 'Twitch pagination is broken on twitch side, requesting all videos at once',
322 broken_paging_detected = True
324 counter_override = '(all at once)'
326 entries.extend(page_entries)
327 if broken_paging_detected or total and len(page_entries) >= total:
330 return self.playlist_result(
331 [self.url_result(entry) for entry in orderedSet(entries)],
332 channel_id, channel_name)
334 def _extract_playlist_page(self, response):
335 videos = response.get('videos')
336 return [video['url'] for video in videos] if videos else []
338 def _real_extract(self, url):
339 return self._extract_playlist(self._match_id(url))
342 class TwitchProfileIE(TwitchPlaylistBaseIE):
343 IE_NAME = 'twitch:profile'
344 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
345 _PLAYLIST_TYPE = 'profile'
348 'url': 'http://www.twitch.tv/vanillatv/profile',
351 'title': 'VanillaTV',
353 'playlist_mincount': 412,
357 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
358 IE_NAME = 'twitch:past_broadcasts'
359 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
360 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcasts=true'
361 _PLAYLIST_TYPE = 'past broadcasts'
364 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
369 'playlist_mincount': 54,
373 class TwitchStreamIE(TwitchBaseIE):
374 IE_NAME = 'twitch:stream'
375 _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
378 'url': 'http://www.twitch.tv/shroomztv',
381 'display_id': 'shroomztv',
383 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
384 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
386 'timestamp': 1421928037,
387 'upload_date': '20150122',
388 'uploader': 'ShroomzTV',
389 'uploader_id': 'shroomztv',
394 'skip_download': True,
397 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
398 'only_matching': True,
401 def _real_extract(self, url):
402 channel_id = self._match_id(url)
404 stream = self._call_api(
405 'kraken/streams/%s' % channel_id, channel_id,
406 'Downloading stream JSON').get('stream')
408 # Fallback on profile extraction if stream is offline
410 return self.url_result(
411 'http://www.twitch.tv/%s/profile' % channel_id,
412 'TwitchProfile', channel_id)
414 # Channel name may be typed if different case than the original channel name
415 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
416 # an invalid m3u8 URL. Working around by use of original channel name from stream
417 # JSON and fallback to lowercase if it's not available.
418 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
420 access_token = self._call_api(
421 'api/channels/%s/access_token' % channel_id, channel_id,
422 'Downloading channel access token')
425 'allow_source': 'true',
426 'allow_audio_only': 'true',
427 'p': random.randint(1000000, 10000000),
428 'player': 'twitchweb',
429 'segment_preference': '4',
430 'sig': access_token['sig'].encode('utf-8'),
431 'token': access_token['token'].encode('utf-8'),
433 formats = self._extract_m3u8_formats(
434 '%s/api/channel/hls/%s.m3u8?%s'
435 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
437 self._prefer_source(formats)
439 view_count = stream.get('viewers')
440 timestamp = parse_iso8601(stream.get('created_at'))
442 channel = stream['channel']
443 title = self._live_title(channel.get('display_name') or channel.get('name'))
444 description = channel.get('status')
447 for thumbnail_key, thumbnail_url in stream['preview'].items():
448 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
452 'url': thumbnail_url,
453 'width': int(m.group('width')),
454 'height': int(m.group('height')),
458 'id': compat_str(stream['_id']),
459 'display_id': channel_id,
461 'description': description,
462 'thumbnails': thumbnails,
463 'uploader': channel.get('display_name'),
464 'uploader_id': channel.get('name'),
465 'timestamp': timestamp,
466 'view_count': view_count,
472 class TwitchClipsIE(InfoExtractor):
473 IE_NAME = 'twitch:clips'
474 _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
477 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
478 'md5': '761769e1eafce0ffebfb4089cb3847cd',
480 'id': 'AggressiveCobraPoooound',
482 'title': 'EA Play 2016 Live from the Novo Theatre',
483 'thumbnail': 're:^https?://.*\.jpg',
485 'uploader': 'stereotype_',
486 'uploader_id': 'stereotype_',
490 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
491 'only_matching': True,
494 def _real_extract(self, url):
495 video_id = self._match_id(url)
497 webpage = self._download_webpage(url, video_id)
499 clip = self._parse_json(
501 r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
502 video_id, transform_source=js_to_json)
504 title = clip.get('channel_title') or self._og_search_title(webpage)
507 'url': option['source'],
508 'format_id': option.get('quality'),
509 'height': int_or_none(option.get('quality')),
510 } for option in clip.get('quality_options', []) if option.get('source')]
514 'url': clip['clip_video_url'],
517 self._sort_formats(formats)
522 'thumbnail': self._og_search_thumbnail(webpage),
523 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
524 'uploader': clip.get('curator_login'),
525 'uploader_id': clip.get('curator_display_name'),