]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/twitch.py
bbba394b0ede953f60c179970c8b41d4013f69c2
[youtubedl] / youtube_dl / extractor / twitch.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import re
6 import random
7
8 from .common import InfoExtractor
9 from ..compat import (
10 compat_HTTPError,
11 compat_parse_qs,
12 compat_str,
13 compat_urllib_parse_urlencode,
14 compat_urllib_parse_urlparse,
15 compat_urlparse,
16 )
17 from ..utils import (
18 clean_html,
19 ExtractorError,
20 int_or_none,
21 js_to_json,
22 orderedSet,
23 parse_duration,
24 parse_iso8601,
25 update_url_query,
26 urlencode_postdata,
27 )
28
29
30 class TwitchBaseIE(InfoExtractor):
31 _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
32
33 _API_BASE = 'https://api.twitch.tv'
34 _USHER_BASE = 'https://usher.ttvnw.net'
35 _LOGIN_URL = 'http://www.twitch.tv/login'
36 _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6'
37 _NETRC_MACHINE = 'twitch'
38
39 def _handle_error(self, response):
40 if not isinstance(response, dict):
41 return
42 error = response.get('error')
43 if error:
44 raise ExtractorError(
45 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
46 expected=True)
47
48 def _call_api(self, path, item_id, note):
49 response = self._download_json(
50 '%s/%s' % (self._API_BASE, path), item_id, note,
51 headers={'Client-ID': self._CLIENT_ID})
52 self._handle_error(response)
53 return response
54
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 def fail(message):
64 raise ExtractorError(
65 'Unable to login. Twitch said: %s' % message, expected=True)
66
67 login_page, handle = self._download_webpage_handle(
68 self._LOGIN_URL, None, 'Downloading login page')
69
70 # Some TOR nodes and public proxies are blocked completely
71 if 'blacklist_message' in login_page:
72 fail(clean_html(login_page))
73
74 login_form = self._hidden_inputs(login_page)
75
76 login_form.update({
77 'username': username,
78 'password': password,
79 })
80
81 redirect_url = handle.geturl()
82
83 post_url = self._search_regex(
84 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
85 'post url', default=redirect_url, group='url')
86
87 if not post_url.startswith('http'):
88 post_url = compat_urlparse.urljoin(redirect_url, post_url)
89
90 headers = {'Referer': redirect_url}
91
92 try:
93 response = self._download_json(
94 post_url, None, 'Logging in as %s' % username,
95 data=urlencode_postdata(login_form),
96 headers=headers)
97 except ExtractorError as e:
98 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
99 response = self._parse_json(
100 e.cause.read().decode('utf-8'), None)
101 fail(response['message'])
102 raise
103
104 if response.get('redirect'):
105 self._download_webpage(
106 response['redirect'], None, 'Downloading login redirect page',
107 headers=headers)
108
109 def _prefer_source(self, formats):
110 try:
111 source = next(f for f in formats if f['format_id'] == 'Source')
112 source['preference'] = 10
113 except StopIteration:
114 pass # No Source stream present
115 self._sort_formats(formats)
116
117
118 class TwitchItemBaseIE(TwitchBaseIE):
119 def _download_info(self, item, item_id):
120 return self._extract_info(self._call_api(
121 'kraken/videos/%s%s' % (item, item_id), item_id,
122 'Downloading %s info JSON' % self._ITEM_TYPE))
123
124 def _extract_media(self, item_id):
125 info = self._download_info(self._ITEM_SHORTCUT, item_id)
126 response = self._call_api(
127 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
128 'Downloading %s playlist JSON' % self._ITEM_TYPE)
129 entries = []
130 chunks = response['chunks']
131 qualities = list(chunks.keys())
132 for num, fragment in enumerate(zip(*chunks.values()), start=1):
133 formats = []
134 for fmt_num, fragment_fmt in enumerate(fragment):
135 format_id = qualities[fmt_num]
136 fmt = {
137 'url': fragment_fmt['url'],
138 'format_id': format_id,
139 'quality': 1 if format_id == 'live' else 0,
140 }
141 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
142 if m:
143 fmt['height'] = int(m.group('height'))
144 formats.append(fmt)
145 self._sort_formats(formats)
146 entry = dict(info)
147 entry['id'] = '%s_%d' % (entry['id'], num)
148 entry['title'] = '%s part %d' % (entry['title'], num)
149 entry['formats'] = formats
150 entries.append(entry)
151 return self.playlist_result(entries, info['id'], info['title'])
152
153 def _extract_info(self, info):
154 return {
155 'id': info['_id'],
156 'title': info.get('title') or 'Untitled Broadcast',
157 'description': info.get('description'),
158 'duration': int_or_none(info.get('length')),
159 'thumbnail': info.get('preview'),
160 'uploader': info.get('channel', {}).get('display_name'),
161 'uploader_id': info.get('channel', {}).get('name'),
162 'timestamp': parse_iso8601(info.get('recorded_at')),
163 'view_count': int_or_none(info.get('views')),
164 }
165
166 def _real_extract(self, url):
167 return self._extract_media(self._match_id(url))
168
169
170 class TwitchVideoIE(TwitchItemBaseIE):
171 IE_NAME = 'twitch:video'
172 _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
173 _ITEM_TYPE = 'video'
174 _ITEM_SHORTCUT = 'a'
175
176 _TEST = {
177 'url': 'http://www.twitch.tv/riotgames/b/577357806',
178 'info_dict': {
179 'id': 'a577357806',
180 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
181 },
182 'playlist_mincount': 12,
183 'skip': 'HTTP Error 404: Not Found',
184 }
185
186
187 class TwitchChapterIE(TwitchItemBaseIE):
188 IE_NAME = 'twitch:chapter'
189 _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
190 _ITEM_TYPE = 'chapter'
191 _ITEM_SHORTCUT = 'c'
192
193 _TESTS = [{
194 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
195 'info_dict': {
196 'id': 'c5285812',
197 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
198 },
199 'playlist_mincount': 3,
200 'skip': 'HTTP Error 404: Not Found',
201 }, {
202 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
203 'only_matching': True,
204 }]
205
206
207 class TwitchVodIE(TwitchItemBaseIE):
208 IE_NAME = 'twitch:vod'
209 _VALID_URL = r'''(?x)
210 https?://
211 (?:
212 (?:www\.)?twitch\.tv/(?:[^/]+/v|videos)/|
213 player\.twitch\.tv/\?.*?\bvideo=v
214 )
215 (?P<id>\d+)
216 '''
217 _ITEM_TYPE = 'vod'
218 _ITEM_SHORTCUT = 'v'
219
220 _TESTS = [{
221 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
222 'info_dict': {
223 'id': 'v6528877',
224 'ext': 'mp4',
225 'title': 'LCK Summer Split - Week 6 Day 1',
226 'thumbnail': r're:^https?://.*\.jpg$',
227 'duration': 17208,
228 'timestamp': 1435131709,
229 'upload_date': '20150624',
230 'uploader': 'Riot Games',
231 'uploader_id': 'riotgames',
232 'view_count': int,
233 'start_time': 310,
234 },
235 'params': {
236 # m3u8 download
237 'skip_download': True,
238 },
239 }, {
240 # Untitled broadcast (title is None)
241 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
242 'info_dict': {
243 'id': 'v11230755',
244 'ext': 'mp4',
245 'title': 'Untitled Broadcast',
246 'thumbnail': r're:^https?://.*\.jpg$',
247 'duration': 1638,
248 'timestamp': 1439746708,
249 'upload_date': '20150816',
250 'uploader': 'BelkAO_o',
251 'uploader_id': 'belkao_o',
252 'view_count': int,
253 },
254 'params': {
255 # m3u8 download
256 'skip_download': True,
257 },
258 'skip': 'HTTP Error 404: Not Found',
259 }, {
260 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
261 'only_matching': True,
262 }, {
263 'url': 'https://www.twitch.tv/videos/6528877',
264 'only_matching': True,
265 }]
266
267 def _real_extract(self, url):
268 item_id = self._match_id(url)
269
270 info = self._download_info(self._ITEM_SHORTCUT, item_id)
271 access_token = self._call_api(
272 'api/vods/%s/access_token' % item_id, item_id,
273 'Downloading %s access token' % self._ITEM_TYPE)
274
275 formats = self._extract_m3u8_formats(
276 '%s/vod/%s?%s' % (
277 self._USHER_BASE, item_id,
278 compat_urllib_parse_urlencode({
279 'allow_source': 'true',
280 'allow_audio_only': 'true',
281 'allow_spectre': 'true',
282 'player': 'twitchweb',
283 'nauth': access_token['token'],
284 'nauthsig': access_token['sig'],
285 })),
286 item_id, 'mp4', entry_protocol='m3u8_native')
287
288 self._prefer_source(formats)
289 info['formats'] = formats
290
291 parsed_url = compat_urllib_parse_urlparse(url)
292 query = compat_parse_qs(parsed_url.query)
293 if 't' in query:
294 info['start_time'] = parse_duration(query['t'][0])
295
296 if info.get('timestamp') is not None:
297 info['subtitles'] = {
298 'rechat': [{
299 'url': update_url_query(
300 'https://rechat.twitch.tv/rechat-messages', {
301 'video_id': 'v%s' % item_id,
302 'start': info['timestamp'],
303 }),
304 'ext': 'json',
305 }],
306 }
307
308 return info
309
310
311 class TwitchPlaylistBaseIE(TwitchBaseIE):
312 _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
313 _PAGE_LIMIT = 100
314
315 def _extract_playlist(self, channel_id):
316 info = self._call_api(
317 'kraken/channels/%s' % channel_id,
318 channel_id, 'Downloading channel info JSON')
319 channel_name = info.get('display_name') or info.get('name')
320 entries = []
321 offset = 0
322 limit = self._PAGE_LIMIT
323 broken_paging_detected = False
324 counter_override = None
325 for counter in itertools.count(1):
326 response = self._call_api(
327 self._PLAYLIST_PATH % (channel_id, offset, limit),
328 channel_id,
329 'Downloading %s JSON page %s'
330 % (self._PLAYLIST_TYPE, counter_override or counter))
331 page_entries = self._extract_playlist_page(response)
332 if not page_entries:
333 break
334 total = int_or_none(response.get('_total'))
335 # Since the beginning of March 2016 twitch's paging mechanism
336 # is completely broken on the twitch side. It simply ignores
337 # a limit and returns the whole offset number of videos.
338 # Working around by just requesting all videos at once.
339 # Upd: pagination bug was fixed by twitch on 15.03.2016.
340 if not broken_paging_detected and total and len(page_entries) > limit:
341 self.report_warning(
342 'Twitch pagination is broken on twitch side, requesting all videos at once',
343 channel_id)
344 broken_paging_detected = True
345 offset = total
346 counter_override = '(all at once)'
347 continue
348 entries.extend(page_entries)
349 if broken_paging_detected or total and len(page_entries) >= total:
350 break
351 offset += limit
352 return self.playlist_result(
353 [self.url_result(entry) for entry in orderedSet(entries)],
354 channel_id, channel_name)
355
356 def _extract_playlist_page(self, response):
357 videos = response.get('videos')
358 return [video['url'] for video in videos] if videos else []
359
360 def _real_extract(self, url):
361 return self._extract_playlist(self._match_id(url))
362
363
364 class TwitchProfileIE(TwitchPlaylistBaseIE):
365 IE_NAME = 'twitch:profile'
366 _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
367 _PLAYLIST_TYPE = 'profile'
368
369 _TEST = {
370 'url': 'http://www.twitch.tv/vanillatv/profile',
371 'info_dict': {
372 'id': 'vanillatv',
373 'title': 'VanillaTV',
374 },
375 'playlist_mincount': 412,
376 }
377
378
379 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
380 _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
381 _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
382
383
384 class TwitchAllVideosIE(TwitchVideosBaseIE):
385 IE_NAME = 'twitch:videos:all'
386 _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
387 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
388 _PLAYLIST_TYPE = 'all videos'
389
390 _TEST = {
391 'url': 'https://www.twitch.tv/spamfish/videos/all',
392 'info_dict': {
393 'id': 'spamfish',
394 'title': 'Spamfish',
395 },
396 'playlist_mincount': 869,
397 }
398
399
400 class TwitchUploadsIE(TwitchVideosBaseIE):
401 IE_NAME = 'twitch:videos:uploads'
402 _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
403 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
404 _PLAYLIST_TYPE = 'uploads'
405
406 _TEST = {
407 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
408 'info_dict': {
409 'id': 'spamfish',
410 'title': 'Spamfish',
411 },
412 'playlist_mincount': 0,
413 }
414
415
416 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
417 IE_NAME = 'twitch:videos:past-broadcasts'
418 _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
419 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
420 _PLAYLIST_TYPE = 'past broadcasts'
421
422 _TEST = {
423 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
424 'info_dict': {
425 'id': 'spamfish',
426 'title': 'Spamfish',
427 },
428 'playlist_mincount': 0,
429 }
430
431
432 class TwitchHighlightsIE(TwitchVideosBaseIE):
433 IE_NAME = 'twitch:videos:highlights'
434 _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
435 _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
436 _PLAYLIST_TYPE = 'highlights'
437
438 _TEST = {
439 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
440 'info_dict': {
441 'id': 'spamfish',
442 'title': 'Spamfish',
443 },
444 'playlist_mincount': 805,
445 }
446
447
448 class TwitchStreamIE(TwitchBaseIE):
449 IE_NAME = 'twitch:stream'
450 _VALID_URL = r'''(?x)
451 https?://
452 (?:
453 (?:www\.)?twitch\.tv/|
454 player\.twitch\.tv/\?.*?\bchannel=
455 )
456 (?P<id>[^/#?]+)
457 '''
458
459 _TESTS = [{
460 'url': 'http://www.twitch.tv/shroomztv',
461 'info_dict': {
462 'id': '12772022048',
463 'display_id': 'shroomztv',
464 'ext': 'mp4',
465 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
466 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
467 'is_live': True,
468 'timestamp': 1421928037,
469 'upload_date': '20150122',
470 'uploader': 'ShroomzTV',
471 'uploader_id': 'shroomztv',
472 'view_count': int,
473 },
474 'params': {
475 # m3u8 download
476 'skip_download': True,
477 },
478 }, {
479 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
480 'only_matching': True,
481 }, {
482 'url': 'https://player.twitch.tv/?channel=lotsofs',
483 'only_matching': True,
484 }]
485
486 @classmethod
487 def suitable(cls, url):
488 return (False
489 if any(ie.suitable(url) for ie in (
490 TwitchVideoIE,
491 TwitchChapterIE,
492 TwitchVodIE,
493 TwitchProfileIE,
494 TwitchAllVideosIE,
495 TwitchUploadsIE,
496 TwitchPastBroadcastsIE,
497 TwitchHighlightsIE))
498 else super(TwitchStreamIE, cls).suitable(url))
499
500 def _real_extract(self, url):
501 channel_id = self._match_id(url)
502
503 stream = self._call_api(
504 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
505 'Downloading stream JSON').get('stream')
506
507 if not stream:
508 raise ExtractorError('%s is offline' % channel_id, expected=True)
509
510 # Channel name may be typed if different case than the original channel name
511 # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
512 # an invalid m3u8 URL. Working around by use of original channel name from stream
513 # JSON and fallback to lowercase if it's not available.
514 channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
515
516 access_token = self._call_api(
517 'api/channels/%s/access_token' % channel_id, channel_id,
518 'Downloading channel access token')
519
520 query = {
521 'allow_source': 'true',
522 'allow_audio_only': 'true',
523 'allow_spectre': 'true',
524 'p': random.randint(1000000, 10000000),
525 'player': 'twitchweb',
526 'segment_preference': '4',
527 'sig': access_token['sig'].encode('utf-8'),
528 'token': access_token['token'].encode('utf-8'),
529 }
530 formats = self._extract_m3u8_formats(
531 '%s/api/channel/hls/%s.m3u8?%s'
532 % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
533 channel_id, 'mp4')
534 self._prefer_source(formats)
535
536 view_count = stream.get('viewers')
537 timestamp = parse_iso8601(stream.get('created_at'))
538
539 channel = stream['channel']
540 title = self._live_title(channel.get('display_name') or channel.get('name'))
541 description = channel.get('status')
542
543 thumbnails = []
544 for thumbnail_key, thumbnail_url in stream['preview'].items():
545 m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
546 if not m:
547 continue
548 thumbnails.append({
549 'url': thumbnail_url,
550 'width': int(m.group('width')),
551 'height': int(m.group('height')),
552 })
553
554 return {
555 'id': compat_str(stream['_id']),
556 'display_id': channel_id,
557 'title': title,
558 'description': description,
559 'thumbnails': thumbnails,
560 'uploader': channel.get('display_name'),
561 'uploader_id': channel.get('name'),
562 'timestamp': timestamp,
563 'view_count': view_count,
564 'formats': formats,
565 'is_live': True,
566 }
567
568
569 class TwitchClipsIE(InfoExtractor):
570 IE_NAME = 'twitch:clips'
571 _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
572
573 _TESTS = [{
574 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
575 'md5': '761769e1eafce0ffebfb4089cb3847cd',
576 'info_dict': {
577 'id': 'AggressiveCobraPoooound',
578 'ext': 'mp4',
579 'title': 'EA Play 2016 Live from the Novo Theatre',
580 'thumbnail': r're:^https?://.*\.jpg',
581 'creator': 'EA',
582 'uploader': 'stereotype_',
583 'uploader_id': 'stereotype_',
584 },
585 }, {
586 # multiple formats
587 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
588 'only_matching': True,
589 }]
590
591 def _real_extract(self, url):
592 video_id = self._match_id(url)
593
594 webpage = self._download_webpage(url, video_id)
595
596 clip = self._parse_json(
597 self._search_regex(
598 r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
599 video_id, transform_source=js_to_json)
600
601 title = clip.get('channel_title') or self._og_search_title(webpage)
602
603 formats = [{
604 'url': option['source'],
605 'format_id': option.get('quality'),
606 'height': int_or_none(option.get('quality')),
607 } for option in clip.get('quality_options', []) if option.get('source')]
608
609 if not formats:
610 formats = [{
611 'url': clip['clip_video_url'],
612 }]
613
614 self._sort_formats(formats)
615
616 return {
617 'id': video_id,
618 'title': title,
619 'thumbnail': self._og_search_thumbnail(webpage),
620 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
621 'uploader': clip.get('curator_login'),
622 'uploader_id': clip.get('curator_display_name'),
623 'formats': formats,
624 }