]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/twitch.py
[ie/ERRJupiter] Add extractor (#8549)
[yt-dlp.git] / yt_dlp / extractor / twitch.py
1 import collections
2 import itertools
3 import json
4 import random
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_parse_qs,
10 compat_str,
11 compat_urllib_parse_urlparse,
12 )
13 from ..utils import (
14 ExtractorError,
15 UserNotLive,
16 base_url,
17 clean_html,
18 dict_get,
19 float_or_none,
20 int_or_none,
21 make_archive_id,
22 parse_duration,
23 parse_iso8601,
24 parse_qs,
25 qualities,
26 str_or_none,
27 traverse_obj,
28 try_get,
29 unified_timestamp,
30 update_url_query,
31 url_or_none,
32 urljoin,
33 )
34
35
36 class TwitchBaseIE(InfoExtractor):
37 _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv'
38
39 _API_BASE = 'https://api.twitch.tv'
40 _USHER_BASE = 'https://usher.ttvnw.net'
41 _LOGIN_FORM_URL = 'https://www.twitch.tv/login'
42 _LOGIN_POST_URL = 'https://passport.twitch.tv/login'
43 _NETRC_MACHINE = 'twitch'
44
45 _OPERATION_HASHES = {
46 'CollectionSideBar': '27111f1b382effad0b6def325caef1909c733fe6a4fbabf54f8d491ef2cf2f14',
47 'FilterableVideoTower_Videos': 'a937f1d22e269e39a03b509f65a7490f9fc247d7f83d6ac1421523e3b68042cb',
48 'ClipsCards__User': 'b73ad2bfaecfd30a9e6c28fada15bd97032c83ec77a0440766a56fe0bd632777',
49 'ChannelCollectionsContent': '447aec6a0cc1e8d0a8d7732d47eb0762c336a2294fdb009e9c9d854e49d484b9',
50 'StreamMetadata': 'a647c2a13599e5991e175155f798ca7f1ecddde73f7f341f39009c14dbf59962',
51 'ComscoreStreamingQuery': 'e1edae8122517d013405f237ffcc124515dc6ded82480a88daef69c83b53ac01',
52 'VideoAccessToken_Clip': '36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11',
53 'VideoPreviewOverlay': '3006e77e51b128d838fa4e835723ca4dc9a05c5efd4466c1085215c6e437e65c',
54 'VideoMetadata': '49b5b8f268cdeb259d75b58dcb0c1a748e3b575003448a2333dc5cdafd49adad',
55 'VideoPlayer_ChapterSelectButtonVideo': '8d2793384aac3773beab5e59bd5d6f585aedb923d292800119e03d40cd0f9b41',
56 'VideoPlayer_VODSeekbarPreviewVideo': '07e99e4d56c5a7c67117a154777b0baf85a5ffefa393b213f4bc712ccaf85dd6',
57 }
58
59 @property
60 def _CLIENT_ID(self):
61 return self._configuration_arg(
62 'client_id', ['ue6666qo983tsx6so1t0vnawi233wa'], ie_key='Twitch', casesense=True)[0]
63
64 def _perform_login(self, username, password):
65 def fail(message):
66 raise ExtractorError(
67 'Unable to login. Twitch said: %s' % message, expected=True)
68
69 def login_step(page, urlh, note, data):
70 form = self._hidden_inputs(page)
71 form.update(data)
72
73 page_url = urlh.url
74 post_url = self._search_regex(
75 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
76 'post url', default=self._LOGIN_POST_URL, group='url')
77 post_url = urljoin(page_url, post_url)
78
79 headers = {
80 'Referer': page_url,
81 'Origin': 'https://www.twitch.tv',
82 'Content-Type': 'text/plain;charset=UTF-8',
83 }
84
85 response = self._download_json(
86 post_url, None, note, data=json.dumps(form).encode(),
87 headers=headers, expected_status=400)
88 error = dict_get(response, ('error', 'error_description', 'error_code'))
89 if error:
90 fail(error)
91
92 if 'Authenticated successfully' in response.get('message', ''):
93 return None, None
94
95 redirect_url = urljoin(
96 post_url,
97 response.get('redirect') or response['redirect_path'])
98 return self._download_webpage_handle(
99 redirect_url, None, 'Downloading login redirect page',
100 headers=headers)
101
102 login_page, handle = self._download_webpage_handle(
103 self._LOGIN_FORM_URL, None, 'Downloading login page')
104
105 # Some TOR nodes and public proxies are blocked completely
106 if 'blacklist_message' in login_page:
107 fail(clean_html(login_page))
108
109 redirect_page, handle = login_step(
110 login_page, handle, 'Logging in', {
111 'username': username,
112 'password': password,
113 'client_id': self._CLIENT_ID,
114 })
115
116 # Successful login
117 if not redirect_page:
118 return
119
120 if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
121 # TODO: Add mechanism to request an SMS or phone call
122 tfa_token = self._get_tfa_info('two-factor authentication token')
123 login_step(redirect_page, handle, 'Submitting TFA token', {
124 'authy_token': tfa_token,
125 'remember_2fa': 'true',
126 })
127
128 def _prefer_source(self, formats):
129 try:
130 source = next(f for f in formats if f['format_id'] == 'Source')
131 source['quality'] = 10
132 except StopIteration:
133 for f in formats:
134 if '/chunked/' in f['url']:
135 f.update({
136 'quality': 10,
137 'format_note': 'Source',
138 })
139
140 def _download_base_gql(self, video_id, ops, note, fatal=True):
141 headers = {
142 'Content-Type': 'text/plain;charset=UTF-8',
143 'Client-ID': self._CLIENT_ID,
144 }
145 gql_auth = self._get_cookies('https://gql.twitch.tv').get('auth-token')
146 if gql_auth:
147 headers['Authorization'] = 'OAuth ' + gql_auth.value
148 return self._download_json(
149 'https://gql.twitch.tv/gql', video_id, note,
150 data=json.dumps(ops).encode(),
151 headers=headers, fatal=fatal)
152
153 def _download_gql(self, video_id, ops, note, fatal=True):
154 for op in ops:
155 op['extensions'] = {
156 'persistedQuery': {
157 'version': 1,
158 'sha256Hash': self._OPERATION_HASHES[op['operationName']],
159 }
160 }
161 return self._download_base_gql(video_id, ops, note)
162
163 def _download_access_token(self, video_id, token_kind, param_name):
164 method = '%sPlaybackAccessToken' % token_kind
165 ops = {
166 'query': '''{
167 %s(
168 %s: "%s",
169 params: {
170 platform: "web",
171 playerBackend: "mediaplayer",
172 playerType: "site"
173 }
174 )
175 {
176 value
177 signature
178 }
179 }''' % (method, param_name, video_id),
180 }
181 return self._download_base_gql(
182 video_id, ops,
183 'Downloading %s access token GraphQL' % token_kind)['data'][method]
184
185 def _get_thumbnails(self, thumbnail):
186 return [{
187 'url': re.sub(r'\d+x\d+(\.\w+)($|(?=[?#]))', r'0x0\g<1>', thumbnail),
188 'preference': 1,
189 }, {
190 'url': thumbnail,
191 }] if thumbnail else None
192
193 def _extract_twitch_m3u8_formats(self, video_id, token, signature):
194 """Subclasses must define _M3U8_PATH"""
195 return self._extract_m3u8_formats(
196 f'{self._USHER_BASE}/{self._M3U8_PATH}/{video_id}.m3u8', video_id, 'mp4', query={
197 'allow_source': 'true',
198 'allow_audio_only': 'true',
199 'allow_spectre': 'true',
200 'p': random.randint(1000000, 10000000),
201 'player': 'twitchweb',
202 'playlist_include_framerate': 'true',
203 'sig': signature,
204 'token': token,
205 })
206
207
208 class TwitchVodIE(TwitchBaseIE):
209 IE_NAME = 'twitch:vod'
210 _VALID_URL = r'''(?x)
211 https?://
212 (?:
213 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
214 player\.twitch\.tv/\?.*?\bvideo=v?|
215 www\.twitch\.tv/[^/]+/schedule\?vodID=
216 )
217 (?P<id>\d+)
218 '''
219 _M3U8_PATH = 'vod'
220
221 _TESTS = [{
222 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
223 'info_dict': {
224 'id': 'v6528877',
225 'ext': 'mp4',
226 'title': 'LCK Summer Split - Week 6 Day 1',
227 'thumbnail': r're:^https?://.*\.jpg$',
228 'duration': 17208,
229 'timestamp': 1435131734,
230 'upload_date': '20150624',
231 'uploader': 'Riot Games',
232 'uploader_id': 'riotgames',
233 'view_count': int,
234 'start_time': 310,
235 'chapters': [
236 {
237 'start_time': 0,
238 'end_time': 17208,
239 'title': 'League of Legends'
240 }
241 ],
242 'live_status': 'was_live',
243 },
244 'params': {
245 # m3u8 download
246 'skip_download': True,
247 },
248 }, {
249 # Untitled broadcast (title is None)
250 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
251 'info_dict': {
252 'id': 'v11230755',
253 'ext': 'mp4',
254 'title': 'Untitled Broadcast',
255 'thumbnail': r're:^https?://.*\.jpg$',
256 'duration': 1638,
257 'timestamp': 1439746708,
258 'upload_date': '20150816',
259 'uploader': 'BelkAO_o',
260 'uploader_id': 'belkao_o',
261 'view_count': int,
262 },
263 'params': {
264 # m3u8 download
265 'skip_download': True,
266 },
267 'skip': 'HTTP Error 404: Not Found',
268 }, {
269 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
270 'only_matching': True,
271 }, {
272 'url': 'https://www.twitch.tv/videos/6528877',
273 'only_matching': True,
274 }, {
275 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
276 'only_matching': True,
277 }, {
278 'url': 'https://www.twitch.tv/northernlion/video/291940395',
279 'only_matching': True,
280 }, {
281 'url': 'https://player.twitch.tv/?video=480452374',
282 'only_matching': True,
283 }, {
284 'url': 'https://www.twitch.tv/videos/635475444',
285 'info_dict': {
286 'id': 'v635475444',
287 'ext': 'mp4',
288 'title': 'Riot Games',
289 'duration': 11643,
290 'uploader': 'Riot Games',
291 'uploader_id': 'riotgames',
292 'timestamp': 1590770569,
293 'upload_date': '20200529',
294 'chapters': [
295 {
296 'start_time': 0,
297 'end_time': 573,
298 'title': 'League of Legends'
299 },
300 {
301 'start_time': 573,
302 'end_time': 3922,
303 'title': 'Legends of Runeterra'
304 },
305 {
306 'start_time': 3922,
307 'end_time': 11643,
308 'title': 'Art'
309 }
310 ],
311 'live_status': 'was_live',
312 'thumbnail': r're:^https?://.*\.jpg$',
313 'view_count': int,
314 },
315 'params': {
316 'skip_download': True
317 },
318 }, {
319 'note': 'Storyboards',
320 'url': 'https://www.twitch.tv/videos/635475444',
321 'info_dict': {
322 'id': 'v635475444',
323 'format_id': 'sb0',
324 'ext': 'mhtml',
325 'title': 'Riot Games',
326 'duration': 11643,
327 'uploader': 'Riot Games',
328 'uploader_id': 'riotgames',
329 'timestamp': 1590770569,
330 'upload_date': '20200529',
331 'chapters': [
332 {
333 'start_time': 0,
334 'end_time': 573,
335 'title': 'League of Legends'
336 },
337 {
338 'start_time': 573,
339 'end_time': 3922,
340 'title': 'Legends of Runeterra'
341 },
342 {
343 'start_time': 3922,
344 'end_time': 11643,
345 'title': 'Art'
346 }
347 ],
348 'live_status': 'was_live',
349 'thumbnail': r're:^https?://.*\.jpg$',
350 'view_count': int,
351 'columns': int,
352 'rows': int,
353 },
354 'params': {
355 'format': 'mhtml',
356 'skip_download': True
357 }
358 }, {
359 'note': 'VOD with single chapter',
360 'url': 'https://www.twitch.tv/videos/1536751224',
361 'info_dict': {
362 'id': 'v1536751224',
363 'ext': 'mp4',
364 'title': 'Porter Robinson Star Guardian Stream Tour with LilyPichu',
365 'duration': 8353,
366 'uploader': 'Riot Games',
367 'uploader_id': 'riotgames',
368 'timestamp': 1658267731,
369 'upload_date': '20220719',
370 'chapters': [
371 {
372 'start_time': 0,
373 'end_time': 8353,
374 'title': 'League of Legends'
375 }
376 ],
377 'live_status': 'was_live',
378 'thumbnail': r're:^https?://.*\.jpg$',
379 'view_count': int,
380 },
381 'params': {
382 'skip_download': True
383 },
384 'expected_warnings': ['Unable to download JSON metadata: HTTP Error 403: Forbidden']
385 }, {
386 'url': 'https://www.twitch.tv/tangotek/schedule?vodID=1822395420',
387 'only_matching': True,
388 }]
389
390 def _download_info(self, item_id):
391 data = self._download_gql(
392 item_id, [{
393 'operationName': 'VideoMetadata',
394 'variables': {
395 'channelLogin': '',
396 'videoID': item_id,
397 },
398 }, {
399 'operationName': 'VideoPlayer_ChapterSelectButtonVideo',
400 'variables': {
401 'includePrivate': False,
402 'videoID': item_id,
403 },
404 }, {
405 'operationName': 'VideoPlayer_VODSeekbarPreviewVideo',
406 'variables': {
407 'includePrivate': False,
408 'videoID': item_id,
409 },
410 }],
411 'Downloading stream metadata GraphQL')
412
413 video = traverse_obj(data, (..., 'data', 'video'), get_all=False)
414 if video is None:
415 raise ExtractorError(f'Video {item_id} does not exist', expected=True)
416
417 video['moments'] = traverse_obj(data, (..., 'data', 'video', 'moments', 'edges', ..., 'node'))
418 video['storyboard'] = traverse_obj(
419 data, (..., 'data', 'video', 'seekPreviewsURL', {url_or_none}), get_all=False)
420
421 return video
422
423 def _extract_info(self, info):
424 status = info.get('status')
425 if status == 'recording':
426 is_live = True
427 elif status == 'recorded':
428 is_live = False
429 else:
430 is_live = None
431 _QUALITIES = ('small', 'medium', 'large')
432 quality_key = qualities(_QUALITIES)
433 thumbnails = []
434 preview = info.get('preview')
435 if isinstance(preview, dict):
436 for thumbnail_id, thumbnail_url in preview.items():
437 thumbnail_url = url_or_none(thumbnail_url)
438 if not thumbnail_url:
439 continue
440 if thumbnail_id not in _QUALITIES:
441 continue
442 thumbnails.append({
443 'url': thumbnail_url,
444 'preference': quality_key(thumbnail_id),
445 })
446 return {
447 'id': info['_id'],
448 'title': info.get('title') or 'Untitled Broadcast',
449 'description': info.get('description'),
450 'duration': int_or_none(info.get('length')),
451 'thumbnails': thumbnails,
452 'uploader': info.get('channel', {}).get('display_name'),
453 'uploader_id': info.get('channel', {}).get('name'),
454 'timestamp': parse_iso8601(info.get('recorded_at')),
455 'view_count': int_or_none(info.get('views')),
456 'is_live': is_live,
457 'was_live': True,
458 }
459
460 def _extract_chapters(self, info, item_id):
461 if not info.get('moments'):
462 game = traverse_obj(info, ('game', 'displayName'))
463 if game:
464 yield {'title': game}
465 return
466
467 for moment in info['moments']:
468 start_time = int_or_none(moment.get('positionMilliseconds'), 1000)
469 duration = int_or_none(moment.get('durationMilliseconds'), 1000)
470 name = str_or_none(moment.get('description'))
471
472 if start_time is None or duration is None:
473 self.report_warning(f'Important chapter information missing for chapter {name}', item_id)
474 continue
475 yield {
476 'start_time': start_time,
477 'end_time': start_time + duration,
478 'title': name,
479 }
480
481 def _extract_info_gql(self, info, item_id):
482 vod_id = info.get('id') or item_id
483 # id backward compatibility for download archives
484 if vod_id[0] != 'v':
485 vod_id = 'v%s' % vod_id
486 thumbnail = url_or_none(info.get('previewThumbnailURL'))
487 is_live = None
488 if thumbnail:
489 if re.findall(r'/404_processing_[^.?#]+\.png', thumbnail):
490 is_live, thumbnail = True, None
491 else:
492 is_live = False
493
494 return {
495 'id': vod_id,
496 'title': info.get('title') or 'Untitled Broadcast',
497 'description': info.get('description'),
498 'duration': int_or_none(info.get('lengthSeconds')),
499 'thumbnails': self._get_thumbnails(thumbnail),
500 'uploader': try_get(info, lambda x: x['owner']['displayName'], compat_str),
501 'uploader_id': try_get(info, lambda x: x['owner']['login'], compat_str),
502 'timestamp': unified_timestamp(info.get('publishedAt')),
503 'view_count': int_or_none(info.get('viewCount')),
504 'chapters': list(self._extract_chapters(info, item_id)),
505 'is_live': is_live,
506 'was_live': True,
507 }
508
509 def _extract_storyboard(self, item_id, storyboard_json_url, duration):
510 if not duration or not storyboard_json_url:
511 return
512 spec = self._download_json(storyboard_json_url, item_id, 'Downloading storyboard metadata JSON', fatal=False) or []
513 # sort from highest quality to lowest
514 # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
515 spec.sort(key=lambda x: int_or_none(x.get('width')) or 0, reverse=True)
516 base = base_url(storyboard_json_url)
517 for i, s in enumerate(spec):
518 count = int_or_none(s.get('count'))
519 images = s.get('images')
520 if not (images and count):
521 continue
522 fragment_duration = duration / len(images)
523 yield {
524 'format_id': f'sb{i}',
525 'format_note': 'storyboard',
526 'ext': 'mhtml',
527 'protocol': 'mhtml',
528 'acodec': 'none',
529 'vcodec': 'none',
530 'url': urljoin(base, images[0]),
531 'width': int_or_none(s.get('width')),
532 'height': int_or_none(s.get('height')),
533 'fps': count / duration,
534 'rows': int_or_none(s.get('rows')),
535 'columns': int_or_none(s.get('cols')),
536 'fragments': [{
537 'url': urljoin(base, path),
538 'duration': fragment_duration,
539 } for path in images],
540 }
541
542 def _real_extract(self, url):
543 vod_id = self._match_id(url)
544
545 video = self._download_info(vod_id)
546 info = self._extract_info_gql(video, vod_id)
547 access_token = self._download_access_token(vod_id, 'video', 'id')
548
549 formats = self._extract_twitch_m3u8_formats(
550 vod_id, access_token['value'], access_token['signature'])
551 formats.extend(self._extract_storyboard(vod_id, video.get('storyboard'), info.get('duration')))
552
553 self._prefer_source(formats)
554 info['formats'] = formats
555
556 parsed_url = compat_urllib_parse_urlparse(url)
557 query = compat_parse_qs(parsed_url.query)
558 if 't' in query:
559 info['start_time'] = parse_duration(query['t'][0])
560
561 if info.get('timestamp') is not None:
562 info['subtitles'] = {
563 'rechat': [{
564 'url': update_url_query(
565 'https://api.twitch.tv/v5/videos/%s/comments' % vod_id, {
566 'client_id': self._CLIENT_ID,
567 }),
568 'ext': 'json',
569 }],
570 }
571
572 return info
573
574
575 def _make_video_result(node):
576 assert isinstance(node, dict)
577 video_id = node.get('id')
578 if not video_id:
579 return
580 return {
581 '_type': 'url_transparent',
582 'ie_key': TwitchVodIE.ie_key(),
583 'id': 'v' + video_id,
584 'url': 'https://www.twitch.tv/videos/%s' % video_id,
585 'title': node.get('title'),
586 'thumbnail': node.get('previewThumbnailURL'),
587 'duration': float_or_none(node.get('lengthSeconds')),
588 'view_count': int_or_none(node.get('viewCount')),
589 }
590
591
592 class TwitchCollectionIE(TwitchBaseIE):
593 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
594
595 _TESTS = [{
596 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
597 'info_dict': {
598 'id': 'wlDCoH0zEBZZbQ',
599 'title': 'Overthrow Nook, capitalism for children',
600 },
601 'playlist_mincount': 13,
602 }]
603
604 _OPERATION_NAME = 'CollectionSideBar'
605
606 def _real_extract(self, url):
607 collection_id = self._match_id(url)
608 collection = self._download_gql(
609 collection_id, [{
610 'operationName': self._OPERATION_NAME,
611 'variables': {'collectionID': collection_id},
612 }],
613 'Downloading collection GraphQL')[0]['data']['collection']
614 title = collection.get('title')
615 entries = []
616 for edge in collection['items']['edges']:
617 if not isinstance(edge, dict):
618 continue
619 node = edge.get('node')
620 if not isinstance(node, dict):
621 continue
622 video = _make_video_result(node)
623 if video:
624 entries.append(video)
625 return self.playlist_result(
626 entries, playlist_id=collection_id, playlist_title=title)
627
628
629 class TwitchPlaylistBaseIE(TwitchBaseIE):
630 _PAGE_LIMIT = 100
631
632 def _entries(self, channel_name, *args):
633 cursor = None
634 variables_common = self._make_variables(channel_name, *args)
635 entries_key = '%ss' % self._ENTRY_KIND
636 for page_num in itertools.count(1):
637 variables = variables_common.copy()
638 variables['limit'] = self._PAGE_LIMIT
639 if cursor:
640 variables['cursor'] = cursor
641 page = self._download_gql(
642 channel_name, [{
643 'operationName': self._OPERATION_NAME,
644 'variables': variables,
645 }],
646 'Downloading %ss GraphQL page %s' % (self._NODE_KIND, page_num),
647 fatal=False)
648 if not page:
649 break
650 edges = try_get(
651 page, lambda x: x[0]['data']['user'][entries_key]['edges'], list)
652 if not edges:
653 break
654 for edge in edges:
655 if not isinstance(edge, dict):
656 continue
657 if edge.get('__typename') != self._EDGE_KIND:
658 continue
659 node = edge.get('node')
660 if not isinstance(node, dict):
661 continue
662 if node.get('__typename') != self._NODE_KIND:
663 continue
664 entry = self._extract_entry(node)
665 if entry:
666 cursor = edge.get('cursor')
667 yield entry
668 if not cursor or not isinstance(cursor, compat_str):
669 break
670
671
672 class TwitchVideosIE(TwitchPlaylistBaseIE):
673 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
674
675 _TESTS = [{
676 # All Videos sorted by Date
677 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
678 'info_dict': {
679 'id': 'spamfish',
680 'title': 'spamfish - All Videos sorted by Date',
681 },
682 'playlist_mincount': 924,
683 }, {
684 # All Videos sorted by Popular
685 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
686 'info_dict': {
687 'id': 'spamfish',
688 'title': 'spamfish - All Videos sorted by Popular',
689 },
690 'playlist_mincount': 931,
691 }, {
692 # Past Broadcasts sorted by Date
693 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
694 'info_dict': {
695 'id': 'spamfish',
696 'title': 'spamfish - Past Broadcasts sorted by Date',
697 },
698 'playlist_mincount': 27,
699 }, {
700 # Highlights sorted by Date
701 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
702 'info_dict': {
703 'id': 'spamfish',
704 'title': 'spamfish - Highlights sorted by Date',
705 },
706 'playlist_mincount': 901,
707 }, {
708 # Uploads sorted by Date
709 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
710 'info_dict': {
711 'id': 'esl_csgo',
712 'title': 'esl_csgo - Uploads sorted by Date',
713 },
714 'playlist_mincount': 5,
715 }, {
716 # Past Premieres sorted by Date
717 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
718 'info_dict': {
719 'id': 'spamfish',
720 'title': 'spamfish - Past Premieres sorted by Date',
721 },
722 'playlist_mincount': 1,
723 }, {
724 'url': 'https://www.twitch.tv/spamfish/videos/all',
725 'only_matching': True,
726 }, {
727 'url': 'https://m.twitch.tv/spamfish/videos/all',
728 'only_matching': True,
729 }, {
730 'url': 'https://www.twitch.tv/spamfish/videos',
731 'only_matching': True,
732 }]
733
734 Broadcast = collections.namedtuple('Broadcast', ['type', 'label'])
735
736 _DEFAULT_BROADCAST = Broadcast(None, 'All Videos')
737 _BROADCASTS = {
738 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
739 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
740 'uploads': Broadcast('UPLOAD', 'Uploads'),
741 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
742 'all': _DEFAULT_BROADCAST,
743 }
744
745 _DEFAULT_SORTED_BY = 'Date'
746 _SORTED_BY = {
747 'time': _DEFAULT_SORTED_BY,
748 'views': 'Popular',
749 }
750
751 _OPERATION_NAME = 'FilterableVideoTower_Videos'
752 _ENTRY_KIND = 'video'
753 _EDGE_KIND = 'VideoEdge'
754 _NODE_KIND = 'Video'
755
756 @classmethod
757 def suitable(cls, url):
758 return (False
759 if any(ie.suitable(url) for ie in (
760 TwitchVideosClipsIE,
761 TwitchVideosCollectionsIE))
762 else super(TwitchVideosIE, cls).suitable(url))
763
764 @staticmethod
765 def _make_variables(channel_name, broadcast_type, sort):
766 return {
767 'channelOwnerLogin': channel_name,
768 'broadcastType': broadcast_type,
769 'videoSort': sort.upper(),
770 }
771
772 @staticmethod
773 def _extract_entry(node):
774 return _make_video_result(node)
775
776 def _real_extract(self, url):
777 channel_name = self._match_id(url)
778 qs = parse_qs(url)
779 filter = qs.get('filter', ['all'])[0]
780 sort = qs.get('sort', ['time'])[0]
781 broadcast = self._BROADCASTS.get(filter, self._DEFAULT_BROADCAST)
782 return self.playlist_result(
783 self._entries(channel_name, broadcast.type, sort),
784 playlist_id=channel_name,
785 playlist_title='%s - %s sorted by %s'
786 % (channel_name, broadcast.label,
787 self._SORTED_BY.get(sort, self._DEFAULT_SORTED_BY)))
788
789
790 class TwitchVideosClipsIE(TwitchPlaylistBaseIE):
791 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
792
793 _TESTS = [{
794 # Clips
795 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
796 'info_dict': {
797 'id': 'vanillatv',
798 'title': 'vanillatv - Clips Top All',
799 },
800 'playlist_mincount': 1,
801 }, {
802 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
803 'only_matching': True,
804 }]
805
806 Clip = collections.namedtuple('Clip', ['filter', 'label'])
807
808 _DEFAULT_CLIP = Clip('LAST_WEEK', 'Top 7D')
809 _RANGE = {
810 '24hr': Clip('LAST_DAY', 'Top 24H'),
811 '7d': _DEFAULT_CLIP,
812 '30d': Clip('LAST_MONTH', 'Top 30D'),
813 'all': Clip('ALL_TIME', 'Top All'),
814 }
815
816 # NB: values other than 20 result in skipped videos
817 _PAGE_LIMIT = 20
818
819 _OPERATION_NAME = 'ClipsCards__User'
820 _ENTRY_KIND = 'clip'
821 _EDGE_KIND = 'ClipEdge'
822 _NODE_KIND = 'Clip'
823
824 @staticmethod
825 def _make_variables(channel_name, filter):
826 return {
827 'login': channel_name,
828 'criteria': {
829 'filter': filter,
830 },
831 }
832
833 @staticmethod
834 def _extract_entry(node):
835 assert isinstance(node, dict)
836 clip_url = url_or_none(node.get('url'))
837 if not clip_url:
838 return
839 return {
840 '_type': 'url_transparent',
841 'ie_key': TwitchClipsIE.ie_key(),
842 'id': node.get('id'),
843 'url': clip_url,
844 'title': node.get('title'),
845 'thumbnail': node.get('thumbnailURL'),
846 'duration': float_or_none(node.get('durationSeconds')),
847 'timestamp': unified_timestamp(node.get('createdAt')),
848 'view_count': int_or_none(node.get('viewCount')),
849 'language': node.get('language'),
850 }
851
852 def _real_extract(self, url):
853 channel_name = self._match_id(url)
854 qs = parse_qs(url)
855 range = qs.get('range', ['7d'])[0]
856 clip = self._RANGE.get(range, self._DEFAULT_CLIP)
857 return self.playlist_result(
858 self._entries(channel_name, clip.filter),
859 playlist_id=channel_name,
860 playlist_title='%s - Clips %s' % (channel_name, clip.label))
861
862
863 class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE):
864 _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
865
866 _TESTS = [{
867 # Collections
868 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
869 'info_dict': {
870 'id': 'spamfish',
871 'title': 'spamfish - Collections',
872 },
873 'playlist_mincount': 3,
874 }, {
875 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
876 'info_dict': {
877 'id': 'monstercat',
878 'title': 'monstercat - Collections',
879 },
880 'playlist_mincount': 13,
881 }]
882
883 _OPERATION_NAME = 'ChannelCollectionsContent'
884 _ENTRY_KIND = 'collection'
885 _EDGE_KIND = 'CollectionsItemEdge'
886 _NODE_KIND = 'Collection'
887
888 @staticmethod
889 def _make_variables(channel_name):
890 return {
891 'ownerLogin': channel_name,
892 }
893
894 @staticmethod
895 def _extract_entry(node):
896 assert isinstance(node, dict)
897 collection_id = node.get('id')
898 if not collection_id:
899 return
900 return {
901 '_type': 'url_transparent',
902 'ie_key': TwitchCollectionIE.ie_key(),
903 'id': collection_id,
904 'url': 'https://www.twitch.tv/collections/%s' % collection_id,
905 'title': node.get('title'),
906 'thumbnail': node.get('thumbnailURL'),
907 'duration': float_or_none(node.get('lengthSeconds')),
908 'timestamp': unified_timestamp(node.get('updatedAt')),
909 'view_count': int_or_none(node.get('viewCount')),
910 }
911
912 def _real_extract(self, url):
913 channel_name = self._match_id(url)
914 return self.playlist_result(
915 self._entries(channel_name), playlist_id=channel_name,
916 playlist_title='%s - Collections' % channel_name)
917
918
919 class TwitchStreamIE(TwitchBaseIE):
920 IE_NAME = 'twitch:stream'
921 _VALID_URL = r'''(?x)
922 https?://
923 (?:
924 (?:(?:www|go|m)\.)?twitch\.tv/|
925 player\.twitch\.tv/\?.*?\bchannel=
926 )
927 (?P<id>[^/#?]+)
928 '''
929 _M3U8_PATH = 'api/channel/hls'
930
931 _TESTS = [{
932 'url': 'http://www.twitch.tv/shroomztv',
933 'info_dict': {
934 'id': '12772022048',
935 'display_id': 'shroomztv',
936 'ext': 'mp4',
937 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
938 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
939 'is_live': True,
940 'timestamp': 1421928037,
941 'upload_date': '20150122',
942 'uploader': 'ShroomzTV',
943 'uploader_id': 'shroomztv',
944 'view_count': int,
945 },
946 'params': {
947 # m3u8 download
948 'skip_download': True,
949 },
950 'skip': 'User does not exist',
951 }, {
952 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
953 'only_matching': True,
954 }, {
955 'url': 'https://player.twitch.tv/?channel=lotsofs',
956 'only_matching': True,
957 }, {
958 'url': 'https://go.twitch.tv/food',
959 'only_matching': True,
960 }, {
961 'url': 'https://m.twitch.tv/food',
962 'only_matching': True,
963 }, {
964 'url': 'https://www.twitch.tv/monstercat',
965 'info_dict': {
966 'id': '40500071752',
967 'display_id': 'monstercat',
968 'title': 're:Monstercat',
969 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
970 'is_live': True,
971 'timestamp': 1677107190,
972 'upload_date': '20230222',
973 'uploader': 'Monstercat',
974 'uploader_id': 'monstercat',
975 'live_status': 'is_live',
976 'thumbnail': 're:https://.*.jpg',
977 'ext': 'mp4',
978 },
979 'params': {
980 'skip_download': 'Livestream',
981 },
982 }]
983
984 @classmethod
985 def suitable(cls, url):
986 return (False
987 if any(ie.suitable(url) for ie in (
988 TwitchVodIE,
989 TwitchCollectionIE,
990 TwitchVideosIE,
991 TwitchVideosClipsIE,
992 TwitchVideosCollectionsIE,
993 TwitchClipsIE))
994 else super(TwitchStreamIE, cls).suitable(url))
995
996 def _real_extract(self, url):
997 channel_name = self._match_id(url).lower()
998
999 gql = self._download_gql(
1000 channel_name, [{
1001 'operationName': 'StreamMetadata',
1002 'variables': {'channelLogin': channel_name},
1003 }, {
1004 'operationName': 'ComscoreStreamingQuery',
1005 'variables': {
1006 'channel': channel_name,
1007 'clipSlug': '',
1008 'isClip': False,
1009 'isLive': True,
1010 'isVodOrCollection': False,
1011 'vodID': '',
1012 },
1013 }, {
1014 'operationName': 'VideoPreviewOverlay',
1015 'variables': {'login': channel_name},
1016 }],
1017 'Downloading stream GraphQL')
1018
1019 user = gql[0]['data']['user']
1020
1021 if not user:
1022 raise ExtractorError(
1023 '%s does not exist' % channel_name, expected=True)
1024
1025 stream = user['stream']
1026
1027 if not stream:
1028 raise UserNotLive(video_id=channel_name)
1029
1030 access_token = self._download_access_token(
1031 channel_name, 'stream', 'channelName')
1032
1033 stream_id = stream.get('id') or channel_name
1034 formats = self._extract_twitch_m3u8_formats(
1035 channel_name, access_token['value'], access_token['signature'])
1036 self._prefer_source(formats)
1037
1038 view_count = stream.get('viewers')
1039 timestamp = unified_timestamp(stream.get('createdAt'))
1040
1041 sq_user = try_get(gql, lambda x: x[1]['data']['user'], dict) or {}
1042 uploader = sq_user.get('displayName')
1043 description = try_get(
1044 sq_user, lambda x: x['broadcastSettings']['title'], compat_str)
1045
1046 thumbnail = url_or_none(try_get(
1047 gql, lambda x: x[2]['data']['user']['stream']['previewImageURL'],
1048 compat_str))
1049
1050 title = uploader or channel_name
1051 stream_type = stream.get('type')
1052 if stream_type in ['rerun', 'live']:
1053 title += ' (%s)' % stream_type
1054
1055 return {
1056 'id': stream_id,
1057 'display_id': channel_name,
1058 'title': title,
1059 'description': description,
1060 'thumbnails': self._get_thumbnails(thumbnail),
1061 'uploader': uploader,
1062 'uploader_id': channel_name,
1063 'timestamp': timestamp,
1064 'view_count': view_count,
1065 'formats': formats,
1066 'is_live': stream_type == 'live',
1067 }
1068
1069
1070 class TwitchClipsIE(TwitchBaseIE):
1071 IE_NAME = 'twitch:clips'
1072 _VALID_URL = r'''(?x)
1073 https?://
1074 (?:
1075 clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
1076 (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/)?clip/
1077 )
1078 (?P<id>[^/?#&]+)
1079 '''
1080
1081 _TESTS = [{
1082 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
1083 'md5': '761769e1eafce0ffebfb4089cb3847cd',
1084 'info_dict': {
1085 'id': '42850523',
1086 'display_id': 'FaintLightGullWholeWheat',
1087 'ext': 'mp4',
1088 'title': 'EA Play 2016 Live from the Novo Theatre',
1089 'thumbnail': r're:^https?://.*\.jpg',
1090 'timestamp': 1465767393,
1091 'upload_date': '20160612',
1092 'creator': 'EA',
1093 'uploader': 'stereotype_',
1094 'uploader_id': '43566419',
1095 },
1096 }, {
1097 # multiple formats
1098 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
1099 'only_matching': True,
1100 }, {
1101 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
1102 'only_matching': True,
1103 }, {
1104 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
1105 'only_matching': True,
1106 }, {
1107 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1108 'only_matching': True,
1109 }, {
1110 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
1111 'only_matching': True,
1112 }, {
1113 'url': 'https://m.twitch.tv/clip/FaintLightGullWholeWheat',
1114 'only_matching': True,
1115 }]
1116
1117 def _real_extract(self, url):
1118 video_id = self._match_id(url)
1119
1120 clip = self._download_gql(
1121 video_id, [{
1122 'operationName': 'VideoAccessToken_Clip',
1123 'variables': {
1124 'slug': video_id,
1125 },
1126 }],
1127 'Downloading clip access token GraphQL')[0]['data']['clip']
1128
1129 if not clip:
1130 raise ExtractorError(
1131 'This clip is no longer available', expected=True)
1132
1133 access_query = {
1134 'sig': clip['playbackAccessToken']['signature'],
1135 'token': clip['playbackAccessToken']['value'],
1136 }
1137
1138 data = self._download_base_gql(
1139 video_id, {
1140 'query': '''{
1141 clip(slug: "%s") {
1142 broadcaster {
1143 displayName
1144 }
1145 createdAt
1146 curator {
1147 displayName
1148 id
1149 }
1150 durationSeconds
1151 id
1152 tiny: thumbnailURL(width: 86, height: 45)
1153 small: thumbnailURL(width: 260, height: 147)
1154 medium: thumbnailURL(width: 480, height: 272)
1155 title
1156 videoQualities {
1157 frameRate
1158 quality
1159 sourceURL
1160 }
1161 viewCount
1162 }
1163 }''' % video_id}, 'Downloading clip GraphQL', fatal=False)
1164
1165 if data:
1166 clip = try_get(data, lambda x: x['data']['clip'], dict) or clip
1167
1168 formats = []
1169 for option in clip.get('videoQualities', []):
1170 if not isinstance(option, dict):
1171 continue
1172 source = url_or_none(option.get('sourceURL'))
1173 if not source:
1174 continue
1175 formats.append({
1176 'url': update_url_query(source, access_query),
1177 'format_id': option.get('quality'),
1178 'height': int_or_none(option.get('quality')),
1179 'fps': int_or_none(option.get('frameRate')),
1180 })
1181
1182 thumbnails = []
1183 for thumbnail_id in ('tiny', 'small', 'medium'):
1184 thumbnail_url = clip.get(thumbnail_id)
1185 if not thumbnail_url:
1186 continue
1187 thumb = {
1188 'id': thumbnail_id,
1189 'url': thumbnail_url,
1190 }
1191 mobj = re.search(r'-(\d+)x(\d+)\.', thumbnail_url)
1192 if mobj:
1193 thumb.update({
1194 'height': int(mobj.group(2)),
1195 'width': int(mobj.group(1)),
1196 })
1197 thumbnails.append(thumb)
1198
1199 old_id = self._search_regex(r'%7C(\d+)(?:-\d+)?.mp4', formats[-1]['url'], 'old id', default=None)
1200
1201 return {
1202 'id': clip.get('id') or video_id,
1203 '_old_archive_ids': [make_archive_id(self, old_id)] if old_id else None,
1204 'display_id': video_id,
1205 'title': clip.get('title'),
1206 'formats': formats,
1207 'duration': int_or_none(clip.get('durationSeconds')),
1208 'view_count': int_or_none(clip.get('viewCount')),
1209 'timestamp': unified_timestamp(clip.get('createdAt')),
1210 'thumbnails': thumbnails,
1211 'creator': try_get(clip, lambda x: x['broadcaster']['displayName'], compat_str),
1212 'uploader': try_get(clip, lambda x: x['curator']['displayName'], compat_str),
1213 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),
1214 }