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