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