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