Merge remote-tracking branch 'derrotebaron/master'
[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             videos = response['videos']
224             if not videos:
225                 break
226             entries.extend([self.url_result(video['url']) for video in videos])
227             offset += limit
228         return self.playlist_result(entries, channel_id, channel_name)
229
230     def _real_extract(self, url):
231         return self._extract_playlist(self._match_id(url))
232
233
234 class TwitchProfileIE(TwitchPlaylistBaseIE):
235     IE_NAME = 'twitch:profile'
236     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
237     _PLAYLIST_TYPE = 'profile'
238
239     _TEST = {
240         'url': 'http://www.twitch.tv/vanillatv/profile',
241         'info_dict': {
242             'id': 'vanillatv',
243             'title': 'VanillaTV',
244         },
245         'playlist_mincount': 412,
246     }
247
248
249 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
250     IE_NAME = 'twitch:past_broadcasts'
251     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
252     _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
253     _PLAYLIST_TYPE = 'past broadcasts'
254
255     _TEST = {
256         'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
257         'info_dict': {
258             'id': 'spamfish',
259             'title': 'Spamfish',
260         },
261         'playlist_mincount': 54,
262     }
263
264
265 class TwitchStreamIE(TwitchBaseIE):
266     IE_NAME = 'twitch:stream'
267     _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
268
269     _TEST = {
270         'url': 'http://www.twitch.tv/shroomztv',
271         'info_dict': {
272             'id': '12772022048',
273             'display_id': 'shroomztv',
274             'ext': 'mp4',
275             'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
276             'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
277             'is_live': True,
278             'timestamp': 1421928037,
279             'upload_date': '20150122',
280             'uploader': 'ShroomzTV',
281             'uploader_id': 'shroomztv',
282             'view_count': int,
283         },
284         'params': {
285             # m3u8 download
286             'skip_download': True,
287         },
288     }
289
290     def _real_extract(self, url):
291         channel_id = self._match_id(url)
292
293         stream = self._download_json(
294             '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
295             'Downloading stream JSON').get('stream')
296
297         # Fallback on profile extraction if stream is offline
298         if not stream:
299             return self.url_result(
300                 'http://www.twitch.tv/%s/profile' % channel_id,
301                 'TwitchProfile', channel_id)
302
303         access_token = self._download_json(
304             '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
305             'Downloading channel access token')
306
307         query = {
308             'allow_source': 'true',
309             'p': random.randint(1000000, 10000000),
310             'player': 'twitchweb',
311             'segment_preference': '4',
312             'sig': access_token['sig'],
313             'token': access_token['token'],
314         }
315
316         formats = self._extract_m3u8_formats(
317             '%s/api/channel/hls/%s.m3u8?%s'
318             % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query).encode('utf-8')),
319             channel_id, 'mp4')
320
321         view_count = stream.get('viewers')
322         timestamp = parse_iso8601(stream.get('created_at'))
323
324         channel = stream['channel']
325         title = self._live_title(channel.get('display_name') or channel.get('name'))
326         description = channel.get('status')
327
328         thumbnails = []
329         for thumbnail_key, thumbnail_url in stream['preview'].items():
330             m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
331             if not m:
332                 continue
333             thumbnails.append({
334                 'url': thumbnail_url,
335                 'width': int(m.group('width')),
336                 'height': int(m.group('height')),
337             })
338
339         return {
340             'id': compat_str(stream['_id']),
341             'display_id': channel_id,
342             'title': title,
343             'description': description,
344             'thumbnails': thumbnails,
345             'uploader': channel.get('display_name'),
346             'uploader_id': channel.get('name'),
347             'timestamp': timestamp,
348             'view_count': view_count,
349             'formats': formats,
350             'is_live': True,
351         }