2 from __future__ import unicode_literals
8 from .common import InfoExtractor
13 compat_urllib_parse_urlparse,
14 compat_urllib_request,
25 class TwitchBaseIE(InfoExtractor):
26 _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
28 _API_BASE = 'https://api.twitch.tv'
29 _USHER_BASE = 'http://usher.twitch.tv'
30 _LOGIN_URL = 'https://secure.twitch.tv/login'
31 _LOGIN_POST_URL = 'https://passport.twitch.tv/authentications/new'
32 _NETRC_MACHINE = 'twitch'
34 def _handle_error(self, response):
35 if not isinstance(response, dict):
37 error = response.get('error')
40 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
43 def _download_json(self, url, video_id, note='Downloading JSON metadata'):
45 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
46 'X-Requested-With': 'XMLHttpRequest',
48 for cookie in self._downloader.cookiejar:
49 if cookie.name == 'api_token':
50 headers['Twitch-Api-Token'] = cookie.value
51 request = compat_urllib_request.Request(url, headers=headers)
52 response = super(TwitchBaseIE, self)._download_json(request, video_id, note)
53 self._handle_error(response)
56 def _real_initialize(self):
60 (username, password) = self._get_login_info()
64 login_page = self._download_webpage(
65 self._LOGIN_URL, None, 'Downloading login page')
67 login_form = self._hidden_inputs(login_page)
70 'login': username.encode('utf-8'),
71 'password': password.encode('utf-8'),
74 post_url = self._search_regex(
75 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
76 'post url', default=self._LOGIN_POST_URL, group='url')
78 if not post_url.startswith('http'):
79 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
81 request = compat_urllib_request.Request(
82 post_url, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
83 request.add_header('Referer', self._LOGIN_URL)
84 response = self._download_webpage(
85 request, None, 'Logging in as %s' % username)
87 error_message = self._search_regex(
88 r'<div[^>]+class="subwindow_notice"[^>]*>([^<]+)</div>',
89 response, 'error message', default=None)
92 'Unable to login. Twitch said: %s' % error_message, expected=True)
94 if '>Reset your password<' in response:
95 self.report_warning('Twitch asks you to reset your password, go to https://secure.twitch.tv/reset/submit')
97 def _prefer_source(self, formats):
99 source = next(f for f in formats if f['format_id'] == 'Source')
100 source['preference'] = 10
101 except StopIteration:
102 pass # No Source stream present
103 self._sort_formats(formats)
106 class TwitchItemBaseIE(TwitchBaseIE):
107 def _download_info(self, item, item_id):
108 return self._extract_info(self._download_json(
109 '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
110 'Downloading %s info JSON' % self._ITEM_TYPE))
112 def _extract_media(self, item_id):
113 info = self._download_info(self._ITEM_SHORTCUT, item_id)
114 response = self._download_json(
115 '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
116 'Downloading %s playlist JSON' % self._ITEM_TYPE)
118 chunks = response['chunks']
119 qualities = list(chunks.keys())
120 for num, fragment in enumerate(zip(*chunks.values()), start=1):
122 for fmt_num, fragment_fmt in enumerate(fragment):
123 format_id = qualities[fmt_num]
125 'url': fragment_fmt['url'],
126 'format_id': format_id,
127 'quality': 1 if format_id == 'live' else 0,
129 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
131 fmt['height'] = int(m.group('height'))
133 self._sort_formats(formats)
135 entry['id'] = '%s_%d' % (entry['id'], num)
136 entry['title'] = '%s part %d' % (entry['title'], num)
137 entry['formats'] = formats
138 entries.append(entry)
139 return self.playlist_result(entries, info['id'], info['title'])
141 def _extract_info(self, info):
144 'title': info.get('title') or 'Untitled Broadcast',
145 'description': info.get('description'),
146 'duration': int_or_none(info.get('length')),
147 'thumbnail': info.get('preview'),
148 'uploader': info.get('channel', {}).get('display_name'),
149 'uploader_id': info.get('channel', {}).get('name'),
150 'timestamp': parse_iso8601(info.get('recorded_at')),
151 'view_count': int_or_none(info.get('views')),
154 def _real_extract(self, url):
155 return self._extract_media(self._match_id(url))
158 class TwitchVideoIE(TwitchItemBaseIE):
159 IE_NAME = 'twitch:video'
160 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
165 'url': 'http://www.twitch.tv/riotgames/b/577357806',
168 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
170 'playlist_mincount': 12,
174 class TwitchChapterIE(TwitchItemBaseIE):
175 IE_NAME = 'twitch:chapter'
176 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
177 _ITEM_TYPE = 'chapter'
181 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
184 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
186 'playlist_mincount': 3,
188 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
189 'only_matching': True,
193 class TwitchVodIE(TwitchItemBaseIE):
194 IE_NAME = 'twitch:vod'
195 _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
200 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
204 'title': 'LCK Summer Split - Week 6 Day 1',
205 'thumbnail': 're:^https?://.*\.jpg$',
207 'timestamp': 1435131709,
208 'upload_date': '20150624',
209 'uploader': 'Riot Games',
210 'uploader_id': 'riotgames',
216 'skip_download': True,
219 # Untitled broadcast (title is None)
220 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
224 'title': 'Untitled Broadcast',
225 'thumbnail': 're:^https?://.*\.jpg$',
227 'timestamp': 1439746708,
228 'upload_date': '20150816',
229 'uploader': 'BelkAO_o',
230 'uploader_id': 'belkao_o',
235 'skip_download': True,
239 def _real_extract(self, url):
240 item_id = self._match_id(url)
241 info = self._download_info(self._ITEM_SHORTCUT, item_id)
242 access_token = self._download_json(
243 '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
244 'Downloading %s access token' % self._ITEM_TYPE)
245 formats = self._extract_m3u8_formats(
246 '%s/vod/%s?nauth=%s&nauthsig=%s&allow_source=true'
247 % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
249 self._prefer_source(formats)
250 info['formats'] = formats
252 parsed_url = compat_urllib_parse_urlparse(url)
253 query = compat_parse_qs(parsed_url.query)
255 info['start_time'] = parse_duration(query['t'][0])
260 class TwitchPlaylistBaseIE(TwitchBaseIE):
261 _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
264 def _extract_playlist(self, channel_id):
265 info = self._download_json(
266 '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
267 channel_id, 'Downloading channel info JSON')
268 channel_name = info.get('display_name') or info.get('name')
271 limit = self._PAGE_LIMIT
272 for counter in itertools.count(1):
273 response = self._download_json(
274 self._PLAYLIST_URL % (channel_id, offset, limit),
275 channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
276 page_entries = self._extract_playlist_page(response)
279 entries.extend(page_entries)
281 return self.playlist_result(
282 [self.url_result(entry) for entry in set(entries)],
283 channel_id, channel_name)
285 def _extract_playlist_page(self, response):
286 videos = response.get('videos')
287 return [video['url'] for video in videos] if videos else []
289 def _real_extract(self, url):
290 return self._extract_playlist(self._match_id(url))
293 class TwitchProfileIE(TwitchPlaylistBaseIE):
294 IE_NAME = 'twitch:profile'
295 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
296 _PLAYLIST_TYPE = 'profile'
299 'url': 'http://www.twitch.tv/vanillatv/profile',
302 'title': 'VanillaTV',
304 'playlist_mincount': 412,
308 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
309 IE_NAME = 'twitch:past_broadcasts'
310 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
311 _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
312 _PLAYLIST_TYPE = 'past broadcasts'
315 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
320 'playlist_mincount': 54,
324 class TwitchBookmarksIE(TwitchPlaylistBaseIE):
325 IE_NAME = 'twitch:bookmarks'
326 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
327 _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
328 _PLAYLIST_TYPE = 'bookmarks'
331 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
336 'playlist_mincount': 3,
339 def _extract_playlist_page(self, response):
341 for bookmark in response.get('bookmarks', []):
342 video = bookmark.get('video')
345 entries.append(video['url'])
349 class TwitchStreamIE(TwitchBaseIE):
350 IE_NAME = 'twitch:stream'
351 _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
354 'url': 'http://www.twitch.tv/shroomztv',
357 'display_id': 'shroomztv',
359 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
360 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
362 'timestamp': 1421928037,
363 'upload_date': '20150122',
364 'uploader': 'ShroomzTV',
365 'uploader_id': 'shroomztv',
370 'skip_download': True,
373 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
374 'only_matching': True,
377 def _real_extract(self, url):
378 channel_id = self._match_id(url)
380 stream = self._download_json(
381 '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
382 'Downloading stream JSON').get('stream')
384 # Fallback on profile extraction if stream is offline
386 return self.url_result(
387 'http://www.twitch.tv/%s/profile' % channel_id,
388 'TwitchProfile', channel_id)
390 # Channel name may be typed if different case than the original channel name
391 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
392 # an invalid m3u8 URL. Working around by use of original channel name from stream
393 # JSON and fallback to lowercase if it's not available.
394 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
396 access_token = self._download_json(
397 '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
398 'Downloading channel access token')
401 'allow_source': 'true',
402 'p': random.randint(1000000, 10000000),
403 'player': 'twitchweb',
404 'segment_preference': '4',
405 'sig': access_token['sig'].encode('utf-8'),
406 'token': access_token['token'].encode('utf-8'),
408 formats = self._extract_m3u8_formats(
409 '%s/api/channel/hls/%s.m3u8?%s'
410 % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)),
412 self._prefer_source(formats)
414 view_count = stream.get('viewers')
415 timestamp = parse_iso8601(stream.get('created_at'))
417 channel = stream['channel']
418 title = self._live_title(channel.get('display_name') or channel.get('name'))
419 description = channel.get('status')
422 for thumbnail_key, thumbnail_url in stream['preview'].items():
423 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
427 'url': thumbnail_url,
428 'width': int(m.group('width')),
429 'height': int(m.group('height')),
433 'id': compat_str(stream['_id']),
434 'display_id': channel_id,
436 'description': description,
437 'thumbnails': thumbnails,
438 'uploader': channel.get('display_name'),
439 'uploader_id': channel.get('name'),
440 'timestamp': timestamp,
441 'view_count': view_count,