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