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