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