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'
26 _NETRC_MACHINE = 'twitch'
28 def _handle_error(self, response):
29 if not isinstance(response, dict):
31 error = response.get('error')
34 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
37 def _download_json(self, url, video_id, note='Downloading JSON metadata'):
39 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
40 'X-Requested-With': 'XMLHttpRequest',
42 for cookie in self._downloader.cookiejar:
43 if cookie.name == 'api_token':
44 headers['Twitch-Api-Token'] = cookie.value
45 request = compat_urllib_request.Request(url, headers=headers)
46 response = super(TwitchBaseIE, self)._download_json(request, video_id, note)
47 self._handle_error(response)
50 def _real_initialize(self):
54 (username, password) = self._get_login_info()
58 login_page = self._download_webpage(
59 self._LOGIN_URL, None, 'Downloading login page')
61 authenticity_token = self._search_regex(
62 r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
63 login_page, 'authenticity token')
66 'utf8': '✓'.encode('utf-8'),
67 'authenticity_token': authenticity_token,
68 'redirect_on_login': '',
69 'embed_form': 'false',
70 'mp_source_action': '',
72 'user[login]': username,
73 'user[password]': password,
76 request = compat_urllib_request.Request(
77 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
78 request.add_header('Referer', self._LOGIN_URL)
79 response = self._download_webpage(
80 request, None, 'Logging in as %s' % username)
83 r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
86 'Unable to login: %s' % m.group('msg').strip(), expected=True)
88 def _prefer_source(self, formats):
90 source = next(f for f in formats if f['format_id'] == 'Source')
91 source['preference'] = 10
93 pass # No Source stream present
94 self._sort_formats(formats)
97 class TwitchItemBaseIE(TwitchBaseIE):
98 def _download_info(self, item, item_id):
99 return self._extract_info(self._download_json(
100 '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
101 'Downloading %s info JSON' % self._ITEM_TYPE))
103 def _extract_media(self, item_id):
104 info = self._download_info(self._ITEM_SHORTCUT, item_id)
105 response = self._download_json(
106 '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
107 'Downloading %s playlist JSON' % self._ITEM_TYPE)
109 chunks = response['chunks']
110 qualities = list(chunks.keys())
111 for num, fragment in enumerate(zip(*chunks.values()), start=1):
113 for fmt_num, fragment_fmt in enumerate(fragment):
114 format_id = qualities[fmt_num]
116 'url': fragment_fmt['url'],
117 'format_id': format_id,
118 'quality': 1 if format_id == 'live' else 0,
120 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
122 fmt['height'] = int(m.group('height'))
124 self._sort_formats(formats)
126 entry['id'] = '%s_%d' % (entry['id'], num)
127 entry['title'] = '%s part %d' % (entry['title'], num)
128 entry['formats'] = formats
129 entries.append(entry)
130 return self.playlist_result(entries, info['id'], info['title'])
132 def _extract_info(self, info):
135 'title': info['title'],
136 'description': info['description'],
137 'duration': info['length'],
138 'thumbnail': info['preview'],
139 'uploader': info['channel']['display_name'],
140 'uploader_id': info['channel']['name'],
141 'timestamp': parse_iso8601(info['recorded_at']),
142 'view_count': info['views'],
145 def _real_extract(self, url):
146 return self._extract_media(self._match_id(url))
149 class TwitchVideoIE(TwitchItemBaseIE):
150 IE_NAME = 'twitch:video'
151 _VALID_URL = r'%s/[^/]+/b/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
156 'url': 'http://www.twitch.tv/riotgames/b/577357806',
159 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
161 'playlist_mincount': 12,
165 class TwitchChapterIE(TwitchItemBaseIE):
166 IE_NAME = 'twitch:chapter'
167 _VALID_URL = r'%s/[^/]+/c/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
168 _ITEM_TYPE = 'chapter'
172 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
175 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
177 'playlist_mincount': 3,
179 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
180 'only_matching': True,
184 class TwitchVodIE(TwitchItemBaseIE):
185 IE_NAME = 'twitch:vod'
186 _VALID_URL = r'%s/[^/]+/v/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
191 'url': 'http://www.twitch.tv/ksptv/v/3622000',
195 'title': '''KSPTV: Squadcast: "Everyone's on vacation so here's Dahud" Edition!''',
196 'thumbnail': 're:^https?://.*\.jpg$',
198 'timestamp': 1419028564,
199 'upload_date': '20141219',
201 'uploader_id': 'ksptv',
206 'skip_download': True,
210 def _real_extract(self, url):
211 item_id = self._match_id(url)
212 info = self._download_info(self._ITEM_SHORTCUT, item_id)
213 access_token = self._download_json(
214 '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
215 'Downloading %s access token' % self._ITEM_TYPE)
216 formats = self._extract_m3u8_formats(
217 '%s/vod/%s?nauth=%s&nauthsig=%s'
218 % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
220 self._prefer_source(formats)
221 info['formats'] = formats
225 class TwitchPlaylistBaseIE(TwitchBaseIE):
226 _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
229 def _extract_playlist(self, channel_id):
230 info = self._download_json(
231 '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
232 channel_id, 'Downloading channel info JSON')
233 channel_name = info.get('display_name') or info.get('name')
236 limit = self._PAGE_LIMIT
237 for counter in itertools.count(1):
238 response = self._download_json(
239 self._PLAYLIST_URL % (channel_id, offset, limit),
240 channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
241 page_entries = self._extract_playlist_page(response)
244 entries.extend(page_entries)
246 return self.playlist_result(
247 [self.url_result(entry) for entry in set(entries)],
248 channel_id, channel_name)
250 def _extract_playlist_page(self, response):
251 videos = response.get('videos')
252 return [video['url'] for video in videos] if videos else []
254 def _real_extract(self, url):
255 return self._extract_playlist(self._match_id(url))
258 class TwitchProfileIE(TwitchPlaylistBaseIE):
259 IE_NAME = 'twitch:profile'
260 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
261 _PLAYLIST_TYPE = 'profile'
264 'url': 'http://www.twitch.tv/vanillatv/profile',
267 'title': 'VanillaTV',
269 'playlist_mincount': 412,
273 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
274 IE_NAME = 'twitch:past_broadcasts'
275 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
276 _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
277 _PLAYLIST_TYPE = 'past broadcasts'
280 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
285 'playlist_mincount': 54,
289 class TwitchBookmarksIE(TwitchPlaylistBaseIE):
290 IE_NAME = 'twitch:bookmarks'
291 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
292 _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
293 _PLAYLIST_TYPE = 'bookmarks'
296 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
301 'playlist_mincount': 3,
304 def _extract_playlist_page(self, response):
306 for bookmark in response.get('bookmarks', []):
307 video = bookmark.get('video')
310 entries.append(video['url'])
314 class TwitchStreamIE(TwitchBaseIE):
315 IE_NAME = 'twitch:stream'
316 _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
319 'url': 'http://www.twitch.tv/shroomztv',
322 'display_id': 'shroomztv',
324 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
325 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
327 'timestamp': 1421928037,
328 'upload_date': '20150122',
329 'uploader': 'ShroomzTV',
330 'uploader_id': 'shroomztv',
335 'skip_download': True,
339 def _real_extract(self, url):
340 channel_id = self._match_id(url)
342 stream = self._download_json(
343 '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
344 'Downloading stream JSON').get('stream')
346 # Fallback on profile extraction if stream is offline
348 return self.url_result(
349 'http://www.twitch.tv/%s/profile' % channel_id,
350 'TwitchProfile', channel_id)
352 access_token = self._download_json(
353 '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
354 'Downloading channel access token')
357 'allow_source': 'true',
358 'p': random.randint(1000000, 10000000),
359 'player': 'twitchweb',
360 'segment_preference': '4',
361 'sig': access_token['sig'].encode('utf-8'),
362 'token': access_token['token'].encode('utf-8'),
364 formats = self._extract_m3u8_formats(
365 '%s/api/channel/hls/%s.m3u8?%s'
366 % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)),
368 self._prefer_source(formats)
370 view_count = stream.get('viewers')
371 timestamp = parse_iso8601(stream.get('created_at'))
373 channel = stream['channel']
374 title = self._live_title(channel.get('display_name') or channel.get('name'))
375 description = channel.get('status')
378 for thumbnail_key, thumbnail_url in stream['preview'].items():
379 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
383 'url': thumbnail_url,
384 'width': int(m.group('width')),
385 'height': int(m.group('height')),
389 'id': compat_str(stream['_id']),
390 'display_id': channel_id,
392 'description': description,
393 'thumbnails': thumbnails,
394 'uploader': channel.get('display_name'),
395 'uploader_id': channel.get('name'),
396 'timestamp': timestamp,
397 'view_count': view_count,