2 from __future__ import unicode_literals
8 from .common import InfoExtractor
12 compat_urllib_request,
20 class TwitchBaseIE(InfoExtractor):
21 _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
23 _API_BASE = 'https://api.twitch.tv'
24 _USHER_BASE = 'http://usher.twitch.tv'
25 _LOGIN_URL = 'https://secure.twitch.tv/user/login'
27 def _handle_error(self, response):
28 if not isinstance(response, dict):
30 error = response.get('error')
33 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
36 def _download_json(self, url, video_id, note='Downloading JSON metadata'):
37 response = super(TwitchBaseIE, self)._download_json(url, video_id, note)
38 self._handle_error(response)
41 def _real_initialize(self):
45 (username, password) = self._get_login_info()
49 login_page = self._download_webpage(
50 self._LOGIN_URL, None, 'Downloading login page')
52 authenticity_token = self._search_regex(
53 r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
54 login_page, 'authenticity token')
57 'utf8': '✓'.encode('utf-8'),
58 'authenticity_token': authenticity_token,
59 'redirect_on_login': '',
60 'embed_form': 'false',
61 'mp_source_action': '',
63 'user[login]': username,
64 'user[password]': password,
67 request = compat_urllib_request.Request(
68 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
69 request.add_header('Referer', self._LOGIN_URL)
70 response = self._download_webpage(
71 request, None, 'Logging in as %s' % username)
74 r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
77 'Unable to login: %s' % m.group('msg').strip(), expected=True)
80 class TwitchItemBaseIE(TwitchBaseIE):
81 def _download_info(self, item, item_id):
82 return self._extract_info(self._download_json(
83 '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
84 'Downloading %s info JSON' % self._ITEM_TYPE))
86 def _extract_media(self, item_id):
87 info = self._download_info(self._ITEM_SHORTCUT, item_id)
88 response = self._download_json(
89 '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
90 'Downloading %s playlist JSON' % self._ITEM_TYPE)
92 chunks = response['chunks']
93 qualities = list(chunks.keys())
94 for num, fragment in enumerate(zip(*chunks.values()), start=1):
96 for fmt_num, fragment_fmt in enumerate(fragment):
97 format_id = qualities[fmt_num]
99 'url': fragment_fmt['url'],
100 'format_id': format_id,
101 'quality': 1 if format_id == 'live' else 0,
103 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
105 fmt['height'] = int(m.group('height'))
107 self._sort_formats(formats)
109 entry['id'] = '%s_%d' % (entry['id'], num)
110 entry['title'] = '%s part %d' % (entry['title'], num)
111 entry['formats'] = formats
112 entries.append(entry)
113 return self.playlist_result(entries, info['id'], info['title'])
115 def _extract_info(self, info):
118 'title': info['title'],
119 'description': info['description'],
120 'duration': info['length'],
121 'thumbnail': info['preview'],
122 'uploader': info['channel']['display_name'],
123 'uploader_id': info['channel']['name'],
124 'timestamp': parse_iso8601(info['recorded_at']),
125 'view_count': info['views'],
128 def _real_extract(self, url):
129 return self._extract_media(self._match_id(url))
132 class TwitchVideoIE(TwitchItemBaseIE):
133 IE_NAME = 'twitch:video'
134 _VALID_URL = r'%s/[^/]+/b/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
139 'url': 'http://www.twitch.tv/riotgames/b/577357806',
142 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
144 'playlist_mincount': 12,
148 class TwitchChapterIE(TwitchItemBaseIE):
149 IE_NAME = 'twitch:chapter'
150 _VALID_URL = r'%s/[^/]+/c/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
151 _ITEM_TYPE = 'chapter'
155 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
158 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
160 'playlist_mincount': 3,
162 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
163 'only_matching': True,
167 class TwitchVodIE(TwitchItemBaseIE):
168 IE_NAME = 'twitch:vod'
169 _VALID_URL = r'%s/[^/]+/v/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
174 'url': 'http://www.twitch.tv/ksptv/v/3622000',
178 'title': '''KSPTV: Squadcast: "Everyone's on vacation so here's Dahud" Edition!''',
179 'thumbnail': 're:^https?://.*\.jpg$',
181 'timestamp': 1419028564,
182 'upload_date': '20141219',
184 'uploader_id': 'ksptv',
189 'skip_download': True,
193 def _real_extract(self, url):
194 item_id = self._match_id(url)
195 info = self._download_info(self._ITEM_SHORTCUT, item_id)
196 access_token = self._download_json(
197 '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
198 'Downloading %s access token' % self._ITEM_TYPE)
199 formats = self._extract_m3u8_formats(
200 '%s/vod/%s?nauth=%s&nauthsig=%s'
201 % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
203 info['formats'] = formats
207 class TwitchPlaylistBaseIE(TwitchBaseIE):
208 _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
211 def _extract_playlist(self, channel_id):
212 info = self._download_json(
213 '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
214 channel_id, 'Downloading channel info JSON')
215 channel_name = info.get('display_name') or info.get('name')
218 limit = self._PAGE_LIMIT
219 for counter in itertools.count(1):
220 response = self._download_json(
221 self._PLAYLIST_URL % (channel_id, offset, limit),
222 channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
223 videos = response['videos']
226 entries.extend([self.url_result(video['url']) for video in videos])
228 return self.playlist_result(entries, channel_id, channel_name)
230 def _real_extract(self, url):
231 return self._extract_playlist(self._match_id(url))
234 class TwitchProfileIE(TwitchPlaylistBaseIE):
235 IE_NAME = 'twitch:profile'
236 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
237 _PLAYLIST_TYPE = 'profile'
240 'url': 'http://www.twitch.tv/vanillatv/profile',
243 'title': 'VanillaTV',
245 'playlist_mincount': 412,
249 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
250 IE_NAME = 'twitch:past_broadcasts'
251 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
252 _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
253 _PLAYLIST_TYPE = 'past broadcasts'
256 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
261 'playlist_mincount': 54,
265 class TwitchStreamIE(TwitchBaseIE):
266 IE_NAME = 'twitch:stream'
267 _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
270 'url': 'http://www.twitch.tv/shroomztv',
273 'display_id': 'shroomztv',
275 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
276 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
278 'timestamp': 1421928037,
279 'upload_date': '20150122',
280 'uploader': 'ShroomzTV',
281 'uploader_id': 'shroomztv',
286 'skip_download': True,
290 def _real_extract(self, url):
291 channel_id = self._match_id(url)
293 stream = self._download_json(
294 '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
295 'Downloading stream JSON').get('stream')
297 # Fallback on profile extraction if stream is offline
299 return self.url_result(
300 'http://www.twitch.tv/%s/profile' % channel_id,
301 'TwitchProfile', channel_id)
303 access_token = self._download_json(
304 '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
305 'Downloading channel access token')
308 'allow_source': 'true',
309 'p': random.randint(1000000, 10000000),
310 'player': 'twitchweb',
311 'segment_preference': '4',
312 'sig': access_token['sig'],
313 'token': access_token['token'],
316 formats = self._extract_m3u8_formats(
317 '%s/api/channel/hls/%s.m3u8?%s'
318 % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query).encode('utf-8')),
321 view_count = stream.get('viewers')
322 timestamp = parse_iso8601(stream.get('created_at'))
324 channel = stream['channel']
325 title = self._live_title(channel.get('display_name') or channel.get('name'))
326 description = channel.get('status')
329 for thumbnail_key, thumbnail_url in stream['preview'].items():
330 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
334 'url': thumbnail_url,
335 'width': int(m.group('width')),
336 'height': int(m.group('height')),
340 'id': compat_str(stream['_id']),
341 'display_id': channel_id,
343 'description': description,
344 'thumbnails': thumbnails,
345 'uploader': channel.get('display_name'),
346 'uploader_id': channel.get('name'),
347 'timestamp': timestamp,
348 'view_count': view_count,