]>
Commit | Line | Data |
---|---|---|
04d02a9d | 1 | # coding: utf-8 |
ee1e1996 PH |
2 | from __future__ import unicode_literals |
3 | ||
3182f3e2 | 4 | import itertools |
79e93125 | 5 | import re |
f353cbdb | 6 | import random |
79e93125 PH |
7 | |
8 | from .common import InfoExtractor | |
1cc79574 | 9 | from ..compat import ( |
e704f87f | 10 | compat_parse_qs, |
240b9b7a | 11 | compat_str, |
04d02a9d | 12 | compat_urllib_parse, |
e704f87f | 13 | compat_urllib_parse_urlparse, |
04d02a9d | 14 | compat_urllib_request, |
03c635a4 | 15 | compat_urlparse, |
1cc79574 PH |
16 | ) |
17 | from ..utils import ( | |
fbd9f6ea | 18 | encode_dict, |
79e93125 | 19 | ExtractorError, |
7a6e8a1b | 20 | int_or_none, |
e704f87f | 21 | parse_duration, |
355d074f | 22 | parse_iso8601, |
79e93125 PH |
23 | ) |
24 | ||
25 | ||
c5db6bb3 | 26 | class TwitchBaseIE(InfoExtractor): |
240b9b7a | 27 | _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv' |
c5db6bb3 | 28 | |
46fd0dd5 | 29 | _API_BASE = 'https://api.twitch.tv' |
240b9b7a | 30 | _USHER_BASE = 'http://usher.twitch.tv' |
fbd9f6ea | 31 | _LOGIN_URL = 'http://www.twitch.tv/login' |
499bfcbf | 32 | _NETRC_MACHINE = 'twitch' |
79e93125 | 33 | |
355d074f S |
34 | def _handle_error(self, response): |
35 | if not isinstance(response, dict): | |
36 | return | |
37 | error = response.get('error') | |
38 | if error: | |
39 | raise ExtractorError( | |
40 | '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')), | |
41 | expected=True) | |
42 | ||
43 | def _download_json(self, url, video_id, note='Downloading JSON metadata'): | |
0d103de3 S |
44 | headers = { |
45 | 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2', | |
46 | 'X-Requested-With': 'XMLHttpRequest', | |
47 | } | |
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) | |
355d074f S |
53 | self._handle_error(response) |
54 | return response | |
55 | ||
c5db6bb3 S |
56 | def _real_initialize(self): |
57 | self._login() | |
58 | ||
59 | def _login(self): | |
60 | (username, password) = self._get_login_info() | |
61 | if username is None: | |
62 | return | |
63 | ||
fbd9f6ea | 64 | login_page, handle = self._download_webpage_handle( |
c5db6bb3 S |
65 | self._LOGIN_URL, None, 'Downloading login page') |
66 | ||
f8da79f8 | 67 | login_form = self._hidden_inputs(login_page) |
c5db6bb3 | 68 | |
9296e92e | 69 | login_form.update({ |
fbd9f6ea S |
70 | 'username': username, |
71 | 'password': password, | |
9296e92e | 72 | }) |
c5db6bb3 | 73 | |
fbd9f6ea S |
74 | redirect_url = handle.geturl() |
75 | ||
03c635a4 S |
76 | post_url = self._search_regex( |
77 | r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page, | |
fbd9f6ea | 78 | 'post url', default=redirect_url, group='url') |
03c635a4 S |
79 | |
80 | if not post_url.startswith('http'): | |
fbd9f6ea | 81 | post_url = compat_urlparse.urljoin(redirect_url, post_url) |
03c635a4 | 82 | |
c5db6bb3 | 83 | request = compat_urllib_request.Request( |
fbd9f6ea S |
84 | post_url, compat_urllib_parse.urlencode(encode_dict(login_form)).encode('utf-8')) |
85 | request.add_header('Referer', redirect_url) | |
c5db6bb3 S |
86 | response = self._download_webpage( |
87 | request, None, 'Logging in as %s' % username) | |
88 | ||
89a683ae S |
89 | error_message = self._search_regex( |
90 | r'<div[^>]+class="subwindow_notice"[^>]*>([^<]+)</div>', | |
91 | response, 'error message', default=None) | |
92 | if error_message: | |
c5db6bb3 | 93 | raise ExtractorError( |
89a683ae | 94 | 'Unable to login. Twitch said: %s' % error_message, expected=True) |
c5db6bb3 | 95 | |
17b41a33 S |
96 | if '>Reset your password<' in response: |
97 | self.report_warning('Twitch asks you to reset your password, go to https://secure.twitch.tv/reset/submit') | |
98 | ||
d0e958c7 PH |
99 | def _prefer_source(self, formats): |
100 | try: | |
101 | source = next(f for f in formats if f['format_id'] == 'Source') | |
102 | source['preference'] = 10 | |
103 | except StopIteration: | |
104 | pass # No Source stream present | |
105 | self._sort_formats(formats) | |
106 | ||
c5db6bb3 S |
107 | |
108 | class TwitchItemBaseIE(TwitchBaseIE): | |
109 | def _download_info(self, item, item_id): | |
110 | return self._extract_info(self._download_json( | |
355d074f | 111 | '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id, |
c5db6bb3 | 112 | 'Downloading %s info JSON' % self._ITEM_TYPE)) |
a22524b0 | 113 | |
c5db6bb3 S |
114 | def _extract_media(self, item_id): |
115 | info = self._download_info(self._ITEM_SHORTCUT, item_id) | |
355d074f | 116 | response = self._download_json( |
c5db6bb3 S |
117 | '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id, |
118 | 'Downloading %s playlist JSON' % self._ITEM_TYPE) | |
355d074f S |
119 | entries = [] |
120 | chunks = response['chunks'] | |
121 | qualities = list(chunks.keys()) | |
122 | for num, fragment in enumerate(zip(*chunks.values()), start=1): | |
123 | formats = [] | |
124 | for fmt_num, fragment_fmt in enumerate(fragment): | |
125 | format_id = qualities[fmt_num] | |
126 | fmt = { | |
127 | 'url': fragment_fmt['url'], | |
128 | 'format_id': format_id, | |
129 | 'quality': 1 if format_id == 'live' else 0, | |
130 | } | |
131 | m = re.search(r'^(?P<height>\d+)[Pp]', format_id) | |
132 | if m: | |
133 | fmt['height'] = int(m.group('height')) | |
134 | formats.append(fmt) | |
135 | self._sort_formats(formats) | |
136 | entry = dict(info) | |
159444a6 | 137 | entry['id'] = '%s_%d' % (entry['id'], num) |
355d074f S |
138 | entry['title'] = '%s part %d' % (entry['title'], num) |
139 | entry['formats'] = formats | |
140 | entries.append(entry) | |
013bfdd8 | 141 | return self.playlist_result(entries, info['id'], info['title']) |
355d074f S |
142 | |
143 | def _extract_info(self, info): | |
144 | return { | |
145 | 'id': info['_id'], | |
369c12e0 | 146 | 'title': info.get('title') or 'Untitled Broadcast', |
7a6e8a1b S |
147 | 'description': info.get('description'), |
148 | 'duration': int_or_none(info.get('length')), | |
149 | 'thumbnail': info.get('preview'), | |
150 | 'uploader': info.get('channel', {}).get('display_name'), | |
151 | 'uploader_id': info.get('channel', {}).get('name'), | |
152 | 'timestamp': parse_iso8601(info.get('recorded_at')), | |
153 | 'view_count': int_or_none(info.get('views')), | |
355d074f S |
154 | } |
155 | ||
c5db6bb3 S |
156 | def _real_extract(self, url): |
157 | return self._extract_media(self._match_id(url)) | |
04d02a9d | 158 | |
04d02a9d | 159 | |
c5db6bb3 S |
160 | class TwitchVideoIE(TwitchItemBaseIE): |
161 | IE_NAME = 'twitch:video' | |
93f78707 | 162 | _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE |
c5db6bb3 S |
163 | _ITEM_TYPE = 'video' |
164 | _ITEM_SHORTCUT = 'a' | |
04d02a9d | 165 | |
c5db6bb3 S |
166 | _TEST = { |
167 | 'url': 'http://www.twitch.tv/riotgames/b/577357806', | |
168 | 'info_dict': { | |
169 | 'id': 'a577357806', | |
170 | 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG', | |
171 | }, | |
172 | 'playlist_mincount': 12, | |
173 | } | |
04d02a9d | 174 | |
04d02a9d | 175 | |
c5db6bb3 S |
176 | class TwitchChapterIE(TwitchItemBaseIE): |
177 | IE_NAME = 'twitch:chapter' | |
93f78707 | 178 | _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE |
c5db6bb3 S |
179 | _ITEM_TYPE = 'chapter' |
180 | _ITEM_SHORTCUT = 'c' | |
04d02a9d | 181 | |
78111136 | 182 | _TESTS = [{ |
c5db6bb3 S |
183 | 'url': 'http://www.twitch.tv/acracingleague/c/5285812', |
184 | 'info_dict': { | |
185 | 'id': 'c5285812', | |
186 | 'title': 'ACRL Off Season - Sports Cars @ Nordschleife', | |
187 | }, | |
188 | 'playlist_mincount': 3, | |
78111136 PH |
189 | }, { |
190 | 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361', | |
191 | 'only_matching': True, | |
192 | }] | |
c5db6bb3 S |
193 | |
194 | ||
195 | class TwitchVodIE(TwitchItemBaseIE): | |
196 | IE_NAME = 'twitch:vod' | |
93f78707 | 197 | _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE |
c5db6bb3 S |
198 | _ITEM_TYPE = 'vod' |
199 | _ITEM_SHORTCUT = 'v' | |
200 | ||
9c724a98 | 201 | _TESTS = [{ |
e704f87f | 202 | 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s', |
c5db6bb3 | 203 | 'info_dict': { |
ac0474f8 | 204 | 'id': 'v6528877', |
c5db6bb3 | 205 | 'ext': 'mp4', |
ac0474f8 | 206 | 'title': 'LCK Summer Split - Week 6 Day 1', |
c5db6bb3 | 207 | 'thumbnail': 're:^https?://.*\.jpg$', |
ac0474f8 YCH |
208 | 'duration': 17208, |
209 | 'timestamp': 1435131709, | |
210 | 'upload_date': '20150624', | |
211 | 'uploader': 'Riot Games', | |
212 | 'uploader_id': 'riotgames', | |
c5db6bb3 | 213 | 'view_count': int, |
e704f87f | 214 | 'start_time': 310, |
c5db6bb3 S |
215 | }, |
216 | 'params': { | |
217 | # m3u8 download | |
218 | 'skip_download': True, | |
219 | }, | |
9c724a98 S |
220 | }, { |
221 | # Untitled broadcast (title is None) | |
222 | 'url': 'http://www.twitch.tv/belkao_o/v/11230755', | |
223 | 'info_dict': { | |
224 | 'id': 'v11230755', | |
225 | 'ext': 'mp4', | |
226 | 'title': 'Untitled Broadcast', | |
227 | 'thumbnail': 're:^https?://.*\.jpg$', | |
228 | 'duration': 1638, | |
229 | 'timestamp': 1439746708, | |
230 | 'upload_date': '20150816', | |
231 | 'uploader': 'BelkAO_o', | |
232 | 'uploader_id': 'belkao_o', | |
233 | 'view_count': int, | |
234 | }, | |
235 | 'params': { | |
236 | # m3u8 download | |
237 | 'skip_download': True, | |
238 | }, | |
239 | }] | |
04d02a9d | 240 | |
79e93125 | 241 | def _real_extract(self, url): |
c5db6bb3 | 242 | item_id = self._match_id(url) |
e5e99661 | 243 | |
c5db6bb3 S |
244 | info = self._download_info(self._ITEM_SHORTCUT, item_id) |
245 | access_token = self._download_json( | |
350c9481 S |
246 | '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id, |
247 | 'Downloading %s access token' % self._ITEM_TYPE) | |
e5e99661 | 248 | |
c5db6bb3 | 249 | formats = self._extract_m3u8_formats( |
350c9481 S |
250 | '%s/vod/%s?%s' % ( |
251 | self._USHER_BASE, item_id, | |
252 | compat_urllib_parse.urlencode({ | |
e5e99661 S |
253 | 'allow_source': 'true', |
254 | 'allow_spectre': 'true', | |
255 | 'player': 'twitchweb', | |
256 | 'nauth': access_token['token'], | |
257 | 'nauthsig': access_token['sig'], | |
258 | })), | |
350c9481 | 259 | item_id, 'mp4') |
e5e99661 | 260 | |
d0e958c7 | 261 | self._prefer_source(formats) |
c5db6bb3 | 262 | info['formats'] = formats |
e704f87f NH |
263 | |
264 | parsed_url = compat_urllib_parse_urlparse(url) | |
265 | query = compat_parse_qs(parsed_url.query) | |
266 | if 't' in query: | |
267 | info['start_time'] = parse_duration(query['t'][0]) | |
268 | ||
c5db6bb3 S |
269 | return info |
270 | ||
271 | ||
272 | class TwitchPlaylistBaseIE(TwitchBaseIE): | |
273 | _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE | |
274 | _PAGE_LIMIT = 100 | |
275 | ||
276 | def _extract_playlist(self, channel_id): | |
277 | info = self._download_json( | |
278 | '%s/kraken/channels/%s' % (self._API_BASE, channel_id), | |
279 | channel_id, 'Downloading channel info JSON') | |
280 | channel_name = info.get('display_name') or info.get('name') | |
281 | entries = [] | |
282 | offset = 0 | |
283 | limit = self._PAGE_LIMIT | |
284 | for counter in itertools.count(1): | |
285 | response = self._download_json( | |
286 | self._PLAYLIST_URL % (channel_id, offset, limit), | |
287 | channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter)) | |
c2e64f71 S |
288 | page_entries = self._extract_playlist_page(response) |
289 | if not page_entries: | |
c5db6bb3 | 290 | break |
c2e64f71 | 291 | entries.extend(page_entries) |
c5db6bb3 | 292 | offset += limit |
c2e64f71 S |
293 | return self.playlist_result( |
294 | [self.url_result(entry) for entry in set(entries)], | |
295 | channel_id, channel_name) | |
296 | ||
297 | def _extract_playlist_page(self, response): | |
298 | videos = response.get('videos') | |
299 | return [video['url'] for video in videos] if videos else [] | |
c5db6bb3 S |
300 | |
301 | def _real_extract(self, url): | |
302 | return self._extract_playlist(self._match_id(url)) | |
303 | ||
304 | ||
305 | class TwitchProfileIE(TwitchPlaylistBaseIE): | |
306 | IE_NAME = 'twitch:profile' | |
307 | _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE | |
308 | _PLAYLIST_TYPE = 'profile' | |
309 | ||
310 | _TEST = { | |
311 | 'url': 'http://www.twitch.tv/vanillatv/profile', | |
312 | 'info_dict': { | |
313 | 'id': 'vanillatv', | |
314 | 'title': 'VanillaTV', | |
315 | }, | |
316 | 'playlist_mincount': 412, | |
317 | } | |
318 | ||
319 | ||
320 | class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE): | |
8bb1bdfa | 321 | IE_NAME = 'twitch:past_broadcasts' |
c5db6bb3 S |
322 | _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE |
323 | _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true' | |
324 | _PLAYLIST_TYPE = 'past broadcasts' | |
325 | ||
326 | _TEST = { | |
327 | 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts', | |
328 | 'info_dict': { | |
329 | 'id': 'spamfish', | |
330 | 'title': 'Spamfish', | |
331 | }, | |
332 | 'playlist_mincount': 54, | |
333 | } | |
240b9b7a S |
334 | |
335 | ||
c2e64f71 S |
336 | class TwitchBookmarksIE(TwitchPlaylistBaseIE): |
337 | IE_NAME = 'twitch:bookmarks' | |
338 | _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE | |
339 | _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE | |
340 | _PLAYLIST_TYPE = 'bookmarks' | |
341 | ||
342 | _TEST = { | |
343 | 'url': 'http://www.twitch.tv/ognos/profile/bookmarks', | |
344 | 'info_dict': { | |
345 | 'id': 'ognos', | |
346 | 'title': 'Ognos', | |
347 | }, | |
348 | 'playlist_mincount': 3, | |
349 | } | |
350 | ||
351 | def _extract_playlist_page(self, response): | |
352 | entries = [] | |
353 | for bookmark in response.get('bookmarks', []): | |
354 | video = bookmark.get('video') | |
355 | if not video: | |
356 | continue | |
357 | entries.append(video['url']) | |
358 | return entries | |
359 | ||
360 | ||
240b9b7a S |
361 | class TwitchStreamIE(TwitchBaseIE): |
362 | IE_NAME = 'twitch:stream' | |
faa1f83a | 363 | _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE |
240b9b7a | 364 | |
faa1f83a | 365 | _TESTS = [{ |
240b9b7a S |
366 | 'url': 'http://www.twitch.tv/shroomztv', |
367 | 'info_dict': { | |
368 | 'id': '12772022048', | |
369 | 'display_id': 'shroomztv', | |
370 | 'ext': 'mp4', | |
371 | 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$', | |
372 | 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV', | |
373 | 'is_live': True, | |
374 | 'timestamp': 1421928037, | |
375 | 'upload_date': '20150122', | |
376 | 'uploader': 'ShroomzTV', | |
377 | 'uploader_id': 'shroomztv', | |
378 | 'view_count': int, | |
379 | }, | |
380 | 'params': { | |
381 | # m3u8 download | |
382 | 'skip_download': True, | |
383 | }, | |
faa1f83a S |
384 | }, { |
385 | 'url': 'http://www.twitch.tv/miracle_doto#profile-0', | |
386 | 'only_matching': True, | |
387 | }] | |
240b9b7a S |
388 | |
389 | def _real_extract(self, url): | |
390 | channel_id = self._match_id(url) | |
391 | ||
392 | stream = self._download_json( | |
393 | '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id, | |
394 | 'Downloading stream JSON').get('stream') | |
395 | ||
396 | # Fallback on profile extraction if stream is offline | |
397 | if not stream: | |
398 | return self.url_result( | |
399 | 'http://www.twitch.tv/%s/profile' % channel_id, | |
400 | 'TwitchProfile', channel_id) | |
401 | ||
06966677 S |
402 | # Channel name may be typed if different case than the original channel name |
403 | # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing | |
404 | # an invalid m3u8 URL. Working around by use of original channel name from stream | |
405 | # JSON and fallback to lowercase if it's not available. | |
1793d71d S |
406 | channel_id = stream.get('channel', {}).get('name') or channel_id.lower() |
407 | ||
240b9b7a S |
408 | access_token = self._download_json( |
409 | '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id, | |
410 | 'Downloading channel access token') | |
411 | ||
412 | query = { | |
413 | 'allow_source': 'true', | |
f353cbdb | 414 | 'p': random.randint(1000000, 10000000), |
240b9b7a S |
415 | 'player': 'twitchweb', |
416 | 'segment_preference': '4', | |
d34e7949 S |
417 | 'sig': access_token['sig'].encode('utf-8'), |
418 | 'token': access_token['token'].encode('utf-8'), | |
240b9b7a | 419 | } |
240b9b7a S |
420 | formats = self._extract_m3u8_formats( |
421 | '%s/api/channel/hls/%s.m3u8?%s' | |
d34e7949 | 422 | % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)), |
240b9b7a | 423 | channel_id, 'mp4') |
d0e958c7 | 424 | self._prefer_source(formats) |
240b9b7a S |
425 | |
426 | view_count = stream.get('viewers') | |
427 | timestamp = parse_iso8601(stream.get('created_at')) | |
428 | ||
429 | channel = stream['channel'] | |
430 | title = self._live_title(channel.get('display_name') or channel.get('name')) | |
431 | description = channel.get('status') | |
432 | ||
433 | thumbnails = [] | |
434 | for thumbnail_key, thumbnail_url in stream['preview'].items(): | |
435 | m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key) | |
436 | if not m: | |
437 | continue | |
438 | thumbnails.append({ | |
439 | 'url': thumbnail_url, | |
440 | 'width': int(m.group('width')), | |
441 | 'height': int(m.group('height')), | |
442 | }) | |
443 | ||
444 | return { | |
445 | 'id': compat_str(stream['_id']), | |
446 | 'display_id': channel_id, | |
447 | 'title': title, | |
448 | 'description': description, | |
449 | 'thumbnails': thumbnails, | |
450 | 'uploader': channel.get('display_name'), | |
451 | 'uploader_id': channel.get('name'), | |
452 | 'timestamp': timestamp, | |
453 | 'view_count': view_count, | |
454 | 'formats': formats, | |
455 | 'is_live': True, | |
12d1fb5a | 456 | } |