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