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