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