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