Merge pull request #10819 from raleeper/adobepass
[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         'skip': 'HTTP Error 404: Not Found',
251     }]
252
253     def _real_extract(self, url):
254         item_id = self._match_id(url)
255
256         info = self._download_info(self._ITEM_SHORTCUT, item_id)
257         access_token = self._call_api(
258             'api/vods/%s/access_token' % item_id, item_id,
259             'Downloading %s access token' % self._ITEM_TYPE)
260
261         formats = self._extract_m3u8_formats(
262             '%s/vod/%s?%s' % (
263                 self._USHER_BASE, item_id,
264                 compat_urllib_parse_urlencode({
265                     'allow_source': 'true',
266                     'allow_audio_only': 'true',
267                     'allow_spectre': 'true',
268                     'player': 'twitchweb',
269                     'nauth': access_token['token'],
270                     'nauthsig': access_token['sig'],
271                 })),
272             item_id, 'mp4', entry_protocol='m3u8_native')
273
274         self._prefer_source(formats)
275         info['formats'] = formats
276
277         parsed_url = compat_urllib_parse_urlparse(url)
278         query = compat_parse_qs(parsed_url.query)
279         if 't' in query:
280             info['start_time'] = parse_duration(query['t'][0])
281
282         return info
283
284
285 class TwitchPlaylistBaseIE(TwitchBaseIE):
286     _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
287     _PAGE_LIMIT = 100
288
289     def _extract_playlist(self, channel_id):
290         info = self._call_api(
291             'kraken/channels/%s' % channel_id,
292             channel_id, 'Downloading channel info JSON')
293         channel_name = info.get('display_name') or info.get('name')
294         entries = []
295         offset = 0
296         limit = self._PAGE_LIMIT
297         broken_paging_detected = False
298         counter_override = None
299         for counter in itertools.count(1):
300             response = self._call_api(
301                 self._PLAYLIST_PATH % (channel_id, offset, limit),
302                 channel_id,
303                 'Downloading %s videos JSON page %s'
304                 % (self._PLAYLIST_TYPE, counter_override or counter))
305             page_entries = self._extract_playlist_page(response)
306             if not page_entries:
307                 break
308             total = int_or_none(response.get('_total'))
309             # Since the beginning of March 2016 twitch's paging mechanism
310             # is completely broken on the twitch side. It simply ignores
311             # a limit and returns the whole offset number of videos.
312             # Working around by just requesting all videos at once.
313             # Upd: pagination bug was fixed by twitch on 15.03.2016.
314             if not broken_paging_detected and total and len(page_entries) > limit:
315                 self.report_warning(
316                     'Twitch pagination is broken on twitch side, requesting all videos at once',
317                     channel_id)
318                 broken_paging_detected = True
319                 offset = total
320                 counter_override = '(all at once)'
321                 continue
322             entries.extend(page_entries)
323             if broken_paging_detected or total and len(page_entries) >= total:
324                 break
325             offset += limit
326         return self.playlist_result(
327             [self.url_result(entry) for entry in orderedSet(entries)],
328             channel_id, channel_name)
329
330     def _extract_playlist_page(self, response):
331         videos = response.get('videos')
332         return [video['url'] for video in videos] if videos else []
333
334     def _real_extract(self, url):
335         return self._extract_playlist(self._match_id(url))
336
337
338 class TwitchProfileIE(TwitchPlaylistBaseIE):
339     IE_NAME = 'twitch:profile'
340     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
341     _PLAYLIST_TYPE = 'profile'
342
343     _TEST = {
344         'url': 'http://www.twitch.tv/vanillatv/profile',
345         'info_dict': {
346             'id': 'vanillatv',
347             'title': 'VanillaTV',
348         },
349         'playlist_mincount': 412,
350     }
351
352
353 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
354     IE_NAME = 'twitch:past_broadcasts'
355     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
356     _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcasts=true'
357     _PLAYLIST_TYPE = 'past broadcasts'
358
359     _TEST = {
360         'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
361         'info_dict': {
362             'id': 'spamfish',
363             'title': 'Spamfish',
364         },
365         'playlist_mincount': 54,
366     }
367
368
369 class TwitchStreamIE(TwitchBaseIE):
370     IE_NAME = 'twitch:stream'
371     _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
372
373     _TESTS = [{
374         'url': 'http://www.twitch.tv/shroomztv',
375         'info_dict': {
376             'id': '12772022048',
377             'display_id': 'shroomztv',
378             'ext': 'mp4',
379             'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
380             'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
381             'is_live': True,
382             'timestamp': 1421928037,
383             'upload_date': '20150122',
384             'uploader': 'ShroomzTV',
385             'uploader_id': 'shroomztv',
386             'view_count': int,
387         },
388         'params': {
389             # m3u8 download
390             'skip_download': True,
391         },
392     }, {
393         'url': 'http://www.twitch.tv/miracle_doto#profile-0',
394         'only_matching': True,
395     }]
396
397     def _real_extract(self, url):
398         channel_id = self._match_id(url)
399
400         stream = self._call_api(
401             'kraken/streams/%s' % channel_id, channel_id,
402             'Downloading stream JSON').get('stream')
403
404         if not stream:
405             raise ExtractorError('%s is offline' % channel_id, expected=True)
406
407         # Channel name may be typed if different case than the original channel name
408         # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
409         # an invalid m3u8 URL. Working around by use of original channel name from stream
410         # JSON and fallback to lowercase if it's not available.
411         channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
412
413         access_token = self._call_api(
414             'api/channels/%s/access_token' % channel_id, channel_id,
415             'Downloading channel access token')
416
417         query = {
418             'allow_source': 'true',
419             'allow_audio_only': 'true',
420             'p': random.randint(1000000, 10000000),
421             'player': 'twitchweb',
422             'segment_preference': '4',
423             'sig': access_token['sig'].encode('utf-8'),
424             'token': access_token['token'].encode('utf-8'),
425         }
426         formats = self._extract_m3u8_formats(
427             '%s/api/channel/hls/%s.m3u8?%s'
428             % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
429             channel_id, 'mp4')
430         self._prefer_source(formats)
431
432         view_count = stream.get('viewers')
433         timestamp = parse_iso8601(stream.get('created_at'))
434
435         channel = stream['channel']
436         title = self._live_title(channel.get('display_name') or channel.get('name'))
437         description = channel.get('status')
438
439         thumbnails = []
440         for thumbnail_key, thumbnail_url in stream['preview'].items():
441             m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
442             if not m:
443                 continue
444             thumbnails.append({
445                 'url': thumbnail_url,
446                 'width': int(m.group('width')),
447                 'height': int(m.group('height')),
448             })
449
450         return {
451             'id': compat_str(stream['_id']),
452             'display_id': channel_id,
453             'title': title,
454             'description': description,
455             'thumbnails': thumbnails,
456             'uploader': channel.get('display_name'),
457             'uploader_id': channel.get('name'),
458             'timestamp': timestamp,
459             'view_count': view_count,
460             'formats': formats,
461             'is_live': True,
462         }
463
464
465 class TwitchClipsIE(InfoExtractor):
466     IE_NAME = 'twitch:clips'
467     _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
468
469     _TESTS = [{
470         'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
471         'md5': '761769e1eafce0ffebfb4089cb3847cd',
472         'info_dict': {
473             'id': 'AggressiveCobraPoooound',
474             'ext': 'mp4',
475             'title': 'EA Play 2016 Live from the Novo Theatre',
476             'thumbnail': 're:^https?://.*\.jpg',
477             'creator': 'EA',
478             'uploader': 'stereotype_',
479             'uploader_id': 'stereotype_',
480         },
481     }, {
482         # multiple formats
483         'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
484         'only_matching': True,
485     }]
486
487     def _real_extract(self, url):
488         video_id = self._match_id(url)
489
490         webpage = self._download_webpage(url, video_id)
491
492         clip = self._parse_json(
493             self._search_regex(
494                 r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
495             video_id, transform_source=js_to_json)
496
497         title = clip.get('channel_title') or self._og_search_title(webpage)
498
499         formats = [{
500             'url': option['source'],
501             'format_id': option.get('quality'),
502             'height': int_or_none(option.get('quality')),
503         } for option in clip.get('quality_options', []) if option.get('source')]
504
505         if not formats:
506             formats = [{
507                 'url': clip['clip_video_url'],
508             }]
509
510         self._sort_formats(formats)
511
512         return {
513             'id': video_id,
514             'title': title,
515             'thumbnail': self._og_search_thumbnail(webpage),
516             'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
517             'uploader': clip.get('curator_login'),
518             'uploader_id': clip.get('curator_display_name'),
519             'formats': formats,
520         }