]>
Commit | Line | Data |
---|---|---|
04d02a9d | 1 | # coding: utf-8 |
ee1e1996 PH |
2 | from __future__ import unicode_literals |
3 | ||
3182f3e2 | 4 | import itertools |
79e93125 | 5 | import re |
f353cbdb | 6 | import random |
79e93125 PH |
7 | |
8 | from .common import InfoExtractor | |
1cc79574 | 9 | from ..compat import ( |
efe470e2 | 10 | compat_HTTPError, |
49fa7de3 | 11 | compat_kwargs, |
e704f87f | 12 | compat_parse_qs, |
240b9b7a | 13 | compat_str, |
15707c7e | 14 | compat_urllib_parse_urlencode, |
e704f87f | 15 | compat_urllib_parse_urlparse, |
1cc79574 PH |
16 | ) |
17 | from ..utils import ( | |
efe470e2 | 18 | clean_html, |
79e93125 | 19 | ExtractorError, |
49fa7de3 | 20 | float_or_none, |
7a6e8a1b | 21 | int_or_none, |
8bbb4b56 | 22 | orderedSet, |
e704f87f | 23 | parse_duration, |
355d074f | 24 | parse_iso8601, |
49fa7de3 S |
25 | qualities, |
26 | try_get, | |
27 | unified_timestamp, | |
264e77c4 | 28 | update_url_query, |
6e6bc8da | 29 | urlencode_postdata, |
3052a30d | 30 | url_or_none, |
c64c03be | 31 | urljoin, |
79e93125 PH |
32 | ) |
33 | ||
34 | ||
c5db6bb3 | 35 | class TwitchBaseIE(InfoExtractor): |
fce79626 | 36 | _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv' |
c5db6bb3 | 37 | |
46fd0dd5 | 38 | _API_BASE = 'https://api.twitch.tv' |
9f4576a7 | 39 | _USHER_BASE = 'https://usher.ttvnw.net' |
c64c03be | 40 | _LOGIN_URL = 'https://www.twitch.tv/login' |
95be29e1 | 41 | _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6' |
499bfcbf | 42 | _NETRC_MACHINE = 'twitch' |
79e93125 | 43 | |
355d074f S |
44 | def _handle_error(self, response): |
45 | if not isinstance(response, dict): | |
46 | return | |
47 | error = response.get('error') | |
48 | if error: | |
49 | raise ExtractorError( | |
50 | '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')), | |
51 | expected=True) | |
52 | ||
49fa7de3 S |
53 | def _call_api(self, path, item_id, *args, **kwargs): |
54 | kwargs.setdefault('headers', {})['Client-ID'] = self._CLIENT_ID | |
e3f6b569 | 55 | response = self._download_json( |
49fa7de3 S |
56 | '%s/%s' % (self._API_BASE, path), item_id, |
57 | *args, **compat_kwargs(kwargs)) | |
355d074f S |
58 | self._handle_error(response) |
59 | return response | |
60 | ||
c5db6bb3 S |
61 | def _real_initialize(self): |
62 | self._login() | |
63 | ||
64 | def _login(self): | |
68217024 | 65 | username, password = self._get_login_info() |
c5db6bb3 S |
66 | if username is None: |
67 | return | |
68 | ||
efe470e2 S |
69 | def fail(message): |
70 | raise ExtractorError( | |
71 | 'Unable to login. Twitch said: %s' % message, expected=True) | |
72 | ||
5316566e | 73 | def login_step(page, urlh, note, data): |
c64c03be XDG |
74 | form = self._hidden_inputs(page) |
75 | form.update(data) | |
76 | ||
77 | page_url = urlh.geturl() | |
78 | post_url = self._search_regex( | |
79 | r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page, | |
80 | 'post url', default=page_url, group='url') | |
81 | post_url = urljoin(page_url, post_url) | |
82 | ||
83 | headers = {'Referer': page_url} | |
84 | ||
85 | try: | |
86 | response = self._download_json( | |
87 | post_url, None, note, | |
88 | data=urlencode_postdata(form), | |
89 | headers=headers) | |
90 | except ExtractorError as e: | |
91 | if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400: | |
92 | response = self._parse_json( | |
93 | e.cause.read().decode('utf-8'), None) | |
1370dba5 | 94 | fail(response.get('message') or response['errors'][0]) |
c64c03be XDG |
95 | raise |
96 | ||
1370dba5 S |
97 | if 'Authenticated successfully' in response.get('message', ''): |
98 | return None, None | |
99 | ||
100 | redirect_url = urljoin( | |
101 | post_url, | |
102 | response.get('redirect') or response['redirect_path']) | |
5316566e S |
103 | return self._download_webpage_handle( |
104 | redirect_url, None, 'Downloading login redirect page', | |
105 | headers=headers) | |
c64c03be | 106 | |
fbd9f6ea | 107 | login_page, handle = self._download_webpage_handle( |
c5db6bb3 S |
108 | self._LOGIN_URL, None, 'Downloading login page') |
109 | ||
efe470e2 S |
110 | # Some TOR nodes and public proxies are blocked completely |
111 | if 'blacklist_message' in login_page: | |
112 | fail(clean_html(login_page)) | |
113 | ||
5316566e | 114 | redirect_page, handle = login_step( |
e4d95865 | 115 | login_page, handle, 'Logging in', { |
5316566e S |
116 | 'username': username, |
117 | 'password': password, | |
fe646a2f | 118 | }) |
c64c03be | 119 | |
1370dba5 S |
120 | # Successful login |
121 | if not redirect_page: | |
122 | return | |
123 | ||
c64c03be XDG |
124 | if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None: |
125 | # TODO: Add mechanism to request an SMS or phone call | |
126 | tfa_token = self._get_tfa_info('two-factor authentication token') | |
5316566e | 127 | login_step(redirect_page, handle, 'Submitting TFA token', { |
c64c03be XDG |
128 | 'authy_token': tfa_token, |
129 | 'remember_2fa': 'true', | |
5316566e | 130 | }) |
17b41a33 | 131 | |
d0e958c7 PH |
132 | def _prefer_source(self, formats): |
133 | try: | |
134 | source = next(f for f in formats if f['format_id'] == 'Source') | |
135 | source['preference'] = 10 | |
136 | except StopIteration: | |
137 | pass # No Source stream present | |
138 | self._sort_formats(formats) | |
139 | ||
c5db6bb3 S |
140 | |
141 | class TwitchItemBaseIE(TwitchBaseIE): | |
142 | def _download_info(self, item, item_id): | |
e3f6b569 S |
143 | return self._extract_info(self._call_api( |
144 | 'kraken/videos/%s%s' % (item, item_id), item_id, | |
c5db6bb3 | 145 | 'Downloading %s info JSON' % self._ITEM_TYPE)) |
a22524b0 | 146 | |
c5db6bb3 S |
147 | def _extract_media(self, item_id): |
148 | info = self._download_info(self._ITEM_SHORTCUT, item_id) | |
e3f6b569 S |
149 | response = self._call_api( |
150 | 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id, | |
c5db6bb3 | 151 | 'Downloading %s playlist JSON' % self._ITEM_TYPE) |
355d074f S |
152 | entries = [] |
153 | chunks = response['chunks'] | |
154 | qualities = list(chunks.keys()) | |
155 | for num, fragment in enumerate(zip(*chunks.values()), start=1): | |
156 | formats = [] | |
157 | for fmt_num, fragment_fmt in enumerate(fragment): | |
158 | format_id = qualities[fmt_num] | |
159 | fmt = { | |
160 | 'url': fragment_fmt['url'], | |
161 | 'format_id': format_id, | |
162 | 'quality': 1 if format_id == 'live' else 0, | |
163 | } | |
164 | m = re.search(r'^(?P<height>\d+)[Pp]', format_id) | |
165 | if m: | |
166 | fmt['height'] = int(m.group('height')) | |
167 | formats.append(fmt) | |
168 | self._sort_formats(formats) | |
169 | entry = dict(info) | |
159444a6 | 170 | entry['id'] = '%s_%d' % (entry['id'], num) |
355d074f S |
171 | entry['title'] = '%s part %d' % (entry['title'], num) |
172 | entry['formats'] = formats | |
173 | entries.append(entry) | |
013bfdd8 | 174 | return self.playlist_result(entries, info['id'], info['title']) |
355d074f S |
175 | |
176 | def _extract_info(self, info): | |
0ff51ada S |
177 | status = info.get('status') |
178 | if status == 'recording': | |
179 | is_live = True | |
180 | elif status == 'recorded': | |
181 | is_live = False | |
182 | else: | |
183 | is_live = None | |
355d074f S |
184 | return { |
185 | 'id': info['_id'], | |
369c12e0 | 186 | 'title': info.get('title') or 'Untitled Broadcast', |
7a6e8a1b S |
187 | 'description': info.get('description'), |
188 | 'duration': int_or_none(info.get('length')), | |
189 | 'thumbnail': info.get('preview'), | |
190 | 'uploader': info.get('channel', {}).get('display_name'), | |
191 | 'uploader_id': info.get('channel', {}).get('name'), | |
192 | 'timestamp': parse_iso8601(info.get('recorded_at')), | |
193 | 'view_count': int_or_none(info.get('views')), | |
0ff51ada | 194 | 'is_live': is_live, |
355d074f S |
195 | } |
196 | ||
c5db6bb3 S |
197 | def _real_extract(self, url): |
198 | return self._extract_media(self._match_id(url)) | |
04d02a9d | 199 | |
04d02a9d | 200 | |
c5db6bb3 S |
201 | class TwitchVideoIE(TwitchItemBaseIE): |
202 | IE_NAME = 'twitch:video' | |
93f78707 | 203 | _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE |
c5db6bb3 S |
204 | _ITEM_TYPE = 'video' |
205 | _ITEM_SHORTCUT = 'a' | |
04d02a9d | 206 | |
c5db6bb3 S |
207 | _TEST = { |
208 | 'url': 'http://www.twitch.tv/riotgames/b/577357806', | |
209 | 'info_dict': { | |
210 | 'id': 'a577357806', | |
211 | 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG', | |
212 | }, | |
213 | 'playlist_mincount': 12, | |
0db3a661 | 214 | 'skip': 'HTTP Error 404: Not Found', |
c5db6bb3 | 215 | } |
04d02a9d | 216 | |
04d02a9d | 217 | |
c5db6bb3 S |
218 | class TwitchChapterIE(TwitchItemBaseIE): |
219 | IE_NAME = 'twitch:chapter' | |
93f78707 | 220 | _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE |
c5db6bb3 S |
221 | _ITEM_TYPE = 'chapter' |
222 | _ITEM_SHORTCUT = 'c' | |
04d02a9d | 223 | |
78111136 | 224 | _TESTS = [{ |
c5db6bb3 S |
225 | 'url': 'http://www.twitch.tv/acracingleague/c/5285812', |
226 | 'info_dict': { | |
227 | 'id': 'c5285812', | |
228 | 'title': 'ACRL Off Season - Sports Cars @ Nordschleife', | |
229 | }, | |
230 | 'playlist_mincount': 3, | |
0db3a661 | 231 | 'skip': 'HTTP Error 404: Not Found', |
78111136 PH |
232 | }, { |
233 | 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361', | |
234 | 'only_matching': True, | |
235 | }] | |
c5db6bb3 S |
236 | |
237 | ||
238 | class TwitchVodIE(TwitchItemBaseIE): | |
239 | IE_NAME = 'twitch:vod' | |
3f1ce168 S |
240 | _VALID_URL = r'''(?x) |
241 | https?:// | |
242 | (?: | |
fce79626 | 243 | (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v|videos)/| |
3f1ce168 S |
244 | player\.twitch\.tv/\?.*?\bvideo=v |
245 | ) | |
246 | (?P<id>\d+) | |
247 | ''' | |
c5db6bb3 S |
248 | _ITEM_TYPE = 'vod' |
249 | _ITEM_SHORTCUT = 'v' | |
250 | ||
9c724a98 | 251 | _TESTS = [{ |
e704f87f | 252 | 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s', |
c5db6bb3 | 253 | 'info_dict': { |
ac0474f8 | 254 | 'id': 'v6528877', |
c5db6bb3 | 255 | 'ext': 'mp4', |
ac0474f8 | 256 | 'title': 'LCK Summer Split - Week 6 Day 1', |
ec85ded8 | 257 | 'thumbnail': r're:^https?://.*\.jpg$', |
ac0474f8 YCH |
258 | 'duration': 17208, |
259 | 'timestamp': 1435131709, | |
260 | 'upload_date': '20150624', | |
261 | 'uploader': 'Riot Games', | |
262 | 'uploader_id': 'riotgames', | |
c5db6bb3 | 263 | 'view_count': int, |
e704f87f | 264 | 'start_time': 310, |
c5db6bb3 S |
265 | }, |
266 | 'params': { | |
267 | # m3u8 download | |
268 | 'skip_download': True, | |
269 | }, | |
9c724a98 S |
270 | }, { |
271 | # Untitled broadcast (title is None) | |
272 | 'url': 'http://www.twitch.tv/belkao_o/v/11230755', | |
273 | 'info_dict': { | |
274 | 'id': 'v11230755', | |
275 | 'ext': 'mp4', | |
276 | 'title': 'Untitled Broadcast', | |
ec85ded8 | 277 | 'thumbnail': r're:^https?://.*\.jpg$', |
9c724a98 S |
278 | 'duration': 1638, |
279 | 'timestamp': 1439746708, | |
280 | 'upload_date': '20150816', | |
281 | 'uploader': 'BelkAO_o', | |
282 | 'uploader_id': 'belkao_o', | |
283 | 'view_count': int, | |
284 | }, | |
285 | 'params': { | |
286 | # m3u8 download | |
287 | 'skip_download': True, | |
288 | }, | |
9bd7bd0b | 289 | 'skip': 'HTTP Error 404: Not Found', |
3f1ce168 S |
290 | }, { |
291 | 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877', | |
292 | 'only_matching': True, | |
0b23c222 S |
293 | }, { |
294 | 'url': 'https://www.twitch.tv/videos/6528877', | |
295 | 'only_matching': True, | |
fce79626 S |
296 | }, { |
297 | 'url': 'https://m.twitch.tv/beagsandjam/v/247478721', | |
298 | 'only_matching': True, | |
9c724a98 | 299 | }] |
04d02a9d | 300 | |
79e93125 | 301 | def _real_extract(self, url): |
c5db6bb3 | 302 | item_id = self._match_id(url) |
e5e99661 | 303 | |
c5db6bb3 | 304 | info = self._download_info(self._ITEM_SHORTCUT, item_id) |
e3f6b569 S |
305 | access_token = self._call_api( |
306 | 'api/vods/%s/access_token' % item_id, item_id, | |
350c9481 | 307 | 'Downloading %s access token' % self._ITEM_TYPE) |
e5e99661 | 308 | |
c5db6bb3 | 309 | formats = self._extract_m3u8_formats( |
350c9481 S |
310 | '%s/vod/%s?%s' % ( |
311 | self._USHER_BASE, item_id, | |
15707c7e | 312 | compat_urllib_parse_urlencode({ |
e5e99661 | 313 | 'allow_source': 'true', |
ac455055 | 314 | 'allow_audio_only': 'true', |
e5e99661 S |
315 | 'allow_spectre': 'true', |
316 | 'player': 'twitchweb', | |
317 | 'nauth': access_token['token'], | |
318 | 'nauthsig': access_token['sig'], | |
319 | })), | |
631d4c87 | 320 | item_id, 'mp4', entry_protocol='m3u8_native') |
e5e99661 | 321 | |
d0e958c7 | 322 | self._prefer_source(formats) |
c5db6bb3 | 323 | info['formats'] = formats |
e704f87f NH |
324 | |
325 | parsed_url = compat_urllib_parse_urlparse(url) | |
326 | query = compat_parse_qs(parsed_url.query) | |
327 | if 't' in query: | |
328 | info['start_time'] = parse_duration(query['t'][0]) | |
329 | ||
264e77c4 S |
330 | if info.get('timestamp') is not None: |
331 | info['subtitles'] = { | |
332 | 'rechat': [{ | |
333 | 'url': update_url_query( | |
334 | 'https://rechat.twitch.tv/rechat-messages', { | |
335 | 'video_id': 'v%s' % item_id, | |
336 | 'start': info['timestamp'], | |
337 | }), | |
338 | 'ext': 'json', | |
339 | }], | |
340 | } | |
341 | ||
c5db6bb3 S |
342 | return info |
343 | ||
344 | ||
345 | class TwitchPlaylistBaseIE(TwitchBaseIE): | |
e3f6b569 | 346 | _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d' |
ececca6c | 347 | _PAGE_LIMIT = 100 |
c5db6bb3 S |
348 | |
349 | def _extract_playlist(self, channel_id): | |
e3f6b569 S |
350 | info = self._call_api( |
351 | 'kraken/channels/%s' % channel_id, | |
c5db6bb3 S |
352 | channel_id, 'Downloading channel info JSON') |
353 | channel_name = info.get('display_name') or info.get('name') | |
354 | entries = [] | |
355 | offset = 0 | |
356 | limit = self._PAGE_LIMIT | |
539a1641 S |
357 | broken_paging_detected = False |
358 | counter_override = None | |
c5db6bb3 | 359 | for counter in itertools.count(1): |
e3f6b569 S |
360 | response = self._call_api( |
361 | self._PLAYLIST_PATH % (channel_id, offset, limit), | |
539a1641 | 362 | channel_id, |
93753aad | 363 | 'Downloading %s JSON page %s' |
539a1641 | 364 | % (self._PLAYLIST_TYPE, counter_override or counter)) |
c2e64f71 S |
365 | page_entries = self._extract_playlist_page(response) |
366 | if not page_entries: | |
c5db6bb3 | 367 | break |
539a1641 S |
368 | total = int_or_none(response.get('_total')) |
369 | # Since the beginning of March 2016 twitch's paging mechanism | |
370 | # is completely broken on the twitch side. It simply ignores | |
371 | # a limit and returns the whole offset number of videos. | |
372 | # Working around by just requesting all videos at once. | |
dec2cae0 | 373 | # Upd: pagination bug was fixed by twitch on 15.03.2016. |
539a1641 S |
374 | if not broken_paging_detected and total and len(page_entries) > limit: |
375 | self.report_warning( | |
dec2cae0 | 376 | 'Twitch pagination is broken on twitch side, requesting all videos at once', |
539a1641 S |
377 | channel_id) |
378 | broken_paging_detected = True | |
a8276b26 | 379 | offset = total |
539a1641 S |
380 | counter_override = '(all at once)' |
381 | continue | |
c2e64f71 | 382 | entries.extend(page_entries) |
539a1641 S |
383 | if broken_paging_detected or total and len(page_entries) >= total: |
384 | break | |
c5db6bb3 | 385 | offset += limit |
c2e64f71 | 386 | return self.playlist_result( |
f0c6c2bc | 387 | [self._make_url_result(entry) for entry in orderedSet(entries)], |
c2e64f71 S |
388 | channel_id, channel_name) |
389 | ||
f0c6c2bc LR |
390 | def _make_url_result(self, url): |
391 | try: | |
392 | video_id = 'v%s' % TwitchVodIE._match_id(url) | |
393 | return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id) | |
394 | except AssertionError: | |
395 | return self.url_result(url) | |
396 | ||
c2e64f71 S |
397 | def _extract_playlist_page(self, response): |
398 | videos = response.get('videos') | |
399 | return [video['url'] for video in videos] if videos else [] | |
c5db6bb3 S |
400 | |
401 | def _real_extract(self, url): | |
402 | return self._extract_playlist(self._match_id(url)) | |
403 | ||
404 | ||
405 | class TwitchProfileIE(TwitchPlaylistBaseIE): | |
406 | IE_NAME = 'twitch:profile' | |
407 | _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE | |
408 | _PLAYLIST_TYPE = 'profile' | |
409 | ||
fce79626 | 410 | _TESTS = [{ |
c5db6bb3 S |
411 | 'url': 'http://www.twitch.tv/vanillatv/profile', |
412 | 'info_dict': { | |
413 | 'id': 'vanillatv', | |
414 | 'title': 'VanillaTV', | |
415 | }, | |
416 | 'playlist_mincount': 412, | |
fce79626 S |
417 | }, { |
418 | 'url': 'http://m.twitch.tv/vanillatv/profile', | |
419 | 'only_matching': True, | |
420 | }] | |
c5db6bb3 S |
421 | |
422 | ||
93753aad S |
423 | class TwitchVideosBaseIE(TwitchPlaylistBaseIE): |
424 | _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE | |
425 | _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type=' | |
426 | ||
427 | ||
428 | class TwitchAllVideosIE(TwitchVideosBaseIE): | |
429 | IE_NAME = 'twitch:videos:all' | |
430 | _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
431 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight' | |
432 | _PLAYLIST_TYPE = 'all videos' | |
433 | ||
fce79626 | 434 | _TESTS = [{ |
93753aad S |
435 | 'url': 'https://www.twitch.tv/spamfish/videos/all', |
436 | 'info_dict': { | |
437 | 'id': 'spamfish', | |
438 | 'title': 'Spamfish', | |
439 | }, | |
440 | 'playlist_mincount': 869, | |
fce79626 S |
441 | }, { |
442 | 'url': 'https://m.twitch.tv/spamfish/videos/all', | |
443 | 'only_matching': True, | |
444 | }] | |
93753aad S |
445 | |
446 | ||
447 | class TwitchUploadsIE(TwitchVideosBaseIE): | |
448 | IE_NAME = 'twitch:videos:uploads' | |
449 | _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
450 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload' | |
451 | _PLAYLIST_TYPE = 'uploads' | |
452 | ||
fce79626 | 453 | _TESTS = [{ |
93753aad S |
454 | 'url': 'https://www.twitch.tv/spamfish/videos/uploads', |
455 | 'info_dict': { | |
456 | 'id': 'spamfish', | |
457 | 'title': 'Spamfish', | |
458 | }, | |
459 | 'playlist_mincount': 0, | |
fce79626 S |
460 | }, { |
461 | 'url': 'https://m.twitch.tv/spamfish/videos/uploads', | |
462 | 'only_matching': True, | |
463 | }] | |
93753aad S |
464 | |
465 | ||
466 | class TwitchPastBroadcastsIE(TwitchVideosBaseIE): | |
467 | IE_NAME = 'twitch:videos:past-broadcasts' | |
468 | _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
469 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive' | |
c5db6bb3 S |
470 | _PLAYLIST_TYPE = 'past broadcasts' |
471 | ||
fce79626 | 472 | _TESTS = [{ |
93753aad S |
473 | 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts', |
474 | 'info_dict': { | |
475 | 'id': 'spamfish', | |
476 | 'title': 'Spamfish', | |
477 | }, | |
478 | 'playlist_mincount': 0, | |
fce79626 S |
479 | }, { |
480 | 'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts', | |
481 | 'only_matching': True, | |
482 | }] | |
93753aad S |
483 | |
484 | ||
485 | class TwitchHighlightsIE(TwitchVideosBaseIE): | |
486 | IE_NAME = 'twitch:videos:highlights' | |
487 | _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE | |
488 | _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight' | |
489 | _PLAYLIST_TYPE = 'highlights' | |
490 | ||
fce79626 | 491 | _TESTS = [{ |
93753aad | 492 | 'url': 'https://www.twitch.tv/spamfish/videos/highlights', |
c5db6bb3 S |
493 | 'info_dict': { |
494 | 'id': 'spamfish', | |
495 | 'title': 'Spamfish', | |
496 | }, | |
93753aad | 497 | 'playlist_mincount': 805, |
fce79626 S |
498 | }, { |
499 | 'url': 'https://m.twitch.tv/spamfish/videos/highlights', | |
500 | 'only_matching': True, | |
501 | }] | |
240b9b7a S |
502 | |
503 | ||
504 | class TwitchStreamIE(TwitchBaseIE): | |
505 | IE_NAME = 'twitch:stream' | |
9db8f6c5 S |
506 | _VALID_URL = r'''(?x) |
507 | https?:// | |
508 | (?: | |
fce79626 | 509 | (?:(?:www|go|m)\.)?twitch\.tv/| |
9db8f6c5 S |
510 | player\.twitch\.tv/\?.*?\bchannel= |
511 | ) | |
512 | (?P<id>[^/#?]+) | |
513 | ''' | |
240b9b7a | 514 | |
faa1f83a | 515 | _TESTS = [{ |
240b9b7a S |
516 | 'url': 'http://www.twitch.tv/shroomztv', |
517 | 'info_dict': { | |
518 | 'id': '12772022048', | |
519 | 'display_id': 'shroomztv', | |
520 | 'ext': 'mp4', | |
521 | 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$', | |
522 | 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV', | |
523 | 'is_live': True, | |
524 | 'timestamp': 1421928037, | |
525 | 'upload_date': '20150122', | |
526 | 'uploader': 'ShroomzTV', | |
527 | 'uploader_id': 'shroomztv', | |
528 | 'view_count': int, | |
529 | }, | |
530 | 'params': { | |
531 | # m3u8 download | |
532 | 'skip_download': True, | |
533 | }, | |
faa1f83a S |
534 | }, { |
535 | 'url': 'http://www.twitch.tv/miracle_doto#profile-0', | |
536 | 'only_matching': True, | |
9db8f6c5 S |
537 | }, { |
538 | 'url': 'https://player.twitch.tv/?channel=lotsofs', | |
539 | 'only_matching': True, | |
b763e1d6 S |
540 | }, { |
541 | 'url': 'https://go.twitch.tv/food', | |
542 | 'only_matching': True, | |
fce79626 S |
543 | }, { |
544 | 'url': 'https://m.twitch.tv/food', | |
545 | 'only_matching': True, | |
faa1f83a | 546 | }] |
240b9b7a | 547 | |
9db8f6c5 S |
548 | @classmethod |
549 | def suitable(cls, url): | |
550 | return (False | |
551 | if any(ie.suitable(url) for ie in ( | |
552 | TwitchVideoIE, | |
553 | TwitchChapterIE, | |
554 | TwitchVodIE, | |
555 | TwitchProfileIE, | |
556 | TwitchAllVideosIE, | |
557 | TwitchUploadsIE, | |
558 | TwitchPastBroadcastsIE, | |
559 | TwitchHighlightsIE)) | |
560 | else super(TwitchStreamIE, cls).suitable(url)) | |
561 | ||
240b9b7a S |
562 | def _real_extract(self, url): |
563 | channel_id = self._match_id(url) | |
564 | ||
e3f6b569 | 565 | stream = self._call_api( |
9aa929d3 | 566 | 'kraken/streams/%s?stream_type=all' % channel_id, channel_id, |
240b9b7a S |
567 | 'Downloading stream JSON').get('stream') |
568 | ||
240b9b7a | 569 | if not stream: |
cc764a6d | 570 | raise ExtractorError('%s is offline' % channel_id, expected=True) |
240b9b7a | 571 | |
06966677 S |
572 | # Channel name may be typed if different case than the original channel name |
573 | # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing | |
574 | # an invalid m3u8 URL. Working around by use of original channel name from stream | |
575 | # JSON and fallback to lowercase if it's not available. | |
1793d71d S |
576 | channel_id = stream.get('channel', {}).get('name') or channel_id.lower() |
577 | ||
e3f6b569 S |
578 | access_token = self._call_api( |
579 | 'api/channels/%s/access_token' % channel_id, channel_id, | |
240b9b7a S |
580 | 'Downloading channel access token') |
581 | ||
582 | query = { | |
583 | 'allow_source': 'true', | |
ac455055 | 584 | 'allow_audio_only': 'true', |
9aa929d3 | 585 | 'allow_spectre': 'true', |
f353cbdb | 586 | 'p': random.randint(1000000, 10000000), |
240b9b7a S |
587 | 'player': 'twitchweb', |
588 | 'segment_preference': '4', | |
d34e7949 S |
589 | 'sig': access_token['sig'].encode('utf-8'), |
590 | 'token': access_token['token'].encode('utf-8'), | |
240b9b7a | 591 | } |
240b9b7a S |
592 | formats = self._extract_m3u8_formats( |
593 | '%s/api/channel/hls/%s.m3u8?%s' | |
15707c7e | 594 | % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)), |
240b9b7a | 595 | channel_id, 'mp4') |
d0e958c7 | 596 | self._prefer_source(formats) |
240b9b7a S |
597 | |
598 | view_count = stream.get('viewers') | |
599 | timestamp = parse_iso8601(stream.get('created_at')) | |
600 | ||
601 | channel = stream['channel'] | |
602 | title = self._live_title(channel.get('display_name') or channel.get('name')) | |
603 | description = channel.get('status') | |
604 | ||
605 | thumbnails = [] | |
606 | for thumbnail_key, thumbnail_url in stream['preview'].items(): | |
607 | m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key) | |
608 | if not m: | |
609 | continue | |
610 | thumbnails.append({ | |
611 | 'url': thumbnail_url, | |
612 | 'width': int(m.group('width')), | |
613 | 'height': int(m.group('height')), | |
614 | }) | |
615 | ||
616 | return { | |
617 | 'id': compat_str(stream['_id']), | |
618 | 'display_id': channel_id, | |
619 | 'title': title, | |
620 | 'description': description, | |
621 | 'thumbnails': thumbnails, | |
622 | 'uploader': channel.get('display_name'), | |
623 | 'uploader_id': channel.get('name'), | |
624 | 'timestamp': timestamp, | |
625 | 'view_count': view_count, | |
626 | 'formats': formats, | |
627 | 'is_live': True, | |
12d1fb5a | 628 | } |
778f9694 S |
629 | |
630 | ||
49fa7de3 | 631 | class TwitchClipsIE(TwitchBaseIE): |
778f9694 S |
632 | IE_NAME = 'twitch:clips' |
633 | _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)' | |
634 | ||
74ba450a | 635 | _TESTS = [{ |
49fa7de3 | 636 | 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat', |
778f9694 S |
637 | 'md5': '761769e1eafce0ffebfb4089cb3847cd', |
638 | 'info_dict': { | |
49fa7de3 | 639 | 'id': '42850523', |
778f9694 S |
640 | 'ext': 'mp4', |
641 | 'title': 'EA Play 2016 Live from the Novo Theatre', | |
ec85ded8 | 642 | 'thumbnail': r're:^https?://.*\.jpg', |
49fa7de3 S |
643 | 'timestamp': 1465767393, |
644 | 'upload_date': '20160612', | |
778f9694 S |
645 | 'creator': 'EA', |
646 | 'uploader': 'stereotype_', | |
49fa7de3 | 647 | 'uploader_id': '43566419', |
778f9694 | 648 | }, |
74ba450a S |
649 | }, { |
650 | # multiple formats | |
651 | 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy', | |
652 | 'only_matching': True, | |
653 | }] | |
778f9694 S |
654 | |
655 | def _real_extract(self, url): | |
656 | video_id = self._match_id(url) | |
657 | ||
49fa7de3 S |
658 | status = self._download_json( |
659 | 'https://clips.twitch.tv/api/v2/clips/%s/status' % video_id, | |
660 | video_id) | |
778f9694 | 661 | |
49fa7de3 | 662 | formats = [] |
778f9694 | 663 | |
49fa7de3 S |
664 | for option in status['quality_options']: |
665 | if not isinstance(option, dict): | |
666 | continue | |
3052a30d S |
667 | source = url_or_none(option.get('source')) |
668 | if not source: | |
49fa7de3 S |
669 | continue |
670 | formats.append({ | |
671 | 'url': source, | |
672 | 'format_id': option.get('quality'), | |
673 | 'height': int_or_none(option.get('quality')), | |
674 | 'fps': int_or_none(option.get('frame_rate')), | |
675 | }) | |
74ba450a | 676 | |
07acdc5a S |
677 | self._sort_formats(formats) |
678 | ||
49fa7de3 S |
679 | info = { |
680 | 'formats': formats, | |
681 | } | |
74ba450a | 682 | |
49fa7de3 S |
683 | clip = self._call_api( |
684 | 'kraken/clips/%s' % video_id, video_id, fatal=False, headers={ | |
685 | 'Accept': 'application/vnd.twitchtv.v5+json', | |
686 | }) | |
778f9694 | 687 | |
49fa7de3 S |
688 | if clip: |
689 | quality_key = qualities(('tiny', 'small', 'medium')) | |
690 | thumbnails = [] | |
691 | thumbnails_dict = clip.get('thumbnails') | |
692 | if isinstance(thumbnails_dict, dict): | |
693 | for thumbnail_id, thumbnail_url in thumbnails_dict.items(): | |
694 | thumbnails.append({ | |
695 | 'id': thumbnail_id, | |
696 | 'url': thumbnail_url, | |
697 | 'preference': quality_key(thumbnail_id), | |
698 | }) | |
699 | ||
700 | info.update({ | |
701 | 'id': clip.get('tracking_id') or video_id, | |
702 | 'title': clip.get('title') or video_id, | |
703 | 'duration': float_or_none(clip.get('duration')), | |
704 | 'views': int_or_none(clip.get('views')), | |
705 | 'timestamp': unified_timestamp(clip.get('created_at')), | |
706 | 'thumbnails': thumbnails, | |
707 | 'creator': try_get(clip, lambda x: x['broadcaster']['display_name'], compat_str), | |
708 | 'uploader': try_get(clip, lambda x: x['curator']['display_name'], compat_str), | |
709 | 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str), | |
710 | }) | |
711 | else: | |
712 | info.update({ | |
713 | 'title': video_id, | |
714 | 'id': video_id, | |
715 | }) | |
0cacae28 | 716 | |
49fa7de3 | 717 | return info |