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