Always use PYTHON env var in Makefile
[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_str,
11     compat_urllib_parse,
12     compat_urllib_request,
13 )
14 from ..utils import (
15     ExtractorError,
16     parse_iso8601,
17 )
18
19
20 class TwitchBaseIE(InfoExtractor):
21     _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
22
23     _API_BASE = 'https://api.twitch.tv'
24     _USHER_BASE = 'http://usher.twitch.tv'
25     _LOGIN_URL = 'https://secure.twitch.tv/user/login'
26
27     def _handle_error(self, response):
28         if not isinstance(response, dict):
29             return
30         error = response.get('error')
31         if error:
32             raise ExtractorError(
33                 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
34                 expected=True)
35
36     def _download_json(self, url, video_id, note='Downloading JSON metadata'):
37         response = super(TwitchBaseIE, self)._download_json(url, video_id, note)
38         self._handle_error(response)
39         return response
40
41     def _real_initialize(self):
42         self._login()
43
44     def _login(self):
45         (username, password) = self._get_login_info()
46         if username is None:
47             return
48
49         login_page = self._download_webpage(
50             self._LOGIN_URL, None, 'Downloading login page')
51
52         authenticity_token = self._search_regex(
53             r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
54             login_page, 'authenticity token')
55
56         login_form = {
57             'utf8': '✓'.encode('utf-8'),
58             'authenticity_token': authenticity_token,
59             'redirect_on_login': '',
60             'embed_form': 'false',
61             'mp_source_action': '',
62             'follow': '',
63             'user[login]': username,
64             'user[password]': password,
65         }
66
67         request = compat_urllib_request.Request(
68             self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
69         request.add_header('Referer', self._LOGIN_URL)
70         response = self._download_webpage(
71             request, None, 'Logging in as %s' % username)
72
73         m = re.search(
74             r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
75         if m:
76             raise ExtractorError(
77                 'Unable to login: %s' % m.group('msg').strip(), expected=True)
78
79
80 class TwitchItemBaseIE(TwitchBaseIE):
81     def _download_info(self, item, item_id):
82         return self._extract_info(self._download_json(
83             '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
84             'Downloading %s info JSON' % self._ITEM_TYPE))
85
86     def _extract_media(self, item_id):
87         info = self._download_info(self._ITEM_SHORTCUT, item_id)
88         response = self._download_json(
89             '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
90             'Downloading %s playlist JSON' % self._ITEM_TYPE)
91         entries = []
92         chunks = response['chunks']
93         qualities = list(chunks.keys())
94         for num, fragment in enumerate(zip(*chunks.values()), start=1):
95             formats = []
96             for fmt_num, fragment_fmt in enumerate(fragment):
97                 format_id = qualities[fmt_num]
98                 fmt = {
99                     'url': fragment_fmt['url'],
100                     'format_id': format_id,
101                     'quality': 1 if format_id == 'live' else 0,
102                 }
103                 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
104                 if m:
105                     fmt['height'] = int(m.group('height'))
106                 formats.append(fmt)
107             self._sort_formats(formats)
108             entry = dict(info)
109             entry['id'] = '%s_%d' % (entry['id'], num)
110             entry['title'] = '%s part %d' % (entry['title'], num)
111             entry['formats'] = formats
112             entries.append(entry)
113         return self.playlist_result(entries, info['id'], info['title'])
114
115     def _extract_info(self, info):
116         return {
117             'id': info['_id'],
118             'title': info['title'],
119             'description': info['description'],
120             'duration': info['length'],
121             'thumbnail': info['preview'],
122             'uploader': info['channel']['display_name'],
123             'uploader_id': info['channel']['name'],
124             'timestamp': parse_iso8601(info['recorded_at']),
125             'view_count': info['views'],
126         }
127
128     def _real_extract(self, url):
129         return self._extract_media(self._match_id(url))
130
131
132 class TwitchVideoIE(TwitchItemBaseIE):
133     IE_NAME = 'twitch:video'
134     _VALID_URL = r'%s/[^/]+/b/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
135     _ITEM_TYPE = 'video'
136     _ITEM_SHORTCUT = 'a'
137
138     _TEST = {
139         'url': 'http://www.twitch.tv/riotgames/b/577357806',
140         'info_dict': {
141             'id': 'a577357806',
142             'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
143         },
144         'playlist_mincount': 12,
145     }
146
147
148 class TwitchChapterIE(TwitchItemBaseIE):
149     IE_NAME = 'twitch:chapter'
150     _VALID_URL = r'%s/[^/]+/c/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
151     _ITEM_TYPE = 'chapter'
152     _ITEM_SHORTCUT = 'c'
153
154     _TESTS = [{
155         'url': 'http://www.twitch.tv/acracingleague/c/5285812',
156         'info_dict': {
157             'id': 'c5285812',
158             'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
159         },
160         'playlist_mincount': 3,
161     }, {
162         'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
163         'only_matching': True,
164     }]
165
166
167 class TwitchVodIE(TwitchItemBaseIE):
168     IE_NAME = 'twitch:vod'
169     _VALID_URL = r'%s/[^/]+/v/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
170     _ITEM_TYPE = 'vod'
171     _ITEM_SHORTCUT = 'v'
172
173     _TEST = {
174         'url': 'http://www.twitch.tv/ksptv/v/3622000',
175         'info_dict': {
176             'id': 'v3622000',
177             'ext': 'mp4',
178             'title': '''KSPTV: Squadcast: "Everyone's on vacation so here's Dahud" Edition!''',
179             'thumbnail': 're:^https?://.*\.jpg$',
180             'duration': 6951,
181             'timestamp': 1419028564,
182             'upload_date': '20141219',
183             'uploader': 'KSPTV',
184             'uploader_id': 'ksptv',
185             'view_count': int,
186         },
187         'params': {
188             # m3u8 download
189             'skip_download': True,
190         },
191     }
192
193     def _real_extract(self, url):
194         item_id = self._match_id(url)
195         info = self._download_info(self._ITEM_SHORTCUT, item_id)
196         access_token = self._download_json(
197             '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
198             'Downloading %s access token' % self._ITEM_TYPE)
199         formats = self._extract_m3u8_formats(
200             '%s/vod/%s?nauth=%s&nauthsig=%s'
201             % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
202             item_id, 'mp4')
203         info['formats'] = formats
204         return info
205
206
207 class TwitchPlaylistBaseIE(TwitchBaseIE):
208     _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
209     _PAGE_LIMIT = 100
210
211     def _extract_playlist(self, channel_id):
212         info = self._download_json(
213             '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
214             channel_id, 'Downloading channel info JSON')
215         channel_name = info.get('display_name') or info.get('name')
216         entries = []
217         offset = 0
218         limit = self._PAGE_LIMIT
219         for counter in itertools.count(1):
220             response = self._download_json(
221                 self._PLAYLIST_URL % (channel_id, offset, limit),
222                 channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
223             page_entries = self._extract_playlist_page(response)
224             if not page_entries:
225                 break
226             entries.extend(page_entries)
227             offset += limit
228         return self.playlist_result(
229             [self.url_result(entry) for entry in set(entries)],
230             channel_id, channel_name)
231
232     def _extract_playlist_page(self, response):
233         videos = response.get('videos')
234         return [video['url'] for video in videos] if videos else []
235
236     def _real_extract(self, url):
237         return self._extract_playlist(self._match_id(url))
238
239
240 class TwitchProfileIE(TwitchPlaylistBaseIE):
241     IE_NAME = 'twitch:profile'
242     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
243     _PLAYLIST_TYPE = 'profile'
244
245     _TEST = {
246         'url': 'http://www.twitch.tv/vanillatv/profile',
247         'info_dict': {
248             'id': 'vanillatv',
249             'title': 'VanillaTV',
250         },
251         'playlist_mincount': 412,
252     }
253
254
255 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
256     IE_NAME = 'twitch:past_broadcasts'
257     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
258     _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
259     _PLAYLIST_TYPE = 'past broadcasts'
260
261     _TEST = {
262         'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
263         'info_dict': {
264             'id': 'spamfish',
265             'title': 'Spamfish',
266         },
267         'playlist_mincount': 54,
268     }
269
270
271 class TwitchBookmarksIE(TwitchPlaylistBaseIE):
272     IE_NAME = 'twitch:bookmarks'
273     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
274     _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
275     _PLAYLIST_TYPE = 'bookmarks'
276
277     _TEST = {
278         'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
279         'info_dict': {
280             'id': 'ognos',
281             'title': 'Ognos',
282         },
283         'playlist_mincount': 3,
284     }
285
286     def _extract_playlist_page(self, response):
287         entries = []
288         for bookmark in response.get('bookmarks', []):
289             video = bookmark.get('video')
290             if not video:
291                 continue
292             entries.append(video['url'])
293         return entries
294
295
296 class TwitchStreamIE(TwitchBaseIE):
297     IE_NAME = 'twitch:stream'
298     _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
299
300     _TEST = {
301         'url': 'http://www.twitch.tv/shroomztv',
302         'info_dict': {
303             'id': '12772022048',
304             'display_id': 'shroomztv',
305             'ext': 'mp4',
306             'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
307             'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
308             'is_live': True,
309             'timestamp': 1421928037,
310             'upload_date': '20150122',
311             'uploader': 'ShroomzTV',
312             'uploader_id': 'shroomztv',
313             'view_count': int,
314         },
315         'params': {
316             # m3u8 download
317             'skip_download': True,
318         },
319     }
320
321     def _real_extract(self, url):
322         channel_id = self._match_id(url)
323
324         stream = self._download_json(
325             '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
326             'Downloading stream JSON').get('stream')
327
328         # Fallback on profile extraction if stream is offline
329         if not stream:
330             return self.url_result(
331                 'http://www.twitch.tv/%s/profile' % channel_id,
332                 'TwitchProfile', channel_id)
333
334         access_token = self._download_json(
335             '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
336             'Downloading channel access token')
337
338         query = {
339             'allow_source': 'true',
340             'p': random.randint(1000000, 10000000),
341             'player': 'twitchweb',
342             'segment_preference': '4',
343             'sig': access_token['sig'],
344             'token': access_token['token'],
345         }
346
347         formats = self._extract_m3u8_formats(
348             '%s/api/channel/hls/%s.m3u8?%s'
349             % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query).encode('utf-8')),
350             channel_id, 'mp4')
351
352         view_count = stream.get('viewers')
353         timestamp = parse_iso8601(stream.get('created_at'))
354
355         channel = stream['channel']
356         title = self._live_title(channel.get('display_name') or channel.get('name'))
357         description = channel.get('status')
358
359         thumbnails = []
360         for thumbnail_key, thumbnail_url in stream['preview'].items():
361             m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
362             if not m:
363                 continue
364             thumbnails.append({
365                 'url': thumbnail_url,
366                 'width': int(m.group('width')),
367                 'height': int(m.group('height')),
368             })
369
370         return {
371             'id': compat_str(stream['_id']),
372             'display_id': channel_id,
373             'title': title,
374             'description': description,
375             'thumbnails': thumbnails,
376             'uploader': channel.get('display_name'),
377             'uploader_id': channel.get('name'),
378             'timestamp': timestamp,
379             'view_count': view_count,
380             'formats': formats,
381             'is_live': True,
382         }