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