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