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