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