2 from __future__ import unicode_literals
7 from .common import InfoExtractor
11 compat_urllib_request,
19 class TwitchBaseIE(InfoExtractor):
20 _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
22 _API_BASE = 'https://api.twitch.tv'
23 _USHER_BASE = 'http://usher.twitch.tv'
24 _LOGIN_URL = 'https://secure.twitch.tv/user/login'
26 def _handle_error(self, response):
27 if not isinstance(response, dict):
29 error = response.get('error')
32 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
35 def _download_json(self, url, video_id, note='Downloading JSON metadata'):
36 response = super(TwitchBaseIE, self)._download_json(url, video_id, note)
37 self._handle_error(response)
40 def _real_initialize(self):
44 (username, password) = self._get_login_info()
48 login_page = self._download_webpage(
49 self._LOGIN_URL, None, 'Downloading login page')
51 authenticity_token = self._search_regex(
52 r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
53 login_page, 'authenticity token')
56 'utf8': '✓'.encode('utf-8'),
57 'authenticity_token': authenticity_token,
58 'redirect_on_login': '',
59 'embed_form': 'false',
60 'mp_source_action': '',
62 'user[login]': username,
63 'user[password]': password,
66 request = compat_urllib_request.Request(
67 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
68 request.add_header('Referer', self._LOGIN_URL)
69 response = self._download_webpage(
70 request, None, 'Logging in as %s' % username)
73 r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
76 'Unable to login: %s' % m.group('msg').strip(), expected=True)
79 class TwitchItemBaseIE(TwitchBaseIE):
80 def _download_info(self, item, item_id):
81 return self._extract_info(self._download_json(
82 '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
83 'Downloading %s info JSON' % self._ITEM_TYPE))
85 def _extract_media(self, item_id):
86 info = self._download_info(self._ITEM_SHORTCUT, item_id)
87 response = self._download_json(
88 '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
89 'Downloading %s playlist JSON' % self._ITEM_TYPE)
91 chunks = response['chunks']
92 qualities = list(chunks.keys())
93 for num, fragment in enumerate(zip(*chunks.values()), start=1):
95 for fmt_num, fragment_fmt in enumerate(fragment):
96 format_id = qualities[fmt_num]
98 'url': fragment_fmt['url'],
99 'format_id': format_id,
100 'quality': 1 if format_id == 'live' else 0,
102 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
104 fmt['height'] = int(m.group('height'))
106 self._sort_formats(formats)
108 entry['id'] = '%s_%d' % (entry['id'], num)
109 entry['title'] = '%s part %d' % (entry['title'], num)
110 entry['formats'] = formats
111 entries.append(entry)
112 return self.playlist_result(entries, info['id'], info['title'])
114 def _extract_info(self, info):
117 'title': info['title'],
118 'description': info['description'],
119 'duration': info['length'],
120 'thumbnail': info['preview'],
121 'uploader': info['channel']['display_name'],
122 'uploader_id': info['channel']['name'],
123 'timestamp': parse_iso8601(info['recorded_at']),
124 'view_count': info['views'],
127 def _real_extract(self, url):
128 return self._extract_media(self._match_id(url))
131 class TwitchVideoIE(TwitchItemBaseIE):
132 IE_NAME = 'twitch:video'
133 _VALID_URL = r'%s/[^/]+/b/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
138 'url': 'http://www.twitch.tv/riotgames/b/577357806',
141 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
143 'playlist_mincount': 12,
147 class TwitchChapterIE(TwitchItemBaseIE):
148 IE_NAME = 'twitch:chapter'
149 _VALID_URL = r'%s/[^/]+/c/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
150 _ITEM_TYPE = 'chapter'
154 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
157 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
159 'playlist_mincount': 3,
163 class TwitchVodIE(TwitchItemBaseIE):
164 IE_NAME = 'twitch:vod'
165 _VALID_URL = r'%s/[^/]+/v/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
170 'url': 'http://www.twitch.tv/ksptv/v/3622000',
174 'title': '''KSPTV: Squadcast: "Everyone's on vacation so here's Dahud" Edition!''',
175 'thumbnail': 're:^https?://.*\.jpg$',
177 'timestamp': 1419028564,
178 'upload_date': '20141219',
180 'uploader_id': 'ksptv',
185 'skip_download': True,
189 def _real_extract(self, url):
190 item_id = self._match_id(url)
191 info = self._download_info(self._ITEM_SHORTCUT, item_id)
192 access_token = self._download_json(
193 '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
194 'Downloading %s access token' % self._ITEM_TYPE)
195 formats = self._extract_m3u8_formats(
196 '%s/vod/%s?nauth=%s&nauthsig=%s'
197 % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
199 info['formats'] = formats
203 class TwitchPlaylistBaseIE(TwitchBaseIE):
204 _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
207 def _extract_playlist(self, channel_id):
208 info = self._download_json(
209 '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
210 channel_id, 'Downloading channel info JSON')
211 channel_name = info.get('display_name') or info.get('name')
214 limit = self._PAGE_LIMIT
215 for counter in itertools.count(1):
216 response = self._download_json(
217 self._PLAYLIST_URL % (channel_id, offset, limit),
218 channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
219 videos = response['videos']
222 entries.extend([self.url_result(video['url']) for video in videos])
224 return self.playlist_result(entries, channel_id, channel_name)
226 def _real_extract(self, url):
227 return self._extract_playlist(self._match_id(url))
230 class TwitchProfileIE(TwitchPlaylistBaseIE):
231 IE_NAME = 'twitch:profile'
232 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
233 _PLAYLIST_TYPE = 'profile'
236 'url': 'http://www.twitch.tv/vanillatv/profile',
239 'title': 'VanillaTV',
241 'playlist_mincount': 412,
245 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
246 IE_NAME = 'twitch:past_broadcasts'
247 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
248 _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
249 _PLAYLIST_TYPE = 'past broadcasts'
252 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
257 'playlist_mincount': 54,
261 class TwitchStreamIE(TwitchBaseIE):
262 IE_NAME = 'twitch:stream'
263 _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
266 'url': 'http://www.twitch.tv/shroomztv',
269 'display_id': 'shroomztv',
271 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
272 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
274 'timestamp': 1421928037,
275 'upload_date': '20150122',
276 'uploader': 'ShroomzTV',
277 'uploader_id': 'shroomztv',
282 'skip_download': True,
286 def _real_extract(self, url):
287 channel_id = self._match_id(url)
289 stream = self._download_json(
290 '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
291 'Downloading stream JSON').get('stream')
293 # Fallback on profile extraction if stream is offline
295 return self.url_result(
296 'http://www.twitch.tv/%s/profile' % channel_id,
297 'TwitchProfile', channel_id)
299 access_token = self._download_json(
300 '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
301 'Downloading channel access token')
304 'allow_source': 'true',
306 'player': 'twitchweb',
307 'segment_preference': '4',
308 'sig': access_token['sig'],
309 'token': access_token['token'],
312 formats = self._extract_m3u8_formats(
313 '%s/api/channel/hls/%s.m3u8?%s'
314 % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query).encode('utf-8')),
317 view_count = stream.get('viewers')
318 timestamp = parse_iso8601(stream.get('created_at'))
320 channel = stream['channel']
321 title = self._live_title(channel.get('display_name') or channel.get('name'))
322 description = channel.get('status')
325 for thumbnail_key, thumbnail_url in stream['preview'].items():
326 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
330 'url': thumbnail_url,
331 'width': int(m.group('width')),
332 'height': int(m.group('height')),
336 'id': compat_str(stream['_id']),
337 'display_id': channel_id,
339 'description': description,
340 'thumbnails': thumbnails,
341 'uploader': channel.get('display_name'),
342 'uploader_id': channel.get('name'),
343 'timestamp': timestamp,
344 'view_count': view_count,