]>
Commit | Line | Data |
---|---|---|
04d02a9d | 1 | # coding: utf-8 |
ee1e1996 PH |
2 | from __future__ import unicode_literals |
3 | ||
3182f3e2 | 4 | import itertools |
79e93125 | 5 | import re |
f353cbdb | 6 | import random |
48afc6ca | 7 | import json |
79e93125 PH |
8 | |
9 | from .common import InfoExtractor | |
1cc79574 | 10 | from ..compat import ( |
49fa7de3 | 11 | compat_kwargs, |
e704f87f | 12 | compat_parse_qs, |
240b9b7a | 13 | compat_str, |
15707c7e | 14 | compat_urllib_parse_urlencode, |
e704f87f | 15 | compat_urllib_parse_urlparse, |
1cc79574 PH |
16 | ) |
17 | from ..utils import ( | |
efe470e2 | 18 | clean_html, |
79e93125 | 19 | ExtractorError, |
7a6e8a1b | 20 | int_or_none, |
8bbb4b56 | 21 | orderedSet, |
e704f87f | 22 | parse_duration, |
355d074f | 23 | parse_iso8601, |
49fa7de3 S |
24 | try_get, |
25 | unified_timestamp, | |
264e77c4 | 26 | update_url_query, |
3052a30d | 27 | url_or_none, |
c64c03be | 28 | urljoin, |
79e93125 PH |
29 | ) |
30 | ||
31 | ||
c5db6bb3 | 32 | class TwitchBaseIE(InfoExtractor): |
fce79626 | 33 | _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv' |
c5db6bb3 | 34 | |
46fd0dd5 | 35 | _API_BASE = 'https://api.twitch.tv' |
9f4576a7 | 36 | _USHER_BASE = 'https://usher.ttvnw.net' |
48afc6ca TB |
37 | _LOGIN_FORM_URL = 'https://www.twitch.tv/login' |
38 | _LOGIN_POST_URL = 'https://passport.twitch.tv/login' | |
cb1c3a3c | 39 | _CLIENT_ID = 'kimne78kx3ncx6brgo4mv6wki5h1ko' |
499bfcbf | 40 | _NETRC_MACHINE = 'twitch' |
79e93125 | 41 | |
355d074f S |
42 | def _handle_error(self, response): |
43 | if not isinstance(response, dict): | |
44 | return | |
45 | error = response.get('error') | |
46 | if error: | |
47 | raise ExtractorError( | |
48 | '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')), | |
49 | expected=True) | |
50 | ||
49fa7de3 | 51 | def _call_api(self, path, item_id, *args, **kwargs): |
e2f61598 S |
52 | headers = kwargs.get('headers', {}).copy() |
53 | headers['Client-ID'] = self._CLIENT_ID | |
54 | kwargs['headers'] = headers | |
e3f6b569 | 55 | response = self._download_json( |
49fa7de3 S |
56 | '%s/%s' % (self._API_BASE, path), item_id, |
57 | *args, **compat_kwargs(kwargs)) | |
355d074f S |
58 | self._handle_error(response) |
59 | return response | |
60 | ||
c5db6bb3 S |
61 | def _real_initialize(self): |
62 | self._login() | |
63 | ||
64 | def _login(self): | |
68217024 | 65 | username, password = self._get_login_info() |
c5db6bb3 S |
66 | if username is None: |
67 | return | |
68 | ||
efe470e2 S |
69 | def fail(message): |
70 | raise ExtractorError( | |
71 | 'Unable to login. Twitch said: %s' % message, expected=True) | |
72 | ||
5316566e | 73 | def login_step(page, urlh, note, data): |
c64c03be XDG |
74 | form = self._hidden_inputs(page) |
75 | form.update(data) | |
76 | ||
77 | page_url = urlh.geturl() | |
78 | post_url = self._search_regex( | |
79 | r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page, | |
48afc6ca | 80 | 'post url', default=self._LOGIN_POST_URL, group='url') |
c64c03be XDG |
81 | post_url = urljoin(page_url, post_url) |
82 | ||
48afc6ca TB |
83 | headers = { |
84 | 'Referer': page_url, | |
85 | 'Origin': page_url, | |
cb1c3a3c | 86 | 'Content-Type': 'text/plain;charset=UTF-8', |
48afc6ca | 87 | } |
c64c03be | 88 | |
cb1c3a3c S |
89 | response = self._download_json( |
90 | post_url, None, note, data=json.dumps(form).encode(), | |
91 | headers=headers, expected_status=400) | |
92 | error = response.get('error_description') or response.get('error_code') | |
93 | if error: | |
94 | fail(error) | |
c64c03be | 95 | |
1370dba5 S |
96 | if 'Authenticated successfully' in response.get('message', ''): |
97 | return None, None | |
98 | ||
99 | redirect_url = urljoin( | |
100 | post_url, | |
101 | response.get('redirect') or response['redirect_path']) | |
5316566e S |
102 | return self._download_webpage_handle( |
103 | redirect_url, None, 'Downloading login redirect page', | |
104 | headers=headers) | |
c64c03be | 105 | |
fbd9f6ea | 106 | login_page, handle = self._download_webpage_handle( |
48afc6ca | 107 | self._LOGIN_FORM_URL, None, 'Downloading login page') |
c5db6bb3 | 108 | |
efe470e2 S |
109 | # Some TOR nodes and public proxies are blocked completely |
110 | if 'blacklist_message' in login_page: | |
111 | fail(clean_html(login_page)) | |
112 | ||
5316566e | 113 | redirect_page, handle = login_step( |
e4d95865 | 114 | login_page, handle, 'Logging in', { |
5316566e S |
115 | 'username': username, |
116 | 'password': password, | |
48afc6ca | 117 | 'client_id': self._CLIENT_ID, |
fe646a2f | 118 | }) |
c64c03be | 119 | |
1370dba5 S |
120 | # Successful login |
121 | if not redirect_page: | |
122 | return | |
123 | ||
c64c03be XDG |
124 | if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None: |
125 | # TODO: Add mechanism to request an SMS or phone call | |
126 | tfa_token = self._get_tfa_info('two-factor authentication token') | |
5316566e | 127 | login_step(redirect_page, handle, 'Submitting TFA token', { |
c64c03be XDG |
128 | 'authy_token': tfa_token, |
129 | 'remember_2fa': 'true', | |
5316566e | 130 | }) |
17b41a33 | 131 | |
d0e958c7 PH |
132 | def _prefer_source(self, formats): |
133 | try: | |
134 | source = next(f for f in formats if f['format_id'] == 'Source') | |
60e67c5b | 135 | source['quality'] = 10 |
d0e958c7 | 136 | except StopIteration: |
985637cb S |
137 | for f in formats: |
138 | if '/chunked/' in f['url']: | |
139 | f.update({ | |
60e67c5b | 140 | 'quality': 10, |
985637cb S |
141 | 'format_note': 'Source', |
142 | }) | |
d0e958c7 PH |
143 | self._sort_formats(formats) |
144 | ||
c5db6bb3 S |
145 | |
146 | class TwitchItemBaseIE(TwitchBaseIE): | |
147 | def _download_info(self, item, item_id): | |
e3f6b569 S |
148 | return self._extract_info(self._call_api( |
149 | 'kraken/videos/%s%s' % (item, item_id), item_id, | |
c5db6bb3 | 150 | 'Downloading %s info JSON' % self._ITEM_TYPE)) |
a22524b0 | 151 | |
c5db6bb3 S |
152 | def _extract_media(self, item_id): |
153 | info = self._download_info(self._ITEM_SHORTCUT, item_id) | |
e3f6b569 S |
154 | response = self._call_api( |
155 | 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id, | |
c5db6bb3 | 156 | 'Downloading %s playlist JSON' % self._ITEM_TYPE) |
355d074f S |
157 | entries = [] |
158 | chunks = response['chunks'] | |
159 | qualities = list(chunks.keys()) | |
160 | for num, fragment in enumerate(zip(*chunks.values()), start=1): | |
161 | formats = [] | |
162 | for fmt_num, fragment_fmt in enumerate(fragment): | |
163 | format_id = qualities[fmt_num] | |
164 | fmt = { | |
165 | 'url': fragment_fmt['url'], | |
166 | 'format_id': format_id, | |
167 | 'quality': 1 if format_id == 'live' else 0, | |
168 | } | |
169 | m = re.search(r'^(?P<height>\d+)[Pp]', format_id) | |
170 | if m: | |
171 | fmt['height'] = int(m.group('height')) | |
172 | formats.append(fmt) | |
173 | self._sort_formats(formats) | |
174 | entry = dict(info) | |
159444a6 | 175 | entry['id'] = '%s_%d' % (entry['id'], num) |
355d074f S |
176 | entry['title'] = '%s part %d' % (entry['title'], num) |
177 | entry['formats'] = formats | |
178 | entries.append(entry) | |
013bfdd8 | 179 | return self.playlist_result(entries, info['id'], info['title']) |
355d074f S |
180 | |
181 | def _extract_info(self, info): | |
0ff51ada S |
182 | status = info.get('status') |
183 | if status == 'recording': | |
184 | is_live = True | |
185 | elif status == 'recorded': | |
186 | is_live = False | |
187 | else: | |
188 | is_live = None | |
355d074f S |
189 | return { |
190 | 'id': info['_id'], | |
369c12e0 | 191 | 'title': info.get('title') or 'Untitled Broadcast', |
7a6e8a1b S |
192 | 'description': info.get('description'), |
193 | 'duration': int_or_none(info.get('length')), | |
194 | 'thumbnail': info.get('preview'), | |
195 | 'uploader': info.get('channel', {}).get('display_name'), | |
196 | 'uploader_id': info.get('channel', {}).get('name'), | |
197 | 'timestamp': parse_iso8601(info.get('recorded_at')), | |
198 | 'view_count': int_or_none(info.get('views')), | |
0ff51ada | 199 | 'is_live': is_live, |
355d074f S |
200 | } |
201 | ||
c5db6bb3 S |
202 | def _real_extract(self, url): |
203 | return self._extract_media(self._match_id(url)) | |
04d02a9d | 204 | |
04d02a9d | 205 | |
c5db6bb3 S |
206 | class TwitchVideoIE(TwitchItemBaseIE): |
207 | IE_NAME = 'twitch:video' | |
93f78707 | 208 | _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE |
c5db6bb3 S |
209 | _ITEM_TYPE = 'video' |
210 | _ITEM_SHORTCUT = 'a' | |
04d02a9d | 211 | |
c5db6bb3 S |
212 | _TEST = { |
213 | 'url': 'http://www.twitch.tv/riotgames/b/577357806', | |
214 | 'info_dict': { | |
215 | 'id': 'a577357806', | |
216 | 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG', | |
217 | }, | |
218 | 'playlist_mincount': 12, | |
0db3a661 | 219 | 'skip': 'HTTP Error 404: Not Found', |
c5db6bb3 | 220 | } |
04d02a9d | 221 | |
04d02a9d | 222 | |
c5db6bb3 S |
223 | class TwitchChapterIE(TwitchItemBaseIE): |
224 | IE_NAME = 'twitch:chapter' | |
93f78707 | 225 | _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE |
c5db6bb3 S |
226 | _ITEM_TYPE = 'chapter' |
227 | _ITEM_SHORTCUT = 'c' | |
04d02a9d | 228 | |
78111136 | 229 | _TESTS = [{ |
c5db6bb3 S |
230 | 'url': 'http://www.twitch.tv/acracingleague/c/5285812', |
231 | 'info_dict': { | |
232 | 'id': 'c5285812', | |
233 | 'title': 'ACRL Off Season - Sports Cars @ Nordschleife', | |
234 | }, | |
235 | 'playlist_mincount': 3, | |
0db3a661 | 236 | 'skip': 'HTTP Error 404: Not Found', |
78111136 PH |
237 | }, { |
238 | 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361', | |
239 | 'only_matching': True, | |
240 | }] | |
c5db6bb3 S |
241 | |
242 | ||
243 | class TwitchVodIE(TwitchItemBaseIE): | |
244 | IE_NAME = 'twitch:vod' | |
3f1ce168 S |
245 | _VALID_URL = r'''(?x) |
246 | https?:// | |
247 | (?: | |
644921b3 | 248 | (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/| |
bc48773e | 249 | player\.twitch\.tv/\?.*?\bvideo=v? |
3f1ce168 S |
250 | ) |
251 | (?P<id>\d+) | |
252 | ''' | |
c5db6bb3 S |
253 | _ITEM_TYPE = 'vod' |
254 | _ITEM_SHORTCUT = 'v' | |
255 | ||
9c724a98 | 256 | _TESTS = [{ |
e704f87f | 257 | 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s', |
c5db6bb3 | 258 | 'info_dict': { |
ac0474f8 | 259 | 'id': 'v6528877', |
c5db6bb3 | 260 | 'ext': 'mp4', |
ac0474f8 | 261 | 'title': 'LCK Summer Split - Week 6 Day 1', |
ec85ded8 | 262 | 'thumbnail': r're:^https?://.*\.jpg$', |
ac0474f8 YCH |
263 | 'duration': 17208, |
264 | 'timestamp': 1435131709, | |
265 | 'upload_date': '20150624', | |
266 | 'uploader': 'Riot Games', | |
267 | 'uploader_id': 'riotgames', | |
c5db6bb3 | 268 | 'view_count': int, |
e704f87f | 269 | 'start_time': 310, |
c5db6bb3 S |
270 | }, |
271 | 'params': { | |
272 | # m3u8 download | |
273 | 'skip_download': True, | |
274 | }, | |
9c724a98 S |
275 | }, { |
276 | # Untitled broadcast (title is None) | |
277 | 'url': 'http://www.twitch.tv/belkao_o/v/11230755', | |
278 | 'info_dict': { | |
279 | 'id': 'v11230755', | |
280 | 'ext': 'mp4', | |
281 | 'title': 'Untitled Broadcast', | |
ec85ded8 | 282 | 'thumbnail': r're:^https?://.*\.jpg$', |
9c724a98 S |
283 | 'duration': 1638, |
284 | 'timestamp': 1439746708, | |
285 | 'upload_date': '20150816', | |
286 | 'uploader': 'BelkAO_o', | |
287 | 'uploader_id': 'belkao_o', | |
288 | 'view_count': int, | |
289 | }, | |
290 | 'params': { | |
291 | # m3u8 download | |
292 | 'skip_download': True, | |
293 | }, | |
9bd7bd0b | 294 | 'skip': 'HTTP Error 404: Not Found', |
3f1ce168 S |
295 | }, { |
296 | 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877', | |
297 | 'only_matching': True, | |
0b23c222 S |
298 | }, { |
299 | 'url': 'https://www.twitch.tv/videos/6528877', | |
300 | 'only_matching': True, | |
fce79626 S |
301 | }, { |
302 | 'url': 'https://m.twitch.tv/beagsandjam/v/247478721', | |
303 | 'only_matching': True, | |
644921b3 S |
304 | }, { |
305 | 'url': 'https://www.twitch.tv/northernlion/video/291940395', | |
306 | 'only_matching': True, | |
bc48773e M |
307 | }, { |
308 | 'url': 'https://player.twitch.tv/?video=480452374', | |
309 | 'only_matching': True, | |
9c724a98 | 310 | }] |
04d02a9d | 311 | |
79e93125 | 312 | def _real_extract(self, url): |
c5db6bb3 | 313 | item_id = self._match_id(url) |
e5e99661 | 314 | |
c5db6bb3 | 315 | info = self._download_info(self._ITEM_SHORTCUT, item_id) |
e3f6b569 S |
316 | access_token = self._call_api( |
317 | 'api/vods/%s/access_token' % item_id, item_id, | |
350c9481 | 318 | 'Downloading %s access token' % self._ITEM_TYPE) |
e5e99661 | 319 | |
c5db6bb3 | 320 | formats = self._extract_m3u8_formats( |
2da4316e | 321 | '%s/vod/%s.m3u8?%s' % ( |
350c9481 | 322 | self._USHER_BASE, item_id, |
15707c7e | 323 | compat_urllib_parse_urlencode({ |
e5e99661 | 324 | 'allow_source': 'true', |
ac455055 | 325 | 'allow_audio_only': 'true', |
e5e99661 S |
326 | 'allow_spectre': 'true', |
327 | 'player': 'twitchweb', | |
1d31b7ca | 328 | 'playlist_include_framerate': 'true', |
e5e99661 S |
329 | 'nauth': access_token['token'], |
330 | 'nauthsig': access_token['sig'], | |
331 | })), | |
631d4c87 | 332 | item_id, 'mp4', entry_protocol='m3u8_native') |
e5e99661 | 333 | |
d0e958c7 | 334 | self._prefer_source(formats) |
c5db6bb3 | 335 | info['formats'] = formats |
e704f87f NH |
336 | |
337 | parsed_url = compat_urllib_parse_urlparse(url) | |
338 | query = compat_parse_qs(parsed_url.query) | |
339 | if 't' in query: | |
340 | info['start_time'] = parse_duration(query['t'][0]) | |
341 | ||
264e77c4 S |
342 | if info.get('timestamp') is not None: |
343 | info['subtitles'] = { | |
344 | 'rechat': [{ | |
345 | 'url': update_url_query( | |
ce112a8c RA |
346 | 'https://api.twitch.tv/v5/videos/%s/comments' % item_id, { |
347 | 'client_id': self._CLIENT_ID, | |
264e77c4 S |
348 | }), |
349 | 'ext': 'json', | |
350 | }], | |
351 | } | |
352 | ||
c5db6bb3 S |
353 | return info |
354 | ||
355 | ||
356 | class TwitchPlaylistBaseIE(TwitchBaseIE): | |
e3f6b569 | 357 | _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d' |
ececca6c | 358 | _PAGE_LIMIT = 100 |
c5db6bb3 S |
359 | |
360 | def _extract_playlist(self, channel_id): | |
e3f6b569 S |
361 | info = self._call_api( |
362 | 'kraken/channels/%s' % channel_id, | |
c5db6bb3 S |
363 | channel_id, 'Downloading channel info JSON') |
364 | channel_name = info.get('display_name') or info.get('name') | |
365 | entries = [] | |
366 | offset = 0 | |
367 | limit = self._PAGE_LIMIT | |
539a1641 S |
368 | broken_paging_detected = False |
369 | counter_override = None | |
c5db6bb3 | 370 | for counter in itertools.count(1): |
e3f6b569 S |
371 | response = self._call_api( |
372 | self._PLAYLIST_PATH % (channel_id, offset, limit), | |
539a1641 | 373 | channel_id, |
93753aad | 374 | 'Downloading %s JSON page %s' |
539a1641 | 375 | % (self._PLAYLIST_TYPE, counter_override or counter)) |
c2e64f71 S |
376 | page_entries = self._extract_playlist_page(response) |
377 | if not page_entries: | |
c5db6bb3 | 378 | break |
539a1641 S |
379 | total = int_or_none(response.get('_total')) |
380 | # Since the beginning of March 2016 twitch's paging mechanism | |
381 | # is completely broken on the twitch side. It simply ignores | |
382 | # a limit and returns the whole offset number of videos. | |
383 | # Working around by just requesting all videos at once. | |
dec2cae0 | 384 | # Upd: pagination bug was fixed by twitch on 15.03.2016. |
539a1641 S |
385 | if not broken_paging_detected and total and len(page_entries) > limit: |
386 | self.report_warning( | |
dec2cae0 | 387 | 'Twitch pagination is broken on twitch side, requesting all videos at once', |
539a1641 S |
388 | channel_id) |
389 | broken_paging_detected = True | |
a8276b26 | 390 | offset = total |
539a1641 S |
391 | counter_override = '(all at once)' |
392 | continue | |
c2e64f71 | 393 | entries.extend(page_entries) |
539a1641 S |
394 | if broken_paging_detected or total and len(page_entries) >= total: |
395 | break | |
c5db6bb3 | 396 | offset += limit |
c2e64f71 | 397 | return self.playlist_result( |
f0c6c2bc | 398 | [self._make_url_result(entry) for entry in orderedSet(entries)], |
c2e64f71 S |
399 | channel_id, channel_name) |
400 | ||
f0c6c2bc LR |
401 | def _make_url_result(self, url): |
402 | try: | |
403 | video_id = 'v%s' % TwitchVodIE._match_id(url) | |
404 | return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id) | |
405 | except AssertionError: | |
406 | return self.url_result(url) | |
407 | ||
c2e64f71 S |
408 | def _extract_playlist_page(self, response): |
409 | videos = response.get('videos') | |
410 | return [video['url'] for video in videos] if videos else [] | |
c5db6bb3 S |
411 | |
412 | def _real_extract(self, url): | |
413 | return self._extract_playlist(self._match_id(url)) | |
414 | ||
415 | ||
416 | class TwitchProfileIE(TwitchPlaylistBaseIE): | |
417 | IE_NAME = 'twitch:profile' | |
418 | _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE | |
419 | _PLAYLIST_TYPE = 'profile' | |
420 | ||
fce79626 | 421 | _TESTS = [{ |
c5db6bb3 S |
422 | 'url': 'http://www.twitch.tv/vanillatv/profile', |
423 | 'info_dict': { | |
424 | 'id': 'vanillatv', | |
425 | 'title': 'VanillaTV', | |
426 | }, | |
427 | 'playlist_mincount': 412, | |
fce79626 S |
428 | }, { |
429 | 'url': 'http://m.twitch.tv/vanillatv/profile', | |
430 | 'only_matching': True, | |
431 | }] | |
c5db6bb3 S |
432 | |
433 | ||
93753aad S |
434 | class TwitchVideosBaseIE(TwitchPlaylistBaseIE): |
435 | _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE | |
436 | _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type=' | |
437 | ||
438 | ||
439 | class TwitchAllVideosIE(TwitchVideosBaseIE): | |
440 | IE_NAME = 'twitch:videos:all' | |
441 | _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
442 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight' | |
443 | _PLAYLIST_TYPE = 'all videos' | |
444 | ||
fce79626 | 445 | _TESTS = [{ |
93753aad S |
446 | 'url': 'https://www.twitch.tv/spamfish/videos/all', |
447 | 'info_dict': { | |
448 | 'id': 'spamfish', | |
449 | 'title': 'Spamfish', | |
450 | }, | |
451 | 'playlist_mincount': 869, | |
fce79626 S |
452 | }, { |
453 | 'url': 'https://m.twitch.tv/spamfish/videos/all', | |
454 | 'only_matching': True, | |
455 | }] | |
93753aad S |
456 | |
457 | ||
458 | class TwitchUploadsIE(TwitchVideosBaseIE): | |
459 | IE_NAME = 'twitch:videos:uploads' | |
460 | _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
461 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload' | |
462 | _PLAYLIST_TYPE = 'uploads' | |
463 | ||
fce79626 | 464 | _TESTS = [{ |
93753aad S |
465 | 'url': 'https://www.twitch.tv/spamfish/videos/uploads', |
466 | 'info_dict': { | |
467 | 'id': 'spamfish', | |
468 | 'title': 'Spamfish', | |
469 | }, | |
470 | 'playlist_mincount': 0, | |
fce79626 S |
471 | }, { |
472 | 'url': 'https://m.twitch.tv/spamfish/videos/uploads', | |
473 | 'only_matching': True, | |
474 | }] | |
93753aad S |
475 | |
476 | ||
477 | class TwitchPastBroadcastsIE(TwitchVideosBaseIE): | |
478 | IE_NAME = 'twitch:videos:past-broadcasts' | |
479 | _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
480 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive' | |
c5db6bb3 S |
481 | _PLAYLIST_TYPE = 'past broadcasts' |
482 | ||
fce79626 | 483 | _TESTS = [{ |
93753aad S |
484 | 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts', |
485 | 'info_dict': { | |
486 | 'id': 'spamfish', | |
487 | 'title': 'Spamfish', | |
488 | }, | |
489 | 'playlist_mincount': 0, | |
fce79626 S |
490 | }, { |
491 | 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts', | |
492 | 'only_matching': True, | |
493 | }] | |
93753aad S |
494 | |
495 | ||
496 | class TwitchHighlightsIE(TwitchVideosBaseIE): | |
497 | IE_NAME = 'twitch:videos:highlights' | |
498 | _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
499 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight' | |
500 | _PLAYLIST_TYPE = 'highlights' | |
501 | ||
fce79626 | 502 | _TESTS = [{ |
93753aad | 503 | 'url': 'https://www.twitch.tv/spamfish/videos/highlights', |
c5db6bb3 S |
504 | 'info_dict': { |
505 | 'id': 'spamfish', | |
506 | 'title': 'Spamfish', | |
507 | }, | |
93753aad | 508 | 'playlist_mincount': 805, |
fce79626 S |
509 | }, { |
510 | 'url': 'https://m.twitch.tv/spamfish/videos/highlights', | |
511 | 'only_matching': True, | |
512 | }] | |
240b9b7a S |
513 | |
514 | ||
515 | class TwitchStreamIE(TwitchBaseIE): | |
516 | IE_NAME = 'twitch:stream' | |
9db8f6c5 S |
517 | _VALID_URL = r'''(?x) |
518 | https?:// | |
519 | (?: | |
fce79626 | 520 | (?:(?:www|go|m)\.)?twitch\.tv/| |
9db8f6c5 S |
521 | player\.twitch\.tv/\?.*?\bchannel= |
522 | ) | |
523 | (?P<id>[^/#?]+) | |
524 | ''' | |
240b9b7a | 525 | |
faa1f83a | 526 | _TESTS = [{ |
240b9b7a S |
527 | 'url': 'http://www.twitch.tv/shroomztv', |
528 | 'info_dict': { | |
529 | 'id': '12772022048', | |
530 | 'display_id': 'shroomztv', | |
531 | 'ext': 'mp4', | |
532 | 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$', | |
533 | 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV', | |
534 | 'is_live': True, | |
535 | 'timestamp': 1421928037, | |
536 | 'upload_date': '20150122', | |
537 | 'uploader': 'ShroomzTV', | |
538 | 'uploader_id': 'shroomztv', | |
539 | 'view_count': int, | |
540 | }, | |
541 | 'params': { | |
542 | # m3u8 download | |
543 | 'skip_download': True, | |
544 | }, | |
faa1f83a S |
545 | }, { |
546 | 'url': 'http://www.twitch.tv/miracle_doto#profile-0', | |
547 | 'only_matching': True, | |
9db8f6c5 S |
548 | }, { |
549 | 'url': 'https://player.twitch.tv/?channel=lotsofs', | |
550 | 'only_matching': True, | |
b763e1d6 S |
551 | }, { |
552 | 'url': 'https://go.twitch.tv/food', | |
553 | 'only_matching': True, | |
fce79626 S |
554 | }, { |
555 | 'url': 'https://m.twitch.tv/food', | |
556 | 'only_matching': True, | |
faa1f83a | 557 | }] |
240b9b7a | 558 | |
9db8f6c5 S |
559 | @classmethod |
560 | def suitable(cls, url): | |
561 | return (False | |
562 | if any(ie.suitable(url) for ie in ( | |
563 | TwitchVideoIE, | |
564 | TwitchChapterIE, | |
565 | TwitchVodIE, | |
566 | TwitchProfileIE, | |
567 | TwitchAllVideosIE, | |
568 | TwitchUploadsIE, | |
569 | TwitchPastBroadcastsIE, | |
db348e88 S |
570 | TwitchHighlightsIE, |
571 | TwitchClipsIE)) | |
9db8f6c5 S |
572 | else super(TwitchStreamIE, cls).suitable(url)) |
573 | ||
240b9b7a S |
574 | def _real_extract(self, url): |
575 | channel_id = self._match_id(url) | |
576 | ||
e3f6b569 | 577 | stream = self._call_api( |
00de61a9 S |
578 | 'kraken/streams/%s?stream_type=all' % channel_id.lower(), |
579 | channel_id, 'Downloading stream JSON').get('stream') | |
240b9b7a | 580 | |
240b9b7a | 581 | if not stream: |
cc764a6d | 582 | raise ExtractorError('%s is offline' % channel_id, expected=True) |
240b9b7a | 583 | |
06966677 S |
584 | # Channel name may be typed if different case than the original channel name |
585 | # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing | |
586 | # an invalid m3u8 URL. Working around by use of original channel name from stream | |
587 | # JSON and fallback to lowercase if it's not available. | |
1793d71d S |
588 | channel_id = stream.get('channel', {}).get('name') or channel_id.lower() |
589 | ||
e3f6b569 S |
590 | access_token = self._call_api( |
591 | 'api/channels/%s/access_token' % channel_id, channel_id, | |
240b9b7a S |
592 | 'Downloading channel access token') |
593 | ||
594 | query = { | |
595 | 'allow_source': 'true', | |
ac455055 | 596 | 'allow_audio_only': 'true', |
9aa929d3 | 597 | 'allow_spectre': 'true', |
f353cbdb | 598 | 'p': random.randint(1000000, 10000000), |
240b9b7a | 599 | 'player': 'twitchweb', |
1d31b7ca | 600 | 'playlist_include_framerate': 'true', |
240b9b7a | 601 | 'segment_preference': '4', |
d34e7949 S |
602 | 'sig': access_token['sig'].encode('utf-8'), |
603 | 'token': access_token['token'].encode('utf-8'), | |
240b9b7a | 604 | } |
240b9b7a S |
605 | formats = self._extract_m3u8_formats( |
606 | '%s/api/channel/hls/%s.m3u8?%s' | |
15707c7e | 607 | % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)), |
240b9b7a | 608 | channel_id, 'mp4') |
d0e958c7 | 609 | self._prefer_source(formats) |
240b9b7a S |
610 | |
611 | view_count = stream.get('viewers') | |
612 | timestamp = parse_iso8601(stream.get('created_at')) | |
613 | ||
614 | channel = stream['channel'] | |
615 | title = self._live_title(channel.get('display_name') or channel.get('name')) | |
616 | description = channel.get('status') | |
617 | ||
618 | thumbnails = [] | |
619 | for thumbnail_key, thumbnail_url in stream['preview'].items(): | |
620 | m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key) | |
621 | if not m: | |
622 | continue | |
623 | thumbnails.append({ | |
624 | 'url': thumbnail_url, | |
625 | 'width': int(m.group('width')), | |
626 | 'height': int(m.group('height')), | |
627 | }) | |
628 | ||
629 | return { | |
630 | 'id': compat_str(stream['_id']), | |
631 | 'display_id': channel_id, | |
632 | 'title': title, | |
633 | 'description': description, | |
634 | 'thumbnails': thumbnails, | |
635 | 'uploader': channel.get('display_name'), | |
636 | 'uploader_id': channel.get('name'), | |
637 | 'timestamp': timestamp, | |
638 | 'view_count': view_count, | |
639 | 'formats': formats, | |
640 | 'is_live': True, | |
12d1fb5a | 641 | } |
778f9694 S |
642 | |
643 | ||
49fa7de3 | 644 | class TwitchClipsIE(TwitchBaseIE): |
778f9694 | 645 | IE_NAME = 'twitch:clips' |
c9595ee7 FS |
646 | _VALID_URL = r'''(?x) |
647 | https?:// | |
648 | (?: | |
649 | clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)| | |
650 | (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/ | |
651 | ) | |
652 | (?P<id>[^/?#&]+) | |
653 | ''' | |
778f9694 | 654 | |
74ba450a | 655 | _TESTS = [{ |
49fa7de3 | 656 | 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat', |
778f9694 S |
657 | 'md5': '761769e1eafce0ffebfb4089cb3847cd', |
658 | 'info_dict': { | |
49fa7de3 | 659 | 'id': '42850523', |
778f9694 S |
660 | 'ext': 'mp4', |
661 | 'title': 'EA Play 2016 Live from the Novo Theatre', | |
ec85ded8 | 662 | 'thumbnail': r're:^https?://.*\.jpg', |
49fa7de3 S |
663 | 'timestamp': 1465767393, |
664 | 'upload_date': '20160612', | |
778f9694 S |
665 | 'creator': 'EA', |
666 | 'uploader': 'stereotype_', | |
49fa7de3 | 667 | 'uploader_id': '43566419', |
778f9694 | 668 | }, |
74ba450a S |
669 | }, { |
670 | # multiple formats | |
671 | 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy', | |
672 | 'only_matching': True, | |
db348e88 S |
673 | }, { |
674 | 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan', | |
675 | 'only_matching': True, | |
0b16b3c2 RA |
676 | }, { |
677 | 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited', | |
678 | 'only_matching': True, | |
c9595ee7 FS |
679 | }, { |
680 | 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank', | |
681 | 'only_matching': True, | |
682 | }, { | |
683 | 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank', | |
684 | 'only_matching': True, | |
74ba450a | 685 | }] |
778f9694 S |
686 | |
687 | def _real_extract(self, url): | |
688 | video_id = self._match_id(url) | |
689 | ||
232ed8e6 RA |
690 | clip = self._download_json( |
691 | 'https://gql.twitch.tv/gql', video_id, data=json.dumps({ | |
692 | 'query': '''{ | |
693 | clip(slug: "%s") { | |
694 | broadcaster { | |
695 | displayName | |
696 | } | |
697 | createdAt | |
698 | curator { | |
699 | displayName | |
700 | id | |
701 | } | |
702 | durationSeconds | |
703 | id | |
704 | tiny: thumbnailURL(width: 86, height: 45) | |
705 | small: thumbnailURL(width: 260, height: 147) | |
706 | medium: thumbnailURL(width: 480, height: 272) | |
707 | title | |
708 | videoQualities { | |
709 | frameRate | |
710 | quality | |
711 | sourceURL | |
712 | } | |
713 | viewCount | |
714 | } | |
715 | }''' % video_id, | |
716 | }).encode(), headers={ | |
717 | 'Client-ID': self._CLIENT_ID, | |
718 | })['data']['clip'] | |
719 | ||
720 | if not clip: | |
721 | raise ExtractorError( | |
722 | 'This clip is no longer available', expected=True) | |
778f9694 | 723 | |
49fa7de3 | 724 | formats = [] |
232ed8e6 | 725 | for option in clip.get('videoQualities', []): |
49fa7de3 S |
726 | if not isinstance(option, dict): |
727 | continue | |
232ed8e6 | 728 | source = url_or_none(option.get('sourceURL')) |
3052a30d | 729 | if not source: |
49fa7de3 S |
730 | continue |
731 | formats.append({ | |
732 | 'url': source, | |
733 | 'format_id': option.get('quality'), | |
734 | 'height': int_or_none(option.get('quality')), | |
232ed8e6 | 735 | 'fps': int_or_none(option.get('frameRate')), |
49fa7de3 | 736 | }) |
07acdc5a S |
737 | self._sort_formats(formats) |
738 | ||
232ed8e6 RA |
739 | thumbnails = [] |
740 | for thumbnail_id in ('tiny', 'small', 'medium'): | |
741 | thumbnail_url = clip.get(thumbnail_id) | |
742 | if not thumbnail_url: | |
743 | continue | |
744 | thumb = { | |
745 | 'id': thumbnail_id, | |
746 | 'url': thumbnail_url, | |
747 | } | |
748 | mobj = re.search(r'-(\d+)x(\d+)\.', thumbnail_url) | |
749 | if mobj: | |
750 | thumb.update({ | |
751 | 'height': int(mobj.group(2)), | |
752 | 'width': int(mobj.group(1)), | |
753 | }) | |
754 | thumbnails.append(thumb) | |
755 | ||
756 | return { | |
757 | 'id': clip.get('id') or video_id, | |
758 | 'title': clip.get('title') or video_id, | |
49fa7de3 | 759 | 'formats': formats, |
232ed8e6 RA |
760 | 'duration': int_or_none(clip.get('durationSeconds')), |
761 | 'views': int_or_none(clip.get('viewCount')), | |
762 | 'timestamp': unified_timestamp(clip.get('createdAt')), | |
763 | 'thumbnails': thumbnails, | |
764 | 'creator': try_get(clip, lambda x: x['broadcaster']['displayName'], compat_str), | |
765 | 'uploader': try_get(clip, lambda x: x['curator']['displayName'], compat_str), | |
766 | 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str), | |
49fa7de3 | 767 | } |